diff --git a/README.md b/README.md index 974e4bf74..9b7c3da74 100644 --- a/README.md +++ b/README.md @@ -82,11 +82,10 @@ metal2vulkan kernel.ll kernel.spv --profile device.json --emit-meta kernel.json - `--profile` is required: the crate ships no device description. Any Khronos profiles JSON works; [`crates/metal2vulkan-validation/profiles/`](crates/metal2vulkan-validation/profiles) has examples, from a bare Vulkan 1.2 device to desktop GPUs and MoltenVK. A profile compiles under - the runtime's policy (`DevicePolicy::default()`, the identity pointer and handle domains), so a - profile without `bufferDeviceAddress` and `shaderInt64` is refused. `--device FILE` takes its - place with a device description and policy as JSON (`{"description": ..., "policy": ...}`), - which is how a runtime's compile device is reproduced: metal2vulkan-runtime's is the - description restricted to the features it enables, under that policy. + the identity pointer and handle domains, the only form, so a profile without + `bufferDeviceAddress` and `shaderInt64` is refused. `--device FILE` takes its place with a + device description as JSON (`{"description": ...}`), which is how a runtime's compile device is + reproduced: metal2vulkan-runtime's is the description restricted to the features it enables. - Without `--function` it compiles the library's only kernel or vertex function. A kernel with `--color-format` compiles as a tile pipeline. A post-tessellation vertex function adds `.tesc.spv` and `.tese.spv` modules; on a device without `tessellationShader` it answers @@ -117,13 +116,13 @@ The flow follows Metal's object lifecycle: describe the device, parse a library, pipeline, then plan and instantiate each dispatch or draw. ```rust,ignore -use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy}; +use metal2vulkan::device::{Device, DeviceDescription}; use metal2vulkan::library::Library; use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, StageSource}; use metal2vulkan::Budget; let description = DeviceDescription::from_khronos_json(&profile_json, None)?; -let device = Device::from_queries(description, DevicePolicy::default())?; +let device = Device::from_queries(description)?; let library = Library::parse(&metallib_bytes)?; let kernel = FunctionDescriptor::new(library.function("my_kernel")?); let descriptor = ComputePipelineDescriptor::new(StageSource::Function(kernel)); diff --git a/crates/metal2vulkan-harness/src/tests.rs b/crates/metal2vulkan-harness/src/tests.rs index f9500871b..322becb1b 100644 --- a/crates/metal2vulkan-harness/src/tests.rs +++ b/crates/metal2vulkan-harness/src/tests.rs @@ -1403,15 +1403,12 @@ fn the_copy_moves_every_byte_in_whole_threadgroups() { assert_eq!(copy_dispatches(4112), [(0, 1, 256), (4096, 1, 1)]); } -/// The fixture's two cells kernels on lavapipe's `Device::from_queries` profile. Under the -/// resident-table domains both observe their threadgroup partition with -/// partial threadgroups through the lockstep order's barriers, which stand past the bounds test, -/// so they are SIMD-group barriers, as in the row-indexed kernels the fixture stands for. Under the -/// identity domains (the runtime's), whose kernels take no lockstep order, neither observes it, -/// plain or with partial threadgroups. +/// The fixture's two cells kernels on lavapipe's `Device::from_queries` profile, whose kernels take +/// no lockstep order: neither observes its threadgroup partition, plain or with partial +/// threadgroups. #[test] -fn the_cells_kernels_observe_their_partition_only_under_the_lockstep_order() { - use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy}; +fn the_cells_kernels_observe_no_threadgroup_partition() { + use metal2vulkan::device::{Device, DeviceDescription}; use metal2vulkan::library::Library; use metal2vulkan::pipeline::{FunctionDescriptor, LoweringInputs, StageEntries}; let air = match crate::authored::library_air() { @@ -1423,9 +1420,7 @@ fn the_cells_kernels_observe_their_partition_only_under_the_lockstep_order() { }; let json = include_str!("../../metal2vulkan-validation/profiles/lavapipe.json"); let description = DeviceDescription::from_khronos_json(json, None).unwrap(); - let resident = - Device::from_queries(description.clone(), DevicePolicy::RESIDENT_TABLES).unwrap(); - let identity = Device::from_queries(description, DevicePolicy::default()).unwrap(); + let identity = Device::from_queries(description).unwrap(); let library = Library::from_air(&air).unwrap(); let budget = metal2vulkan::Budget::standard(); let mut partial = LoweringInputs::new(); @@ -1437,7 +1432,6 @@ fn the_cells_kernels_observe_their_partition_only_under_the_lockstep_order() { (device.kernel_observes_partition(&function, inputs, &budget, &entries)) .unwrap_or_else(|why| panic!("{name}: {why}")) }; - assert!(observes(&resident, &partial), "{name}: the partial variant"); let own = (identity.compile_function(&function, &LoweringInputs::new(), &budget)) .unwrap_or_else(|why| panic!("{name}: {why}")); assert!( diff --git a/crates/metal2vulkan-runtime/README.md b/crates/metal2vulkan-runtime/README.md index a1060fcc8..837164735 100644 --- a/crates/metal2vulkan-runtime/README.md +++ b/crates/metal2vulkan-runtime/README.md @@ -2380,9 +2380,8 @@ made, with no lock, and never rewritten for layouts. - A texture buffer held as words is read (through a sampler too, and where the function observes its residency), written and asked its width through the words. Its other accesses have no own view to take: the translator refuses, on a device that holds some format as words, a function - that reads or writes a texture buffer in another numeric class than its texture's - (`LoweringInputs::cross_class`, which the runtime never sets), reads an sRGB texture buffer's - codes or writes fewer than four lanes; MSL reaches none of them. + that reads an sRGB texture buffer's codes or writes fewer than four lanes; MSL reaches + neither. - `replace_region` and `get_bytes` of a texture without named bytes go through the staging region: a copy Metal does not make, counted in `Metrics::bytes_copied`. - A blit copy between textures of a compressed region of whole blocks that ends inside one @@ -4449,10 +4448,15 @@ cache is answered compile-required on both. imageblocks from the Apple4 family, and both its guests, x86-64 and arm64, answer no Apple family; - a value from the encoder that the function reads and the identity domains do not source ("an - encoder value the function reads as F", `F` the `PushField`: a texture buffer's bind offset, - `SlotBindOffset`; the draw's `InstanceCount` or `BaseVertexInstance`; a stage-in stride, - `StageInStride`; and the others the translator pushes beside the identity fields): no test - yet; + encoder value the function reads as F", `F` the `PushField`): a descriptor-form slot's residual + bind offset on a device whose kernels do not bind their buffers, `SlotBindOffset`; a bound + instance acceleration structure's `InstanceCount`; the draw's `BaseVertexInstance`; a + stage-in stride, `StageInStride`; a fragment function's depth clamp range, `DepthClampRange`; + a vertex amplification's `AmplificationId`, `AmplificationLayerOffset` and + `AmplificationViewportOffset`; the primitive ID's `VerticesPerPrimitive`, + `CaptureIndexAddress` and `CaptureLayout`; a merged draw replay's `MergedDrawAddress`; a + device-replay dispatch's `ReplayRegionAddress`; and the others the translator pushes beside + the identity fields: no test yet; - a buffer argument not reached through its device address ("a buffer argument not reached through its device address"): no test yet; - a texture argument of a type the identity arrays hold no element of, or whose bound texture's @@ -4473,7 +4477,10 @@ cache is answered compile-required on both. the word of the sampler's resource ID (docs/API.md, Accepted differences): the translator test `under_the_identity_domains_a_runtime_samplers_query_reads_its_pushed_word`; - other state of a bound texture or sampler beyond its resource ID ("state of a bound texture - or sampler beyond its resource ID (F)", `F` the `RuntimeFact`): no test yet; + or sampler beyond its resource ID (F)", `F` the `RuntimeFact`): a sparse texture's residency, + `SparseTexture`; a cube's view shape, `ImageViewShape`; a storage texture's numeric type that + nothing in the function states, `StorageTextureNumericType`; and a texture's swizzle, + `TextureSwizzle`: no test yet; - the residency of a sparse operation on a texture that is not sparse (the `sparse_color` of `sparse_sample`, `sparse_gather` or `sparse_read`): the golden table holds the refusal (`engine/a2_sparse_status`); @@ -4491,8 +4498,8 @@ cache is answered compile-required on both. `a_bicubic_kernel_reads_each_slots_format_treatment_from_its_pushed_field` asserts the text; - a bicubic sample of an extended-range texture through `address::repeat` with a constant texel offset: the golden table holds the refusal (`engine/xr_bicubic`'s `xrb_repeat_offset`); - - an argument buffer's texture of a type the identity arrays hold no element of (a texture - buffer's parts, a cube read as an array, level views, a two-plane, extended-range, RGBX or + - an argument buffer's texture of a type the identity arrays hold no element of (a cube read as + an array, level views, a two-plane, extended-range, RGBX or `ulong` form, or a storage texture with a format), one read through another numeric type than its own or as the raw texels of an extended-range member, a read of one that decodes an extended-range member, and a handle that reads its table entry beyond its element: no test @@ -4501,9 +4508,9 @@ cache is answered compile-required on both. or a sampler argument: the golden table holds the refusal (`engine/kernel_read_through`'s `rt_heap_zero`, `rt_heap_ow` and `rt_heap_arg`); - a sequentially consistent fence (`atomic_thread_fence` of `memory_order_seq_cst` beyond the - thread, or a `seq_cst` barrier whose memory scope is the device), which the translator - orders through a word the identity domains do not reach ("a sequentially consistent - fence"): the translator test + thread, or a `seq_cst` barrier whose memory scope is the device), which Vulkan has no order + for (its memory model reads `SequentiallyConsistent` as acquire-release) ("a sequentially + consistent fence"): the translator test `a_seq_cst_fence_is_refused_naming_its_form_under_the_identity_domains` asserts the text. The states-only plays of the 26 kept replay streams on lavapipe, each making every pipeline state diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs index 4fb07c198..c5795d010 100644 --- a/crates/metal2vulkan-runtime/src/device.rs +++ b/crates/metal2vulkan-runtime/src/device.rs @@ -30,7 +30,7 @@ use crate::submit_calls::SubmitCalls; use crate::times::{StampPools, Ticks}; use crate::visibility::OcclusionPools; use ash::vk; -use metal2vulkan::device::{ApiVersion, DeviceDescription, DevicePolicy}; +use metal2vulkan::device::{ApiVersion, DeviceDescription}; use metal2vulkan::metal::{ArgumentBuffersTier, ReadWriteTextureTier}; use std::cell::Cell; use std::collections::HashMap; @@ -51,11 +51,11 @@ use std::time::{Duration, Instant}; /// /// The runtime runs four threads: the block-maker, which makes the pool's allocations ahead of need /// and the runtime's fixed-size internals (the zero source, the parameter ring's blocks and the -/// staging region) off every caller's thread, and frees device memory; the submit thread, which runs every scheduled -/// handler; the completion thread, which runs every completed handler and listener; and the -/// reaper, which frees the semaphores and command pools the others give up, one at a time, so no -/// driver free runs on the completion thread. The device is torn down when the last handle is -/// dropped: the submit thread submits what is ready and ends what it holds with +/// staging region) off every caller's thread, and frees device memory; the submit thread, which +/// runs every scheduled handler; the completion thread, which runs every completed handler and +/// listener; and the reaper, which frees the semaphores and command pools the others give up, one +/// at a time, so no driver free runs on the completion thread. The device is torn down when the +/// last handle is dropped: the submit thread submits what is ready and ends what it holds with /// [`CommandBufferError::NotRun`](crate::CommandBufferError::NotRun); the completion thread /// retires the rest as the GPU completes it; the threads are joined; then every allocation is /// freed, after [`BlockMappings::unmap`] for each the consumer mapped, and the @@ -65,8 +65,8 @@ use std::time::{Duration, Instant}; /// whose value is reached before the threads end, and every [`BlockMappings`] hook or import /// release the block-maker thread runs, to return: a handler, listener or hook that waits for a /// lock the dropping thread holds never lets the drop return. Where the last handle drops in a -/// handler or a listener, the reaper runs the teardown once the handler returns, and the consumer calls -/// [`Instance::wait_until_devices_torn_down`](crate::Instance::wait_until_devices_torn_down) +/// handler or a listener, the reaper runs the teardown once the handler returns, and the consumer +/// calls [`Instance::wait_until_devices_torn_down`](crate::Instance::wait_until_devices_torn_down) /// before it drops its instance or exits. Nothing relies on a static destructor or an `atexit` /// handler: the consumer drops every handle before the process exits, or, where a handle is still /// out, calls [`quiesce`](Device::quiesce) and ends with `_exit`. `exit()` with a live device is @@ -395,7 +395,8 @@ pub(crate) struct Core { pub(crate) constexprs: Mutex>, /// [`Device::minimum_linear_texture_alignment`]'s answers, one per pixel format asked. pub(crate) linear_alignments: Mutex>, - /// What a texture buffer's offset and width take ([`Device::minimum_texture_buffer_alignment`]). + /// What a texture buffer's offset and width take + /// ([`Device::minimum_texture_buffer_alignment`]). pub(crate) texels: crate::texture::TexelLimits, /// The live textures over a buffer in an image of their own (`crate::over`): while there are /// any, the commands track what they write. @@ -552,13 +553,13 @@ impl Device { /// `MTLCreateSystemDefaultDevice`, for the physical device the consumer chose. /// /// Checks the floor ([`PhysicalDevice::check`]), then makes one `VkDevice` with the floor's - /// features and extensions, each of the optional features and extensions the device has, and each - /// of the consumer's extensions ([`DeviceOptions::extensions`]) the device offers with the - /// features the consumer needs, and chooses its memory types on it. It takes one queue of the floor's queue - /// family for the runtime and, where that family has a second queue, a queue for presenting; - /// where it has one, presenting shares the runtime's queue and its lock. It makes one - /// allocation of each memory class for blocks, then starts the block-maker thread, the submit - /// thread and the completion thread. The block-maker thread's first work, after the call + /// features and extensions, each of the optional features and extensions the device has, and + /// each of the consumer's extensions ([`DeviceOptions::extensions`]) the device offers with the + /// features the consumer needs, and chooses its memory types on it. It takes one queue of the + /// floor's queue family for the runtime and, where that family has a second queue, a queue for + /// presenting; where it has one, presenting shares the runtime's queue and its lock. It makes + /// one allocation of each memory class for blocks, then starts the block-maker thread, the + /// submit thread and the completion thread. The block-maker thread's first work, after the call /// returns, is the runtime's fixed-size internals: the zero source (64 KiB), the parameter /// ring's first block (2 MiB) and the staging region (16 MiB). A call that needs one before it /// is made waits for that make, counted in @@ -607,9 +608,8 @@ impl Device { Some(described) => described(description), None => description, }; - let translator = - (metal2vulkan::device::Device::from_queries(description, DevicePolicy::default())) - .map_err(Error::translation)?; + let translator = (metal2vulkan::device::Device::from_queries(description)) + .map_err(Error::translation)?; let family = capabilities.queue_family; // SAFETY: as above. let families = unsafe { vk_instance.get_physical_device_queue_family_properties(raw) }; @@ -1099,12 +1099,13 @@ impl Device { /// `getDefaultSamplePositions:count:`: where the samples of a pass of `count` samples lie when /// it sets no positions, sample `i` at `i`: Vulkan's standard sample locations, which the /// floor's `standardSampleLocations` makes every pass that sets none rasterize at. At 1, 2, 4 - /// and 8 samples, the counts [`supports_texture_sample_count`](Device::supports_texture_sample_count) - /// can answer, they are Metal's own (an Apple M3 Max, macOS 27.0.1: (0.5, 0.5); (0.75, 0.75), - /// (0.25, 0.25); (0.375, 0.125), (0.875, 0.375), (0.125, 0.625), (0.625, 0.875); and an AMD - /// Radeon Pro 5300M, macOS 26.7.1, at 8: (0.5625, 0.3125), (0.4375, 0.6875), (0.8125, 0.5625), - /// (0.3125, 0.1875), (0.1875, 0.8125), (0.0625, 0.4375), (0.6875, 0.9375), (0.9375, 0.0625)). - /// Metal writes the positions into the caller's array; this returns them. + /// and 8 samples, the counts + /// [`supports_texture_sample_count`](Device::supports_texture_sample_count) can answer, they + /// are Metal's own (an Apple M3 Max, macOS 27.0.1: (0.5, 0.5); (0.75, 0.75), (0.25, 0.25); + /// (0.375, 0.125), (0.875, 0.375), (0.125, 0.625), (0.625, 0.875); and an AMD Radeon Pro 5300M, + /// macOS 26.7.1, at 8: (0.5625, 0.3125), (0.4375, 0.6875), (0.8125, 0.5625), (0.3125, 0.1875), + /// (0.1875, 0.8125), (0.0625, 0.4375), (0.6875, 0.9375), (0.9375, 0.0625)). Metal writes the + /// positions into the caller's array; this returns them. /// /// Err: [`Refusal::DefaultSamplePositions`] for a count the device does not render, where plain /// Metal ends the process. @@ -1181,8 +1182,9 @@ impl Device { /// the runtime for its length. A present in `f` waits only on semaphores whose signal is /// already submitted: the command buffer that presents the image /// ([`CommandBuffer::present_drawable`](crate::CommandBuffer::present_drawable)) is - /// scheduled ([`CommandBuffer::wait_until_scheduled`](crate::CommandBuffer::wait_until_scheduled) - /// has returned for it, or `f` runs in its scheduled handler). + /// scheduled + /// ([`CommandBuffer::wait_until_scheduled`](crate::CommandBuffer::wait_until_scheduled) has + /// returned for it, or `f` runs in its scheduled handler). pub fn with_present_queue(&self, f: impl FnOnce(vk::Queue) -> R) -> R { let queue = lock(&self.shared.core.queues.present); f(*queue) @@ -1254,11 +1256,12 @@ impl Device { /// Err: [`Limit::BlockLen`](crate::Limit::BlockLen) past the device's largest allocation or /// buffer; [`Limit::BlockIds`](crate::Limit::BlockIds); /// [`Limit::MemoryAllocations`](crate::Limit::MemoryAllocations) where the block takes an - /// allocation past the device's count; [`Limit::AllocationNotMapped`](crate::Limit::AllocationNotMapped) - /// where the consumer did not map the allocation the take made; + /// allocation past the device's count; + /// [`Limit::AllocationNotMapped`](crate::Limit::AllocationNotMapped) where the consumer did not + /// map the allocation the take made; /// [`Limit::AllocationAddress`](crate::Limit::AllocationAddress) where the device placed the - /// allocation the take made off a multiple of 16; [`Error::Vulkan`] where the - /// device is out of memory or lost; [`Error::Quiesced`]. + /// allocation the take made off a multiple of 16; [`Error::Vulkan`] where the device is out of + /// memory or lost; [`Error::Quiesced`]. pub fn take_block(&self, class: MemoryClass, len: u64) -> Result { let core = &self.shared.core; if core.closed() { @@ -1271,10 +1274,10 @@ impl Device { } /// No Metal counterpart: stops the runtime's threads and its GPU work, for a process that must - /// end while a handle of the device is still out. True once the GPU went idle and every thread ended - /// within `timeout`; false where the timeout passed first, or the call ran in a handler or a - /// listener (the submit thread, which runs the scheduled handlers, and the completion thread, - /// which runs the completed handlers and listeners, cannot wait for themselves). + /// end while a handle of the device is still out. True once the GPU went idle and every thread + /// ended within `timeout`; false where the timeout passed first, or the call ran in a handler + /// or a listener (the submit thread, which runs the scheduled handlers, and the completion + /// thread, which runs the completed handlers and listeners, cannot wait for themselves). /// /// In order, each wait bounded by `timeout`: the submit thread submits what is ready, ends /// every command buffer it holds or has not yet submitted with @@ -1290,8 +1293,9 @@ impl Device { /// it leaves the blob as it was. After it, no runtime thread touches a block, /// unless the call answered false. A thread past the timeout ends alone: the completion /// thread once the GPU completed what was submitted and it retired that, running its - /// completed handlers, so what the work held goes then. Such a thread is not joined here; the device's last handle joins - /// it, with no deadline, before it destroys anything the thread can reach. + /// completed handlers, so what the work held goes then. Such a thread is not joined here; the + /// device's last handle joins it, with no deadline, before it destroys anything the thread can + /// reach. /// /// It frees nothing: every allocation's memory and mapping stays valid until the process ends, /// or until the device's last handle drops, which then frees it without the hook. Later calls @@ -1583,9 +1587,8 @@ fn join(core: &Arc, threads: Threads) { /// The description of `raw` the translator is made of, with what device creation enables of /// `capabilities`: its Vulkan queries alone, so no driver or GPU identity, and no fact measured on -/// one, applies. `Device::from_queries` makes the translator of it under the identity domains: a -/// buffer argument is the guest's address of the buffer, a push field, and a texture or a sampler -/// its resource ID. +/// one, applies. `Device::from_queries` makes the translator of it: a buffer argument is the +/// guest's address of the buffer, a push field, and a texture or a sampler its resource ID. /// /// # Safety /// @@ -1896,9 +1899,9 @@ impl Drop for Shared { join(core, left); // The blocks the consumer still holds handles of go back to the pool once the threads // have stopped and the consumer's unmap hook has returned for each allocation - // (`halt`), for the core to free; a handle dropped later finds its claim empty. No buffer - // of them is left: the consumer's each hold a handle of the device, and the command - // buffers that kept one have retired. + // (`halt`), for the core to free; a handle dropped later finds its claim empty. No + // buffer of them is left: the consumer's each hold a handle of the device, and the + // command buffers that kept one have retired. let claims: Vec> = lock(&core.claims).drain().map(|(_, c)| c).collect(); let blocks: Vec> = (claims.iter()) .filter_map(Weak::upgrade) diff --git a/crates/metal2vulkan-runtime/src/error.rs b/crates/metal2vulkan-runtime/src/error.rs index 355a7a51c..93808eae7 100644 --- a/crates/metal2vulkan-runtime/src/error.rs +++ b/crates/metal2vulkan-runtime/src/error.rs @@ -1862,16 +1862,6 @@ pub enum RenderPipelineKind { #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum DrawInputCause { - /// A buffer a function reaches through the translator's root table of addresses - /// (`PipelineInterface::needs_pointer_translation`), which the runtime does not build: a draw - /// pushes each buffer's own device address. Metal's counterpart is a device pointer the - /// function reads, which Metal reaches at its `gpuAddress`. - PointerTranslation, - /// A texture or sampler a function resolves through the translator's handle table - /// (`PipelineInterface::needs_handle_translation`), which the runtime does not build: a draw - /// pushes each one's resource ID. Metal's counterpart is a texture or sampler the function - /// reads, which Metal resolves by its `gpuResourceID`. - HandleTranslation, /// A descriptor set of the pipeline's layout that is not the device's: a binding of set 1 /// that is not one of the device's texture and sampler arrays, or a binding of another set. /// Metal has no counterpart: it binds every argument by its index. @@ -1932,16 +1922,6 @@ pub enum DrawInputCause { #[non_exhaustive] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum KernelInputKind { - /// A buffer the kernel reaches through the translator's root table of addresses - /// (`PipelineInterface::needs_pointer_translation`), which the runtime does not build: it - /// pushes each buffer's own device address. Metal's counterpart is a device pointer the - /// kernel reads, which Metal reaches at its `gpuAddress`. - PointerTranslation, - /// A texture or sampler the kernel resolves through the translator's handle table - /// (`PipelineInterface::needs_handle_translation`), which the runtime does not build: it - /// pushes each one's resource ID. Metal's counterpart is a texture or sampler the kernel - /// reads, which Metal resolves by its `gpuResourceID`. - HandleTranslation, /// A descriptor set of the pipeline's layout that is not the device's: a binding of set 1 /// that is not one of the device's texture and sampler arrays, or a binding of another set. /// Metal has no counterpart: it binds every argument by its index. diff --git a/crates/metal2vulkan-runtime/src/pipeline.rs b/crates/metal2vulkan-runtime/src/pipeline.rs index 0d28a21d1..66878f469 100644 --- a/crates/metal2vulkan-runtime/src/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/pipeline.rs @@ -1800,14 +1800,6 @@ pub(crate) fn interface( let subgroups = vk::PipelineShaderStageCreateFlags::REQUIRE_FULL_SUBGROUPS | vk::PipelineShaderStageCreateFlags::ALLOW_VARYING_SUBGROUP_SIZE; let unsupplied = [ - ( - translated.needs_pointer_translation, - KernelInputKind::PointerTranslation, - ), - ( - translated.needs_handle_translation, - KernelInputKind::HandleTranslation, - ), ( views.is_none() || !(pipeline.layout.sets.iter()) diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index 5a2c19b1b..312802409 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -892,8 +892,8 @@ fn constexpr_unstated() -> Error { /// fetching the colours of `arrays` through elements holding 2D array views ([`Draws::arrays`]). /// /// Err: [`Gap::RenderPipeline`] of [`RenderPipelineKind::DrawInput`] for a pipeline that reads -/// what a draw does not supply, its [`DrawInputCause`] naming what: a function table, a pointer or -/// handle translation table, a parameter block longer than a ring chunk, push bytes past the +/// what a draw does not supply, its [`DrawInputCause`] naming what: a function table, a parameter +/// block longer than a ring chunk, push bytes past the /// device's push `window` (`DeviceProfile::push_window`), a push field or bind-time fact the /// encoder does not fill, or an unnormalized constexpr sampler. fn draws( @@ -902,22 +902,8 @@ fn draws( arrays: u8, ) -> Result<(Draws, Numbering), Error> { let translated = &pipeline.interface; - let unsupplied = [ - ( - translated.needs_pointer_translation, - DrawInputCause::PointerTranslation, - ), - ( - translated.needs_handle_translation, - DrawInputCause::HandleTranslation, - ), - ( - !pipeline.layout.sets.iter().all(of_the_device), - DrawInputCause::DescriptorSet, - ), - ]; - if let Some(&(_, cause)) = unsupplied.iter().find(|(reads, _)| *reads) { - return Err(draw_input(cause)); + if !pipeline.layout.sets.iter().all(of_the_device) { + return Err(draw_input(DrawInputCause::DescriptorSet)); } let table = |stage| match stage { Stage::Vertex => Ok(VERTEX), diff --git a/crates/metal2vulkan-runtime/src/tests/feature_enables.rs b/crates/metal2vulkan-runtime/src/tests/feature_enables.rs index cb7987093..3a1fd2224 100644 --- a/crates/metal2vulkan-runtime/src/tests/feature_enables.rs +++ b/crates/metal2vulkan-runtime/src/tests/feature_enables.rs @@ -12,7 +12,7 @@ use crate::floor::{ }; use ash::vk; use metal2vulkan::device::{ - Device, DeviceDescription, DevicePolicy, DeviceProfile, EnableSet, VkExtension, VkFeature, + Device, DeviceDescription, DeviceProfile, EnableSet, VkExtension, VkFeature, KERNEL_BUFFER_BINDINGS, }; use serde_json::Value; @@ -389,7 +389,7 @@ fn read_but_withheld( .map_err(|error| { format!("{name}: the translator's description refuses creation's enables: {error}") })?; - let base = Device::from_queries(created.clone(), DevicePolicy::default()) + let base = Device::from_queries(created.clone()) .map_err(|error| format!("{name}: no translator for creation's enables: {error}"))?; let base = facts(base.profile()); for &feature in VkFeature::ALL { @@ -405,7 +405,7 @@ fn read_but_withheld( else { continue; }; - let Ok(device) = Device::from_queries(with, DevicePolicy::default()) else { + let Ok(device) = Device::from_queries(with) else { continue; }; if facts(device.profile()) != base { diff --git a/crates/metal2vulkan-runtime/src/tests/one_path.rs b/crates/metal2vulkan-runtime/src/tests/one_path.rs index 86c6a2761..650adbd23 100644 --- a/crates/metal2vulkan-runtime/src/tests/one_path.rs +++ b/crates/metal2vulkan-runtime/src/tests/one_path.rs @@ -9,9 +9,8 @@ //! `#[cfg(test)]`, and its inline `#[cfg(test)]` modules. A line [`ALLOWED`] lists may hold what //! the scan finds on it, and no other line may: the device type where unified memory is decided, //! the stage cache's key, the translator's `DeviceDescription` and the two readers that fill it, -//! the translator's `DevicePolicy`, Vulkan's enums mirrored, the registry of the translator's -//! environment variables, the command line's device file, and numbers of a table or a grammar that -//! equal a vendor's ID. +//! Vulkan's enums mirrored, the registry of the translator's environment variables, the command +//! line's device file, and numbers of a table or a grammar that equal a vendor's ID. //! //! A scan cannot see all that rule 2 forbids, and review covers the rest: a policy switch spelled //! as a `bool` field, a constant or a `cfg(feature)` gate reads like any other code, and a `//` @@ -159,12 +158,6 @@ const ALLOWED: &[(&str, &str)] = &[ "metal2vulkan/src/device/khronos.rs", "desc.device_type = p.enum_value(\"deviceType\", vk::PhysicalDeviceType::from_name)?;", ), - // The translator's `DevicePolicy`: its default is the runtime's, and its one other value only - // tests build. - ( - "metal2vulkan/src/device/policy.rs", - "pub struct DevicePolicy {", - ), // Vulkan's driver enum, mirrored and converted. ( "metal2vulkan/src/vk/generated.rs", diff --git a/crates/metal2vulkan-runtime/src/tests/translate.rs b/crates/metal2vulkan-runtime/src/tests/translate.rs index abd03fc05..006573de8 100644 --- a/crates/metal2vulkan-runtime/src/tests/translate.rs +++ b/crates/metal2vulkan-runtime/src/tests/translate.rs @@ -129,14 +129,13 @@ mod on_device { for (which, pipeline) in translated { match pipeline { Ok(pipeline) => eprintln!( - "{name}: {which}: interface {:?}\nconstants {:?}\ndependencies {:?}\nsets {:?}\nflags {:?} subgroup {:?} blob {}", + "{name}: {which}: interface {:?}\nconstants {:?}\ndependencies {:?}\nsets {:?}\nflags {:?} subgroup {:?}", pipeline.interface, pipeline.stage.specialization.constants, pipeline.dependencies, pipeline.layout.sets, pipeline.stage.stage_flags, pipeline.stage.required_subgroup_size, - pipeline.stage.constant_blob.is_some(), ), Err(refused) => eprintln!("{name}: {which}: refused: {refused}"), } diff --git a/crates/metal2vulkan-runtime/src/tests/translator_fields.rs b/crates/metal2vulkan-runtime/src/tests/translator_fields.rs index 3f5273d02..fcf34e4c8 100644 --- a/crates/metal2vulkan-runtime/src/tests/translator_fields.rs +++ b/crates/metal2vulkan-runtime/src/tests/translator_fields.rs @@ -28,9 +28,6 @@ enum Verdict { use Verdict::{Applied, Fact, Refused}; -/// The draw's set-0 bindings, which `draws` refuses (`of_the_device`). -const SET_0: &str = "a set-0 binding, which draws() refuses"; - const GRAPHICS_STATE: &[(&str, Verdict)] = &[ ( "topology", @@ -47,7 +44,6 @@ const GRAPHICS_STATE: &[(&str, Verdict)] = &[ ("alpha_to_one", Applied), ("rasterizer_discard", Applied), ("dynamic_states", Applied), - ("input_attachments", Refused(SET_0)), ( "max_vertex_amplification_count", Refused("refuse() refuses the descriptor's count other than 1"), @@ -136,18 +132,10 @@ const STAGE_MODULE: &[(&str, Verdict)] = &[ ), ("precision_notes", Applied), ("strategies", Fact("a census of the lowering, for coverage")), - ( - "constant_blob", - Fact("under the identity domains the module holds its constant data"), - ), ( "rounded_colors", Fact("what the rounding costs, which the module pays"), ), - ( - "specialized_notes", - Fact("the runtime records every note of precision_notes at creation, these among them"), - ), ("own_pixel_textures", Applied), ( "private_bytes", diff --git a/crates/metal2vulkan-validation/build.rs b/crates/metal2vulkan-validation/build.rs index 6c479fe8b..3cf6c8341 100644 --- a/crates/metal2vulkan-validation/build.rs +++ b/crates/metal2vulkan-validation/build.rs @@ -151,7 +151,6 @@ fn main() { "metal2vulkan/src/device/mechanism.rs", "metal2vulkan/src/device/metal.rs", "metal2vulkan/src/device/mod.rs", - "metal2vulkan/src/device/policy.rs", "metal2vulkan/src/device/profile.rs", "metal2vulkan/src/device/requirements.rs", "metal2vulkan/src/device/subgroup.rs", diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index c68ebc8d2..214106cfb 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -44066e695ea8e4fddb0faea3bc602d1ef37e314cf6716e5d66e14f6715417503 +7f7dcbcbc4a6b43e2c5fb3e192fbc10f4f1d95fc63eefbaa9ef3e1a5494f3b6f diff --git a/crates/metal2vulkan-validation/src/acceptance.rs b/crates/metal2vulkan-validation/src/acceptance.rs index d3200af36..1aeb4de27 100644 --- a/crates/metal2vulkan-validation/src/acceptance.rs +++ b/crates/metal2vulkan-validation/src/acceptance.rs @@ -36,7 +36,7 @@ use crate::worker::compile::{ use crate::worker::{Measured, WorkerFailure}; use metal2vulkan::device::Independence; use metal2vulkan::device::Requirements; -use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile, EnableSet}; +use metal2vulkan::device::{Device, DeviceDescription, DeviceProfile, EnableSet}; use metal2vulkan::error::{DescriptorError, Error, RuntimeInput}; use metal2vulkan::library::{FunctionConstantValues, Library}; use metal2vulkan::pipeline::Stage; @@ -1002,9 +1002,9 @@ pub fn read_at( read } -/// The profile of an opened description ([`opened_description`]) under the default policy. +/// The profile of an opened description ([`opened_description`]). pub fn derived_profile(description: DeviceDescription) -> Result { - Device::from_queries(description, DevicePolicy::default()) + Device::from_queries(description) .map(|device| device.profile().clone()) .map_err(|error| format!("derive the opened device's profile: {error}")) } @@ -1103,11 +1103,8 @@ mod tests { let Some(bitcode) = fixture("kernel_stage_in.ll") else { return; }; - let device = Device::from_queries( - crate::engine::load_description("moltenvk-m3").unwrap(), - DevicePolicy::RESIDENT_TABLES, - ) - .unwrap(); + let device = + Device::from_queries(crate::engine::load_description("moltenvk-m3").unwrap()).unwrap(); let undefined = FunctionConstantValues::defaults(); let implied = stage_inputs::implied_descriptor(&bitcode, "stage_in_fetch", &undefined) .unwrap() @@ -1466,7 +1463,7 @@ mod tests { ] { description.features.remove(&feature); } - Device::from_queries(description, DevicePolicy::default()).unwrap() + Device::from_queries(description).unwrap() }; let compile_on = |device: &Device, entry| compile_row(&bitcode, entry, RowStage::Vertex, device, None); @@ -1672,8 +1669,7 @@ mod tests { /// stage. #[test] fn a_worker_boundary_failure_is_a_stopped_row() { - let device = - WorkerDevice::new(description("runtime-floor"), DevicePolicy::default()).unwrap(); + let device = WorkerDevice::new(description("runtime-floor")).unwrap(); let worker = CompileWorker::program("/nonexistent/compile-worker"); for stage in [RowStage::Kernel, RowStage::Vertex, RowStage::Fragment] { let (row, measured) = compile_row_in_worker( diff --git a/crates/metal2vulkan-validation/src/authored_compile.rs b/crates/metal2vulkan-validation/src/authored_compile.rs index 4ea069e45..03976a2d4 100644 --- a/crates/metal2vulkan-validation/src/authored_compile.rs +++ b/crates/metal2vulkan-validation/src/authored_compile.rs @@ -59,7 +59,7 @@ use crate::store::CorpusStore; use crate::translation_audit::CensusKey; use crate::worker::compile::{CompileWorker, NotCompiled, WorkerDevice}; use crate::worker::{run_json_within, Measured}; -use metal2vulkan::device::{DeviceDescription, DevicePolicy}; +use metal2vulkan::device::DeviceDescription; use rusqlite::{params, Connection}; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; @@ -147,11 +147,10 @@ pub struct CensusProfile { } impl CensusProfile { - /// The committed profile `profile` as the runtime's device describes it, under the default - /// policy. + /// The committed profile `profile` as the runtime's device describes it. pub fn load(profile: &ProfileStem) -> Result { let description = crate::engine::runtime_description(&profile.stem)?; - let device = WorkerDevice::new(description, DevicePolicy::default()) + let device = WorkerDevice::new(description) .map_err(|error| format!("{}: {error}", profile.label()))?; let key = profile_key(&CensusKey::engine( &profile.label(), @@ -500,7 +499,7 @@ struct CaseInput<'a> { root: &'a Path, index: &'a Path, case: &'a AuthoredCase, - profiles: Vec<(&'a DeviceDescription, &'a DevicePolicy)>, + profiles: Vec<&'a DeviceDescription>, } /// A case worker's input, as it reads it. @@ -509,7 +508,7 @@ struct CaseInputOwned { root: PathBuf, index: PathBuf, case: AuthoredCase, - profiles: Vec<(DeviceDescription, DevicePolicy)>, + profiles: Vec, } /// A case worker's report: its cells, and how it found the private sources it read. @@ -529,7 +528,7 @@ impl CaseCompiler for CaseWorkers { case, profiles: profiles .iter() - .map(|profile| (profile.device.description(), profile.device.policy())) + .map(|profile| profile.device.description()) .collect(), }; let run = run_json_within::( @@ -604,8 +603,8 @@ pub fn serve_if_requested() { let devices = input .profiles .into_iter() - .map(|(description, policy)| { - WorkerDevice::new(description, policy).map_err(|error| error.to_string()) + .map(|description| { + WorkerDevice::new(description).map_err(|error| error.to_string()) }) .collect::, _>>()?; let devices = devices.iter().collect::>(); diff --git a/crates/metal2vulkan-validation/src/bin/corpus-pipeline.rs b/crates/metal2vulkan-validation/src/bin/corpus-pipeline.rs index 38247c2fd..038e4379f 100644 --- a/crates/metal2vulkan-validation/src/bin/corpus-pipeline.rs +++ b/crates/metal2vulkan-validation/src/bin/corpus-pipeline.rs @@ -303,11 +303,10 @@ fn run() -> Result<(), String> { } /// The compile device of an engine sweep of profile `stem` as the runtime's device describes it -/// (`engine::runtime_description`), created under the default policy. +/// (`engine::runtime_description`). fn compile_device(stem: &str) -> Result { let description = engine::runtime_description(stem)?; - WorkerDevice::new(description, metal2vulkan::device::DevicePolicy::default()) - .map_err(|error| format!("{stem}: {error}")) + WorkerDevice::new(description).map_err(|error| format!("{stem}: {error}")) } /// What one engine sweep compiles: profile P, and the corpus or the owned fixtures. diff --git a/crates/metal2vulkan-validation/src/candidate/engine.rs b/crates/metal2vulkan-validation/src/candidate/engine.rs index 53c892b6b..8e48ad5a0 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine.rs @@ -941,9 +941,6 @@ pub(crate) fn draw_out_of_bounds_run( .iter() .map(|vertex| (vertex.location, vertex.buffer_index)), ), - resident_roots: pipeline.interface.needs_pointer_translation, - handle_table: pipeline.interface.needs_handle_translation, - policy: *device.policy(), strategies: &graphics::vertex_module(pipeline)?.strategies, // A render stage reaches its buffers at their addresses or through views checked in // the shader. diff --git a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs index 20b442cc2..fedd23cb4 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/artifact/tests.rs @@ -122,7 +122,6 @@ fn the_runtime_sources_are_the_committed_ones() { ("metal2vulkan/src/cache/mod.rs", "the `Hash256` re-export device/derive.rs names a profile's fingerprint with, and RUNTIME_VERSION itself, which cannot be among the sources it versions"), ("metal2vulkan/src/error/mod.rs", "the error vocabulary: the runtime's code decides which error a run reports, and a record keeps the error as reported"), ("metal2vulkan/src/lower/access/imageblock.rs", compile), - ("metal2vulkan/src/lower/access/mod.rs", "compile-time translation, reached only from lower/dispatch.rs's kernel plan, which asks `identity` whether the profile takes the identity domains; what it produces is in the pipeline the artifact digests"), ("metal2vulkan/src/lower/access/tile.rs", "compile-time translation, reached only from the compile-time parts of mixed runtime files; what it produces is in the pipeline the artifact digests"), ("metal2vulkan/src/lower/arith/aggregate.rs", compile), // The block decode (`bind/block_decode.rs`) and its exact division diff --git a/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs index 594e16ae1..4661cba3c 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/graphics/tests.rs @@ -8,7 +8,7 @@ use crate::check::interface::tests::vertex_buffers_at; use crate::executor_contract::depth_stencil_test; use crate::source::public_sources; use crate::store::CorpusStore; -use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy}; +use metal2vulkan::device::{Device, DeviceDescription}; use metal2vulkan::library::FunctionConstantValues; use metal2vulkan_devtools::{fixtures_dir, llvm_assemble, AssembleError}; use std::path::Path; @@ -17,7 +17,7 @@ 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() + Device::from_queries(description).unwrap() } /// The module text a case maps with when its module's stage metadata declares no render target diff --git a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs index 85c0af461..cacdce02e 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/tests.rs @@ -5,17 +5,17 @@ use super::*; use crate::case::ScalarType; use crate::check::admission::NotSupported; use crate::requirement::ToolingRequirement; -use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy}; +use metal2vulkan::device::{Device, DeviceDescription}; use metal2vulkan::metal::DataType; use metal2vulkan::pipeline::PrecisionNote; mod argument_buffer_members; -fn device(stem: &str, policy: DevicePolicy) -> Device { +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, policy).unwrap() + Device::from_queries(description).unwrap() } /// A noted verdict is a noted difference unless the C3 reviewed list holds its case under an @@ -923,8 +923,8 @@ fn texture_arrays_bind_each_element_at_its_slot() { #[test] fn identity_is_per_profile_and_per_engine_slot() { - let a = engine_fingerprint(device("lavapipe", DevicePolicy::RESIDENT_TABLES).profile()); - let b = engine_fingerprint(device("moltenvk-m3", DevicePolicy::RESIDENT_TABLES).profile()); + let a = engine_fingerprint(device("lavapipe").profile()); + let b = engine_fingerprint(device("moltenvk-m3").profile()); assert_ne!(a, b); assert_eq!(a.len(), 64); assert_eq!( diff --git a/crates/metal2vulkan-validation/src/candidate/engine/variants.rs b/crates/metal2vulkan-validation/src/candidate/engine/variants.rs index 56f19f019..c6a4512b5 100644 --- a/crates/metal2vulkan-validation/src/candidate/engine/variants.rs +++ b/crates/metal2vulkan-validation/src/candidate/engine/variants.rs @@ -55,13 +55,13 @@ pub fn compile_kernel( #[cfg(test)] mod tests { use super::*; - use metal2vulkan::device::{DeviceDescription, DevicePolicy}; + use metal2vulkan::device::DeviceDescription; 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() + Device::from_queries(description).unwrap() } /// A dispatch whose threadgroup has a partial simdgroup runs the kernel's emulated-simdgroups diff --git a/crates/metal2vulkan-validation/src/candidate/platform/acceptance.rs b/crates/metal2vulkan-validation/src/candidate/platform/acceptance.rs index 72742fbbb..98b064595 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/acceptance.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/acceptance.rs @@ -18,11 +18,10 @@ use ash::vk; use metal2vulkan::device::Requirements; use metal2vulkan::pipeline::{PipelineLayout, RenderPipeline, StageModule}; -/// The descriptor-set layouts (with their immutable samplers) and the pipeline layout of one +/// The descriptor-set layouts and the pipeline layout of one /// binder `PipelineLayout`, destroyed on every exit path. pub(super) struct LayoutObjects<'a> { device: &'a ash::Device, - samplers: Vec, pub(super) set_layouts: Vec, pub(super) pipeline_layout: vk::PipelineLayout, } @@ -38,9 +37,6 @@ impl Drop for LayoutObjects<'_> { for layout in &self.set_layouts { self.device.destroy_descriptor_set_layout(*layout, None); } - for sampler in &self.samplers { - self.device.destroy_sampler(*sampler, None); - } } } } @@ -105,11 +101,8 @@ pub fn opened_worker_device( .clone() .map_err(ExecutorError::Failed) .and_then(|description| { - crate::worker::compile::WorkerDevice::new( - description, - metal2vulkan::device::DevicePolicy::default(), - ) - .map_err(|error| crate::candidate::engine::product_refusal(&error)) + crate::worker::compile::WorkerDevice::new(description) + .map_err(|error| crate::candidate::engine::product_refusal(&error)) })) }) .map_err(ExecutorError::Failed)? @@ -251,7 +244,7 @@ pub(super) enum LayoutError { } impl<'a> LayoutObjects<'a> { - /// The descriptor-set layouts (with immutable samplers and binding flags) and the pipeline + /// The descriptor-set layouts (with their binding flags) and the pipeline /// layout of `layout`. pub(super) fn create( device: &'a ash::Device, @@ -271,7 +264,6 @@ impl<'a> LayoutObjects<'a> { } let mut objects = LayoutObjects { device, - samplers: Vec::new(), set_layouts: Vec::new(), pipeline_layout: vk::PipelineLayout::null(), }; @@ -284,40 +276,15 @@ impl<'a> LayoutObjects<'a> { /// the driver refusing an object. fn create_layouts(objects: &mut LayoutObjects<'_>, layout: &PipelineLayout) -> Result<(), String> { for set in &layout.sets { - let mut immutable: Vec> = Vec::with_capacity(set.bindings.len()); - for binding in &set.bindings { - let mut samplers = Vec::new(); - if let Some(desc) = &binding.immutable_sampler { - let mut reduction = vk::SamplerReductionModeCreateInfo::default(); - let mut border = vk::SamplerBorderColorComponentMappingCreateInfoEXT::default(); - let info = metal2vulkan::ash_interop::sampler_create_info( - desc, - &mut reduction, - &mut border, - ); - // SAFETY: `info` and its chain are live for the call. - let sampler = unsafe { objects.device.create_sampler(&info, None) } - .map_err(|error| format!("create immutable sampler: {error}"))?; - objects.samplers.push(sampler); - samplers = vec![sampler; binding.count as usize]; - } - immutable.push(samplers); - } let bindings: Vec> = set .bindings .iter() - .zip(&immutable) - .map(|(binding, samplers)| { - let info = vk::DescriptorSetLayoutBinding::default() + .map(|binding| { + vk::DescriptorSetLayoutBinding::default() .binding(binding.binding) .descriptor_type(binding.ty.into()) .descriptor_count(binding.count) - .stage_flags(binding.stages.into()); - if samplers.is_empty() { - info - } else { - info.immutable_samplers(samplers) - } + .stage_flags(binding.stages.into()) }) .collect(); let flags: Vec = diff --git a/crates/metal2vulkan-validation/src/candidate/platform/enables/tests.rs b/crates/metal2vulkan-validation/src/candidate/platform/enables/tests.rs index 71700120e..fa2e759a8 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/enables/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/enables/tests.rs @@ -3,7 +3,7 @@ use crate::acceptance::{derived_profile, opened_description}; use crate::coverage::ROBUSTNESS_FEATURES; use crate::engine::{committed_profiles, load_description}; use metal2vulkan::device::ApiVersion; -use metal2vulkan::device::{Device, DevicePolicy}; +use metal2vulkan::device::Device; use std::collections::BTreeMap; /// What a committed profile states that the engine's vocabulary cannot carry, by the names the @@ -418,7 +418,7 @@ fn the_list_enables_what_the_runtime_enables_of_the_description() { assert_eq!(set, crate::engine::runtime_enables(&description), "{stem}"); let opened = opened_description(description.clone(), &set) .unwrap_or_else(|error| panic!("{stem}: {error}")); - let profile = Device::from_queries(opened, DevicePolicy::default()) + let profile = Device::from_queries(opened) .unwrap_or_else(|error| panic!("{stem}: {error}")) .profile() .clone(); @@ -617,8 +617,7 @@ fn the_list_enables_no_buffer_robustness_and_keeps_the_texel_buffers_update_afte } let opened = opened_description(description.clone(), &set) .unwrap_or_else(|error| panic!("{stem}: {error}")); - Device::from_queries(opened, DevicePolicy::default()) - .unwrap_or_else(|error| panic!("{stem}: {error}")); + Device::from_queries(opened).unwrap_or_else(|error| panic!("{stem}: {error}")); } } @@ -972,8 +971,7 @@ fn a_restricted_context_enables_what_the_runtime_enables_at_its_profiles_version assert_eq!(set, crate::engine::runtime_enables(&description), "{stem}"); let opened = opened_description(description.clone(), &set) .unwrap_or_else(|error| panic!("{stem}: {error}")); - Device::from_queries(opened, DevicePolicy::default()) - .unwrap_or_else(|error| panic!("{stem}: {error}")); + Device::from_queries(opened).unwrap_or_else(|error| panic!("{stem}: {error}")); for structure in enables.linked.iter().filter(|s| s.core_at(version)) { assert!( structure diff --git a/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs b/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs index 0485d3c37..4dc27c44a 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/graphics_pipeline.rs @@ -2,9 +2,8 @@ //! ([`super::acceptance`]) creates it. //! //! Everything comes from the artifact's graphics state and vertex input: the render pass -//! ([`create_render_pass`]: every color attachment at its Metal index, each framebuffer-fetch -//! input as an input attachment of its color attachment with the by-region self-dependency the -//! contract names, and the depth/stencil attachment), the vertex input (static strides, and zero +//! ([`create_render_pass`]: every color attachment at its Metal index, and the depth/stencil +//! attachment), the vertex input (static strides, and zero //! for a stride the pipeline makes dynamic state; instance divisors through the divisor state), //! the multisample, blend and dynamic states. The caller supplies what the artifact leaves to the //! consumer: each stage's specialization, the draw's topology within the compiled class with the @@ -129,48 +128,33 @@ pub(super) fn has_depth(format: vk::Format) -> bool { } /// The render pass of `graphics`: one subpass writing every color attachment at its Metal index -/// (`VK_ATTACHMENT_UNUSED` for an absent one), in `COLOR_ATTACHMENT_OPTIMAL` (`GENERAL` for an -/// attachment a framebuffer-fetch input also reads, as the input attachment of the same index, -/// with the by-region self-dependency of [`FETCH_SELF_DEPENDENCY`]), then the depth/stencil -/// attachment ([`depth_stencil_format`]) in `DEPTH_STENCIL_ATTACHMENT_OPTIMAL`. Every attachment -/// is loaded before and stored after the subpass. The framebuffer's views are the present color -/// attachments in index order, then the depth/stencil one. +/// (`VK_ATTACHMENT_UNUSED` for an absent one), in `COLOR_ATTACHMENT_OPTIMAL`, then the +/// depth/stencil attachment ([`depth_stencil_format`]) in `DEPTH_STENCIL_ATTACHMENT_OPTIMAL`. Every +/// attachment is loaded before and stored after the subpass. The framebuffer's views are the +/// present color attachments in index order, then the depth/stencil one. pub(super) fn create_render_pass( device: &ash::Device, graphics: &GraphicsState, ) -> Result { let samples: vk::SampleCountFlags = graphics.rasterization_samples.into(); - let fetched = |index: u32| { - graphics - .input_attachments - .iter() - .any(|input| input.color_index == index) - }; let mut attachments = Vec::new(); let mut colors = Vec::new(); - let mut numbers = Vec::new(); - for (index, state) in graphics.color_attachments.iter().enumerate() { + for state in &graphics.color_attachments { let Some(state) = state else { colors.push( vk::AttachmentReference::default() .attachment(vk::ATTACHMENT_UNUSED) .layout(vk::ImageLayout::UNDEFINED), ); - numbers.push(None); continue; }; - let layout = if fetched(index as u32) { - vk::ImageLayout::GENERAL - } else { - vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL - }; + let layout = vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL; let number = attachments.len() as u32; colors.push( vk::AttachmentReference::default() .attachment(number) .layout(layout), ); - numbers.push(Some((number, layout))); attachments.push( vk::AttachmentDescription::default() .format(state.format.into()) @@ -183,31 +167,6 @@ pub(super) fn create_render_pass( .final_layout(layout), ); } - let mut inputs = Vec::new(); - for input in &graphics.input_attachments { - let at = input.input_attachment_index as usize; - if inputs.len() <= at { - inputs.resize( - at + 1, - vk::AttachmentReference::default() - .attachment(vk::ATTACHMENT_UNUSED) - .layout(vk::ImageLayout::UNDEFINED), - ); - } - let (number, layout) = numbers - .get(input.color_index as usize) - .copied() - .flatten() - .ok_or_else(|| { - GraphicsError::Unmodelled(format!( - "framebuffer-fetch input {} has no color attachment", - input.color_index - )) - })?; - inputs[at] = vk::AttachmentReference::default() - .attachment(number) - .layout(layout); - } let depth_stencil = depth_stencil_format(graphics)?.map(|format| { let number = attachments.len() as u32; let (depth_op, stencil_op) = ( @@ -245,52 +204,19 @@ pub(super) fn create_render_pass( }); let mut subpass = vk::SubpassDescription::default() .pipeline_bind_point(vk::PipelineBindPoint::GRAPHICS) - .color_attachments(&colors) - .input_attachments(&inputs); + .color_attachments(&colors); if let Some(reference) = depth_stencil.as_ref() { subpass = subpass.depth_stencil_attachment(reference); } let subpasses = [subpass]; - // Framebuffer fetch reads the attachment the same subpass writes: the contract's by-region - // self-dependency. - let scopes = FETCH_SELF_DEPENDENCY; - let dependencies = [vk::SubpassDependency::default() - .src_subpass(0) - .dst_subpass(0) - .src_stage_mask(scopes.0) - .dst_stage_mask(scopes.0) - .src_access_mask(scopes.1) - .dst_access_mask(scopes.2) - .dependency_flags(vk::DependencyFlags::BY_REGION)]; - let mut info = vk::RenderPassCreateInfo::default() + let info = vk::RenderPassCreateInfo::default() .attachments(&attachments) .subpasses(&subpasses); - if !graphics.input_attachments.is_empty() { - info = info.dependencies(&dependencies); - } // SAFETY: `info` and every array it points at are live for the call. unsafe { device.create_render_pass(&info, None) } .map_err(|error| GraphicsError::Refused(format!("create render pass: {error}"))) } -/// The stages and the source and destination accesses of the self-dependency of a subpass whose -/// colors a framebuffer-fetch input reads ([`create_render_pass`]), by region: from the color -/// writes to the input attachment reads (a fetch after an earlier draw's writes, or the load -/// operations'), and from the fragment shader's reads to the color reads and writes (a write -/// after an earlier draw's fetch). -pub(super) const FETCH_SELF_DEPENDENCY: (vk::PipelineStageFlags, vk::AccessFlags, vk::AccessFlags) = ( - vk::PipelineStageFlags::from_raw( - vk::PipelineStageFlags::FRAGMENT_SHADER.as_raw() - | vk::PipelineStageFlags::COLOR_ATTACHMENT_OUTPUT.as_raw(), - ), - vk::AccessFlags::COLOR_ATTACHMENT_WRITE, - vk::AccessFlags::from_raw( - vk::AccessFlags::INPUT_ATTACHMENT_READ.as_raw() - | vk::AccessFlags::COLOR_ATTACHMENT_READ.as_raw() - | vk::AccessFlags::COLOR_ATTACHMENT_WRITE.as_raw(), - ), -); - /// One stage's specialization: its map entries and packed data. pub(super) type Specialization = (Vec, Vec); diff --git a/crates/metal2vulkan-validation/src/candidate/platform/profiles/tests.rs b/crates/metal2vulkan-validation/src/candidate/platform/profiles/tests.rs index ad6fedcf2..4fd7d9bc0 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/profiles/tests.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/profiles/tests.rs @@ -402,13 +402,10 @@ fn a_restricted_context_runs_only_on_a_device_that_has_and_reports_its_profile() assert_eq!(check(&native, &tools, &queried), Ok(translated.clone())); // A profile is every driver's: the profile on lavapipe's identity and on SwiftShader's is one. let profile_of = |description: &DeviceDescription| { - metal2vulkan::device::Device::from_queries( - description.clone(), - metal2vulkan::device::DevicePolicy::default(), - ) - .expect("device") - .profile() - .fingerprint() + metal2vulkan::device::Device::from_queries(description.clone()) + .expect("device") + .profile() + .fingerprint() }; let mut swiftshader_native = native.clone(); swiftshader_native.driver_id = Some(vk::DriverId::GOOGLE_SWIFTSHADER); diff --git a/crates/metal2vulkan-validation/src/candidate/platform/runtime_bounds.rs b/crates/metal2vulkan-validation/src/candidate/platform/runtime_bounds.rs index 29bc5f70d..1ef66b94a 100644 --- a/crates/metal2vulkan-validation/src/candidate/platform/runtime_bounds.rs +++ b/crates/metal2vulkan-validation/src/candidate/platform/runtime_bounds.rs @@ -76,9 +76,6 @@ pub(super) fn contained( stage: lowered.stage(), slots: lowered.slots(), attributes: &attributes, - resident_roots: lowered.reads_resident_roots(), - handle_table: lowered.resolves_handles(), - policy: *translator.policy(), strategies: lowered.strategies(), robust_views: (lowered.requirements().features) .contains(&metal2vulkan::device::VkFeature::PipelineRobustness), diff --git a/crates/metal2vulkan-validation/src/companion/tests.rs b/crates/metal2vulkan-validation/src/companion/tests.rs index 4b855120e..deaa052c0 100644 --- a/crates/metal2vulkan-validation/src/companion/tests.rs +++ b/crates/metal2vulkan-validation/src/companion/tests.rs @@ -867,8 +867,9 @@ fn an_integer_observation_takes_its_sign_from_the_target() { } /// Every companion links with the stage it completes in one engine render pipeline: by user -/// key, at the types the two sides state. Under the resident-table domains, which compile the -/// mesh and object stages the identity domains refuse. +/// key, at the types the two sides state. The mesh companions' pipelines (the launch observer's +/// mesh function under its object function, and the payload object under its mesh function) are +/// refused: the one form compiles no object or mesh stage. #[test] fn generated_companions_link_with_their_cases_in_the_engine() { use metal2vulkan::library::Library; @@ -885,7 +886,6 @@ fn generated_companions_link_with_their_cases_in_the_engine() { }; let device = metal2vulkan::device::Device::from_queries( crate::engine::load_description("lavapipe").unwrap(), - metal2vulkan::device::DevicePolicy::RESIDENT_TABLES, ) .unwrap(); let function = |bitcode: &[u8], entry: &str| { @@ -990,11 +990,7 @@ fn generated_companions_link_with_their_cases_in_the_engine() { descriptor.color_attachments[0] = Some(metal2vulkan::pipeline::ColorAttachmentDescriptor::new( metal2vulkan::metal::PixelFormat::RGBA32Uint, )); - let linked = device - .compile_mesh_pipeline(&descriptor, &metal2vulkan::Budget::standard()) - .unwrap(); - // The object, mesh and fragment stages. - assert!(linked.stages.len() >= 3, "{}", linked.stages.len()); + refused_mesh(device.compile_mesh_pipeline(&descriptor, &metal2vulkan::Budget::standard())); // The payload object under the mesh function that reads its payload, and that mesh // function's fragment partner. @@ -1018,10 +1014,22 @@ fn generated_companions_link_with_their_cases_in_the_engine() { metal2vulkan::metal::PixelFormat::RGBA32Uint, )); } - let linked = device - .compile_mesh_pipeline(&descriptor, &metal2vulkan::Budget::standard()) - .unwrap(); - assert!(linked.stages.len() >= 3, "{}", linked.stages.len()); + refused_mesh(device.compile_mesh_pipeline(&descriptor, &metal2vulkan::Budget::standard())); +} + +/// The one form's refusal of a mesh pipeline: its object and mesh stages are a stage other than a +/// kernel, vertex or fragment function (`IdentityCause::ObjectOrMeshStage`). +fn refused_mesh(r: Result) { + use metal2vulkan::error::{Cause, Error, IdentityCause}; + match r { + Err(Error::Unsupported(u)) => assert_eq!( + u.cause, + Some(Cause::Identity(IdentityCause::ObjectOrMeshStage)), + "{u}" + ), + Err(e) => panic!("the mesh pipeline: {e}"), + Ok(_) => panic!("the mesh pipeline compiled"), + } } /// The typed spelling is what the Metal oracle loads: `metal-as` assembles it, `metal-opt` diff --git a/crates/metal2vulkan-validation/src/coverage/tests.rs b/crates/metal2vulkan-validation/src/coverage/tests.rs index 2555e846b..1e667e2a9 100644 --- a/crates/metal2vulkan-validation/src/coverage/tests.rs +++ b/crates/metal2vulkan-validation/src/coverage/tests.rs @@ -227,15 +227,15 @@ fn the_tier_table_derives_a_robustness_off_leg_from_each_profile() { assert_eq!(robustness_off(&none), None); } -/// A compile records the containment it compiled under, from its profile and its own module: -/// both legs of one copy census the same strategy names under the one buffer encoding, checked -/// (the shader checks every descriptor view); a kernel that declares no image has none; a texture -/// write's image encoding follows the leg's image robustness, and a device that writes a storage -/// image only through its declared format (`runtime-floor` without -/// `shaderStorageImageWriteWithoutFormat`, below the runtime's floor) needs the texture's format -/// first; and a kernel that turns an integer into a pointer (a dynamic root) reaches that memory by -/// device address under names of its own, checked in the shader in both legs, as its descriptor -/// accesses are. +/// A compile records the containment it compiled under, from its profile and its own module. +/// lavapipe binds no kernel buffer (`DeviceProfile::binds_kernel_buffers`), so both legs of one +/// copy reach both buffers at their device addresses, census the same names and declare no buffer +/// variable (`buffers:unused`); a kernel that declares no image has none; a texture write's image +/// encoding follows the leg's image robustness, and a device that writes a storage image only +/// through its declared format (`runtime-floor` without `shaderStorageImageWriteWithoutFormat`, +/// below the runtime's floor) refuses the write, naming the format it lacks; and a kernel that +/// turns an integer into a pointer (a dynamic root) reaches that memory by device address under +/// names of its own, beside its own accesses at their device addresses. #[test] fn a_compile_records_the_containment_it_compiled_under() { use metal2vulkan_devtools::{engine_dir, fixtures_dir, llvm_assemble}; @@ -264,11 +264,21 @@ fn a_compile_records_the_containment_it_compiled_under() { leg("lavapipe", leg_of), ) }; + for leg_of in [Leg::Stated, Leg::RobustnessOff] { + assert!( + !leg("lavapipe", leg_of).binds_kernel_buffers(), + "{leg_of:?}" + ); + } let (stated, off) = (copy(Leg::Stated), copy(Leg::RobustnessOff)); - assert!(stated.strategies.contains("access.memcpy.dynamic")); - assert!(off.strategies.contains("access.memcpy.dynamic")); - assert_eq!(stated.containment, encoding(B::Checked, I::Unused)); - assert_eq!(off.containment, encoding(B::Checked, I::Unused)); + assert!(stated + .strategies + .contains("access.memcpy.dynamic.to_psb.from_psb")); + assert!(off + .strategies + .contains("access.memcpy.dynamic.to_psb.from_psb")); + assert_eq!(stated.containment, encoding(B::Unused, I::Unused)); + assert_eq!(off.containment, encoding(B::Unused, I::Unused)); let write = |stem: &str, leg_of| { compile( @@ -288,22 +298,20 @@ fn a_compile_records_the_containment_it_compiled_under() { assert!(formatted .features .remove(&VkFeature::ShaderStorageImageWriteWithoutFormat)); - let formatted = metal2vulkan::device::Device::from_queries( - formatted, - metal2vulkan::device::DevicePolicy::RESIDENT_TABLES, - ) - .unwrap() - .profile() - .clone(); + let formatted = metal2vulkan::device::Device::from_queries(formatted) + .unwrap() + .profile() + .clone(); match compile_module( &select_write, "a4_select_write", &CaseInputs::defaults(), &formatted, ) { - Err(CompileError::Refused(reason)) => assert!( - reason.starts_with("needs_input StorageTextureFormat"), - "{reason}" + Err(CompileError::Refused(reason)) => assert_eq!( + reason, + "unsupported not_implemented IdentityDomains unsupported: IdentityDomains: \ + StorageTextureFormat; needs NotImplemented" ), other => panic!("a4_select_write without formatless writes: {other:?}"), } @@ -330,14 +338,10 @@ fn a_compile_records_the_containment_it_compiled_under() { assert_eq!( round_trip(leg_of), ( - encoding(B::Checked, I::Unused), - [ - "access.dynamic.load", - "access.load.checked", - "access.store.checked" - ] - .map(String::from) - .into() + encoding(B::Unused, I::Unused), + ["access.dynamic.load", "access.load.psb", "access.store.psb"] + .map(String::from) + .into() ), "{leg_of:?}" ); @@ -414,13 +418,10 @@ fn an_image_encoding_names_what_its_device_is_left() { let mut alone = crate::engine::load_description("runtime-floor").unwrap(); assert!(alone.features.remove(&VkFeature::RobustImageAccess2)); let derive = |description: DeviceDescription| { - metal2vulkan::device::Device::from_queries( - description, - metal2vulkan::device::DevicePolicy::RESIDENT_TABLES, - ) - .unwrap() - .profile() - .clone() + metal2vulkan::device::Device::from_queries(description) + .unwrap() + .profile() + .clone() }; let floor = &table .iter() @@ -472,10 +473,8 @@ fn an_image_encoding_names_what_its_device_is_left() { /// A vertex case's row compiles under the vertex descriptor its executors draw it with. /// `vertex_varying_triangle` reads two `float2` attributes and binds no buffer. Under its -/// descriptor both legs pull them from a storage buffer checked in the shader, as nothing bounds -/// fixed-function input outside the identity domains (VUID-vkCmdDraw-None-02721): the row the -/// executed module belongs to. A fixture entry's default inputs (no descriptor) declare no buffer -/// on either leg. +/// descriptor both legs fetch them by fixed-function vertex input, so the module declares no +/// buffer, as under a fixture entry's default inputs (no descriptor). #[test] fn a_vertex_case_compiles_under_its_vertex_descriptor() { use crate::case::{AttributeFormat, AttributeInput}; @@ -521,7 +520,7 @@ fn a_vertex_case_compiles_under_its_vertex_descriptor() { for leg_of in [Leg::Stated, Leg::RobustnessOff] { assert_eq!( buffers(&inputs, leg(stem, leg_of)), - BufferEncoding::Checked, + BufferEncoding::Unused, "{stem} {leg_of:?}" ); assert_eq!( @@ -619,11 +618,12 @@ fn target(resource: OutOfBoundsResource, form: ContainmentForm) -> OutOfBoundsTa } /// The out-of-bounds fixtures (`engine/ob1_*`) compile each target they declare to the form -/// and mechanism of the inventory on lavapipe, MoltenVK, and the runtime's floor, in both legs: a -/// descriptor view, a texel buffer and a device address checked in the shader on every leg, the -/// arena checked nowhere (no profile checks a threadgroup access), and an image left to the -/// device's image robustness where enabled. The form is the compiled structure's: every leg views -/// the `constant` buffer as a storage buffer. +/// and mechanism of the inventory on lavapipe, MoltenVK, and the runtime's floor, in both legs. +/// None of them binds a kernel buffer (`DeviceProfile::binds_kernel_buffers`), so every buffer is +/// a device address checked in the shader, an atomic one keeping its atomic form; a texel buffer +/// is checked in the shader on every leg, the arena nowhere (no profile checks a threadgroup +/// access), and an image is left to the device's image robustness where enabled. The form is the +/// compiled structure's: a storage or `constant` buffer is reached at its device address. #[test] fn the_out_of_bounds_fixtures_contain_each_target_as_declared() { use metal2vulkan_devtools::{engine_dir, llvm_assemble}; @@ -669,25 +669,23 @@ fn the_out_of_bounds_fixtures_contain_each_target_as_declared() { ], ), ]; - // The mechanism label of each fixture's targets per (stem, leg). - let expected = |fixture: &str, _: &str, leg: Leg| -> &str { + // The mechanism label of each fixture's targets per leg. + let expected = |fixture: &str, leg: Leg| -> &str { match fixture { - "ob1_device_address" => "device-address:shader", "ob1_threadgroup" => "arena:unchecked", "ob1_texture" if leg == Leg::RobustnessOff => "image:shader", "ob1_texture" => "image:robust2", "ob1_texel_buffer" => "texel-buffer:shader", - _ => "descriptor-view:shader", + _ => "device-address:shader", } }; // The form each target is exercised as: the declared one, but a buffer as its compiled slot - // reaches it. `ob1_uniform_buffer`'s `constant` buffer is a storage buffer, which each thread - // reads at its own index: a read whose address may differ between the lanes takes the slot's - // storage view on every device. - let form = |fixture: &str, _: &str, _: Leg, declared: ContainmentForm| match fixture { - "ob1_uniform_buffer" => F::StorageBuffer, + // reaches it, at its device address, where an atomic one stays a buffer atomic. + let form = |declared: ContainmentForm| match declared { + F::StorageBuffer | F::UniformBuffer => F::DeviceAddress, _ => declared, }; + let mut wrong = Vec::new(); for (fixture, targets) in fixtures { let path = engine_dir().join(format!("{fixture}.ll")); let bitcode = llvm_assemble(&path).unwrap_or_else(|error| panic!("{error:?}")); @@ -698,36 +696,32 @@ fn the_out_of_bounds_fixtures_contain_each_target_as_declared() { for entry in table.iter().filter(|entry| { ["lavapipe", "moltenvk-m3", "runtime-floor"].contains(&entry.tier.stem.as_str()) }) { + let label = entry.tier.label(); + assert!(!entry.profile.binds_kernel_buffers(), "{label}"); let compiled = compile_module(&bitcode, fixture, &inputs, &entry.profile) - .unwrap_or_else(|error| panic!("{fixture} on {}: {error:?}", entry.tier.label())); - let want = expected(fixture, &entry.tier.stem, entry.tier.leg); + .unwrap_or_else(|error| panic!("{fixture} on {label}: {error:?}")); + let want = expected(fixture, entry.tier.leg); assert_eq!(compiled.out_of_bounds.len(), targets.len()); for (contained, declared) in compiled.out_of_bounds.iter().zip(&targets) { - assert_eq!( - contained.form, - form(fixture, &entry.tier.stem, entry.tier.leg, declared.form), - "{fixture} on {}", - entry.tier.label() - ); - assert_eq!( - contained.mechanism.label(), - want, - "{fixture} on {}", - entry.tier.label() - ); + let got = (contained.form, contained.mechanism.label()); + if got != (form(declared.form), want.to_string()) { + wrong.push(format!("{fixture} on {label}: {got:?}")); + } } } } + assert!(wrong.is_empty(), "{wrong:#?}"); } -/// The fixtures of the authorable forms (`engine/ob2_*`) compile each target to its form and an -/// in-shader check on every committed profile, in both legs: the buffer a loaded pointer reaches is -/// a device address the resident set resolves, the thread-local array a typed object checked per -/// array level, and the argument buffer's texture array a handle table. A device without device -/// addresses or 64-bit integers refuses the loaded pointer, and one without descriptor indexing the -/// argument buffer's textures, with what it lacks; every committed profile has them. +/// The fixtures of the authorable forms (`engine/ob2_*`) compile each target to its form on every +/// committed profile, in both legs: the buffer a loaded pointer reaches is the device address the +/// pointer holds, used as given and checked nowhere, the thread-local array a typed object checked +/// per array level, and the argument buffer's texture array its resource ids, each index masked +/// onto the descriptor arrays in the shader. A device without device addresses or 64-bit integers +/// refuses the loaded pointer, and one without descriptor indexing the argument buffer's textures, +/// with what it lacks; every committed profile has them. #[test] -fn the_ob2_fixtures_contain_each_target_in_the_shader_on_every_profile() { +fn the_ob2_fixtures_contain_each_target_by_its_form_on_every_profile() { use metal2vulkan_devtools::{engine_dir, llvm_assemble}; use ContainmentForm as F; use OutOfBoundsResource as R; @@ -742,7 +736,7 @@ fn the_ob2_fixtures_contain_each_target_in_the_shader_on_every_profile() { }, F::LoadedPointer, ), - "device-address:shader", + "device-address:unchecked", ), ( "ob2_sized_array", @@ -758,10 +752,11 @@ fn the_ob2_fixtures_contain_each_target_in_the_shader_on_every_profile() { }, F::HandleArrayIndex, ), - "handle-table:shader", + "resource-id:shader", ), ]; let mut refused = BTreeSet::new(); + let mut wrong = Vec::new(); for (fixture, declared, mechanism) in fixtures { let path = engine_dir().join(format!("{fixture}.ll")); let bitcode = llvm_assemble(&path).unwrap_or_else(|error| panic!("{error:?}")); @@ -776,12 +771,10 @@ fn the_ob2_fixtures_contain_each_target_in_the_shader_on_every_profile() { let [contained] = compiled.out_of_bounds.as_slice() else { panic!("{fixture} on {label}: {:?}", compiled.out_of_bounds); }; - assert_eq!(contained.form, declared.form, "{fixture} on {label}"); - assert_eq!( - contained.mechanism.label(), - mechanism, - "{fixture} on {label}" - ); + let got = (contained.form, contained.mechanism.label()); + if got != (declared.form, mechanism.to_string()) { + wrong.push(format!("{fixture} on {label}: {got:?}")); + } } Err(CompileError::Refused(reason)) => { let lacked = match fixture { @@ -798,6 +791,7 @@ fn the_ob2_fixtures_contain_each_target_in_the_shader_on_every_profile() { } } } + assert!(wrong.is_empty(), "{wrong:#?}"); // Every committed profile has device addresses, 64-bit integers and descriptor indexing. assert!(refused.is_empty(), "{refused:?}"); } @@ -903,12 +897,14 @@ fn ob3_case(fixture: &str) -> AuthoredCase { /// The fixtures of the authorable forms (`engine/ob3_*`) compile, under the inputs their cases /// imply (a vertex descriptor, a stage-input descriptor), each target to its declared form and the -/// mechanism of its fetch on every committed profile, in both legs: a vertex input, a control -/// point and a stage input are pulled through a descriptor view checked in the shader (outside -/// the identity domains nothing bounds fixed-function input); an index buffer is drawn from a -/// zero-padded copy; a top-level texture array's index is clamped in the shader. The profiles without `tessellationShader` refuse the control-point draw, -/// a post-tessellation vertex function, and those without vertex stores the vertex draws, which -/// write memory, each a typed refusal; a control point compiles on every other profile. +/// mechanism of its fetch on every committed profile, in both legs: a vertex input is fetched by +/// fixed-function vertex input, which nothing bounds; a control point and a stage input are pulled +/// from their buffer's device address, checked in the shader (a source buffer keeps its device +/// address on every device); an index buffer is drawn from a zero-padded copy; a top-level texture +/// array's index is clamped in the shader. The profiles without `tessellationShader` refuse the +/// control-point draw, a post-tessellation vertex function, and those without vertex stores the +/// vertex draws, which write memory, each a typed refusal; a control point compiles on every other +/// profile. #[test] fn the_ob3_fixtures_contain_each_target_by_its_fetch_on_every_profile() { use metal2vulkan_devtools::{engine_dir, llvm_assemble}; @@ -931,6 +927,7 @@ fn the_ob3_fixtures_contain_each_target_by_its_fetch_on_every_profile() { }) .collect::>(); let mut compiled_rows = 0; + let mut wrong = Vec::new(); for fixture in [ "ob3_vertex_input", "ob3_control_point", @@ -954,9 +951,8 @@ fn the_ob3_fixtures_contain_each_target_by_its_fetch_on_every_profile() { _ => None, }; let expected = match fixture { - "ob3_vertex_input" | "ob3_control_point" | "ob3_stage_input" => { - "descriptor-view:shader" - } + "ob3_vertex_input" => "vertex-input:unchecked", + "ob3_control_point" | "ob3_stage_input" => "device-address:shader", // Every device and leg draws from a zero-padded copy. "ob3_index_buffer" => "index-buffer:padded", _ => "handle-array:shader", @@ -967,12 +963,10 @@ fn the_ob3_fixtures_contain_each_target_by_its_fetch_on_every_profile() { let declared = &case.out_of_bounds.as_ref().unwrap().targets; assert_eq!(compiled.out_of_bounds.len(), declared.len()); for (contained, target) in compiled.out_of_bounds.iter().zip(declared) { - assert_eq!(contained.form, target.form, "{fixture} on {label}"); - assert_eq!( - contained.mechanism.label(), - expected, - "{fixture} on {label}" - ); + let got = (contained.form, contained.mechanism.label()); + if got != (target.form, expected.to_string()) { + wrong.push(format!("{fixture} on {label}: {got:?}")); + } } compiled_rows += 1; } @@ -988,5 +982,6 @@ fn the_ob3_fixtures_contain_each_target_by_its_fetch_on_every_profile() { } } } + assert!(wrong.is_empty(), "{wrong:#?}"); assert!(compiled_rows > 0); } diff --git a/crates/metal2vulkan-validation/src/coverage/tier_table.rs b/crates/metal2vulkan-validation/src/coverage/tier_table.rs index 37d8560a6..d96242ad3 100644 --- a/crates/metal2vulkan-validation/src/coverage/tier_table.rs +++ b/crates/metal2vulkan-validation/src/coverage/tier_table.rs @@ -11,7 +11,7 @@ use crate::check::loop_free::DecodedModule; use crate::engine::{bounded_detail, Outcome}; use crate::executor_contract::out_of_bounds::{self, Mechanism}; use crate::literal::LiteralResources; -use metal2vulkan::device::{Device, DevicePolicy, DeviceProfile}; +use metal2vulkan::device::{Device, DeviceProfile}; use metal2vulkan::error::Error; use metal2vulkan::library::FunctionConstantValues; use metal2vulkan::pipeline::{EntryDescriptor, EntryRef, LoweringInputs}; @@ -65,7 +65,7 @@ pub fn committed_profiles() -> Result, String> { for stem in crate::engine::committed_profiles()? { let description = crate::engine::load_description(&stem)?; let derive = |description: DeviceDescription| { - Device::from_queries(description, DevicePolicy::RESIDENT_TABLES) + Device::from_queries(description) .map(|device| device.profile().clone()) .map_err(|error| format!("{stem}: {error}")) }; @@ -105,10 +105,9 @@ fn is_typed_refusal(outcome: &Outcome) -> bool { } /// What a module compiles with: the function constants, and the vertex descriptor a vertex -/// case's executors draw it with. A vertex function's fetch projection is one of -/// its lowering inputs, decided by the descriptor and the profile (on a leg without buffer -/// robustness every attribute is pulled from a checked storage buffer, so the module declares -/// one), so a case's row compile takes the descriptor its executed module compiled under. +/// case's executors draw it with. A vertex function's fetch projection is one of its lowering +/// inputs, decided by the descriptor and the profile, so a case's row compile takes the +/// descriptor its executed module compiled under. #[derive(Clone, Debug, PartialEq, Eq)] pub struct CaseInputs { pub constants: FunctionConstantValues, @@ -261,10 +260,6 @@ pub fn compile_module( stage: function.stage(), slots: function.slots(), attributes: &attributes, - resident_roots: function.reads_resident_roots(), - handle_table: function.resolves_handles(), - // Every committed profile's device takes the resident-table domains (`committed_profiles`). - policy: DevicePolicy::RESIDENT_TABLES, strategies: function.strategies(), robust_views: (function.requirements().features) .contains(&metal2vulkan::device::VkFeature::PipelineRobustness), diff --git a/crates/metal2vulkan-validation/src/engine.rs b/crates/metal2vulkan-validation/src/engine.rs index d6c4dc840..cc0989dcd 100644 --- a/crates/metal2vulkan-validation/src/engine.rs +++ b/crates/metal2vulkan-validation/src/engine.rs @@ -11,8 +11,7 @@ use crate::l3::L3Failure; use metal2vulkan::device::{ - ApiVersion, DeviceDescription, DevicePolicy, DeviceProfile, EnableSet, Requirements, - VkExtension, + ApiVersion, DeviceDescription, DeviceProfile, EnableSet, Requirements, VkExtension, }; use metal2vulkan::error::{ CanonError, Capability, Error, ErrorClass, Feature, InputError, InputErrorKind, InternalKind, @@ -876,9 +875,10 @@ impl BitcodeError { } /// What an engine translation worker reads of an indexed row: its identity (its key, -/// [`crate::source::SourceRow::key`]), its entry, and where its bitcode comes from. Every lane that translates indexed rows with the engine in a -/// worker sends this (the translation census). A row with retained bitcode carries -/// no AIR text, so neither the parent holding it nor the worker input holds the text. +/// [`crate::source::SourceRow::key`]), its entry, and where its bitcode comes from. Every lane that +/// translates indexed rows with the engine in a worker sends this (the translation census). A row +/// with retained bitcode carries no AIR text, so neither the parent holding it nor the worker input +/// holds the text. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct RowInput<'a> { pub air_sha256: Cow<'a, str>, @@ -992,11 +992,11 @@ pub fn load_profile(stem: &str) -> Result { Ok(load_device(stem)?.profile().clone()) } -/// The engine's `Device` for committed profile `stem` under the default policy (the runtime's), -/// made of [`runtime_description`]: what the public compile API compiles against (its profile is +/// The engine's `Device` for committed profile `stem` (the runtime's), made of +/// [`runtime_description`]: what the public compile API compiles against (its profile is /// [`load_profile`]'s). pub fn load_device(stem: &str) -> Result { - metal2vulkan::device::Device::from_queries(runtime_description(stem)?, DevicePolicy::default()) + metal2vulkan::device::Device::from_queries(runtime_description(stem)?) .map_err(|error| format!("{stem}: {error}")) } @@ -1393,13 +1393,10 @@ mod tests { let mut description = load_description("runtime-floor").unwrap(); description.limits.max_color_attachments = 4; description.limits.max_fragment_output_attachments = 4; - metal2vulkan::device::Device::from_queries( - description, - metal2vulkan::device::DevicePolicy::default(), - ) - .unwrap() - .profile() - .clone() + metal2vulkan::device::Device::from_queries(description) + .unwrap() + .profile() + .clone() }; let lavapipe = load_profile("lavapipe").unwrap(); for (stem, profile, expected) in [ diff --git a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs index eff6690cb..b005f6d59 100644 --- a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs +++ b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds.rs @@ -8,26 +8,24 @@ //! - **The form and mechanism** of each target are what its compiled module does with it, never //! only what the case says ([`containment`]): a buffer is a storage buffer through its //! descriptor, or a device address; a buffer slot the product reaches through a descriptor view -//! and a slot reached by its device address are checked in the shader in every leg, except that a kernel whose buffer arguments are bound as storage buffers of set 0 +//! and a slot reached by its device address are checked in the shader in every leg, except that a +//! kernel whose buffer arguments are bound as storage buffers of set 0 //! (`ModuleFacts::robust_views`) leaves its views' loads and stores to its pipeline's -//! `robustBufferAccess2` and checks only their atomics in the shader; a texel buffer and an image follow the product's texel containment -//! (`DeviceProfile::device_reads_texels` and `device_drops_texel_writes`): a texel buffer is -//! checked in the shader; an image's reads are left to `robustImageAccess2` and its writes to -//! `robustImageAccess` at either level, each otherwise checked in the shader. A buffer reached through a pointer loaded from an argument buffer is a -//! device address the resident set resolves, a thread-local array a typed object whose index is -//! checked against its length, and an argument buffer's texture array a handle table the loaded -//! resource id is looked up in: each checked in the shader in every leg. The threadgroup arena is -//! checked nowhere: no profile checks a threadgroup access, and one past the memory is undefined, -//! as in Metal (docs/API.md, "Threadgroup memory"), so the candidate does not run a case reaching -//! past it ([`Check::Unchecked`]). Under the identity -//! domains (`DevicePolicy`) a loaded pointer is the address it holds, which nothing checks, so -//! the candidate does not run the case ([`Check::Unchecked`]), and a loaded resource id's index -//! is masked onto the descriptor arrays, whose elements no live texture owns are null -//! descriptors. An attribute buffer is fetched by fixed-function vertex input, which nothing -//! bounds ([`Check::Unchecked`]), or pulled in the shader through the slot its fetch names, -//! contained as that slot is ([`Fetch`]); a direct -//! indexed draw's index buffer is bounded by `robustBufferAccess2` or the binder's clamp; and a -//! top-level texture array's dynamic index is clamped onto its elements in the shader. +//! `robustBufferAccess2` and checks only their atomics in the shader; a texel buffer and an image +//! follow the product's texel containment (`DeviceProfile::device_reads_texels` and +//! `device_drops_texel_writes`): a texel buffer is checked in the shader; an image's reads are +//! left to `robustImageAccess2` and its writes to `robustImageAccess` at either level, each +//! otherwise checked in the shader. A thread-local array is a typed object whose index is checked +//! against its length in the shader in every leg. The threadgroup arena is checked nowhere: no profile checks a threadgroup access, and one past the +//! memory is undefined, as in Metal (docs/API.md, "Threadgroup memory"), so the candidate does +//! not run a case reaching past it ([`Check::Unchecked`]). A loaded pointer is the address it +//! holds, which nothing checks, so the candidate does not run the case ([`Check::Unchecked`]), +//! and a loaded resource id's index is masked onto the descriptor arrays, whose elements no live +//! texture owns are null descriptors. An attribute buffer is fetched by fixed-function vertex +//! input, which nothing bounds ([`Check::Unchecked`]), or pulled in the shader through the slot +//! its fetch names, contained as that slot is ([`Fetch`]); a direct indexed draw's index buffer +//! is bounded by `robustBufferAccess2` or the binder's clamp; and a top-level texture array's +//! dynamic index is clamped onto its elements in the shader. //! - **The read rule** ([`read_rule`]) says what an out-of-bounds read of the target may return: //! zero under an in-shader check and under `robustBufferAccess2` (Vulkan's "Robust Buffer //! Access 2": "reads ... outside of the checked range will return zero values"), anything for @@ -54,7 +52,7 @@ use crate::case::{AuthoredCase, OutputSelection}; use crate::coverage::ExecutedCensus; use crate::observation_contract::words::{Judgement, WordFacts}; use base64::Engine as _; -use metal2vulkan::device::{DevicePolicy, DeviceProfile, HandleDomain, PointerDomain}; +use metal2vulkan::device::DeviceProfile; use metal2vulkan::library::CompiledFunction; use metal2vulkan::pipeline::VertexInputState; use metal2vulkan::pipeline::{AttributeFetch, StrategyCensus}; @@ -83,9 +81,9 @@ pub enum Medium { /// The handle table a texture's resource id, loaded from an argument buffer, is looked up in: /// an id of no resident texture is the null handle. HandleTable, - /// The descriptor arrays a texture's resource id, loaded from an argument buffer, indexes - /// under the identity handle domain (`HandleDomain::Identity`), its index masked onto the - /// arrays' elements: an element no live texture owns is the null descriptor. + /// The descriptor arrays a texture's resource id, loaded from an argument buffer, indexes, its + /// index masked onto the arrays' elements: an element no live texture owns is the null + /// descriptor. ResourceId, /// Vulkan's fixed-function vertex input, fetching a vertex buffer binding (only under buffer /// robustness). @@ -121,10 +119,9 @@ pub enum Check { /// position past where Metal's fetch stops reads index 0. Padded, /// Nothing checks the access: neither the shader nor the device's robustness bounds it (a - /// pointer loaded from memory under the identity pointer domain, `PointerDomain::Identity`, - /// is the device address it holds, used as given; fixed-function vertex input on a device - /// without buffer robustness fetches past its buffer what the device gives; and no profile - /// checks a threadgroup access). A run would reach + /// pointer loaded from memory is the device address it holds, used as given; fixed-function + /// vertex input on a device without buffer robustness fetches past its buffer what the device + /// gives; and no profile checks a threadgroup access). A run would reach /// memory no binding gave the case, so the candidate refuses the case before it makes the /// pipeline (`NotSupported::Uncontained`). Unchecked, @@ -336,15 +333,6 @@ pub struct ModuleFacts<'a> { /// How the module (for a render pipeline, the pipeline's vertex input with its module) fetches /// each attribute, by Metal attribute index ([`Fetch`]). pub attributes: &'a BTreeMap, - /// The module reads the resident root table: it has a device-address slot or a dynamic root - /// (`needs_pointer_translation`). - pub resident_roots: bool, - /// The module resolves texture or sampler handles through the handle table - /// (`needs_handle_translation`). - pub handle_table: bool, - /// The pointer and handle domains of the device the module was compiled for - /// (`Device::policy`). - pub policy: DevicePolicy, pub strategies: &'a StrategyCensus, /// The module's storage views are contained by its pipeline's robust buffer access 2, not by /// a check in the shader: a kernel whose buffer arguments are bound as storage buffers of set @@ -396,13 +384,12 @@ mod census { /// buffer, and a `device_address` when it reaches it by its address, except that a /// `buffer_atomic` target (one an AIR atomic accesses, which the case checker establishes) stays /// one in every medium. A buffer an argument buffer points to is a `loaded_pointer` when the -/// module loads a pointer and accesses memory through it, which the resident table checks and the -/// identity pointer domain leaves unchecked ([`Check::Unchecked`]), thread memory a `sized_array` -/// when the module indexes a typed thread-local array at a dynamic index, and an argument buffer's -/// texture array a `handle_array_index` when the module looks its handles up in the handle table, -/// or, under the identity handle domain, masks their ids onto the descriptor arrays. `Err` -/// when the module does not access the target, reaches it in a way validation does not know (thread -/// memory in the private arena, whose check is the arena's bounds, not the array's). +/// module loads a pointer and accesses memory through it, which nothing checks +/// ([`Check::Unchecked`]), thread memory a `sized_array` when the module indexes a typed +/// thread-local array at a dynamic index, and an argument buffer's texture array a +/// `handle_array_index` when the module masks the ids it loads onto the descriptor arrays. `Err` +/// when the module does not access the target, reaches it in a way validation does not know +/// (thread memory in the private arena, whose check is the arena's bounds, not the array's). pub fn containment( target: &OutOfBoundsTarget, module: &ModuleFacts<'_>, @@ -486,16 +473,10 @@ pub fn containment( OutOfBoundsResource::ArgumentBufferBuffer { buffer_binding, .. } => { slot(SlotClass::Buffer, buffer_binding)?; let accessed = module.uses(census::DYNAMIC_LOAD) || module.uses(census::DYNAMIC_STORE); - // Under the resident table the loaded pointer resolves to the resident allocation - // holding it, and each access is checked against that allocation's size in the shader, - // in every leg. Under the identity pointer domain it is the device address it holds, - // used as given: nothing checks the access. - let (resolved, check) = match module.policy.pointer_domain { - PointerDomain::ResidentTable => (module.resident_roots, Check::Shader), - PointerDomain::Identity => (true, Check::Unchecked), - _ => return Err("a pointer domain validation does not know".into()), - }; - if !resolved || !module.uses_family(census::LOAD_POINTER) || !accessed { + // The loaded pointer is the device address it holds, used as given: nothing checks the + // access. + let check = Check::Unchecked; + if !module.uses_family(census::LOAD_POINTER) || !accessed { return Err(format!( "the compiled module accesses no memory through a pointer loaded from {}", target.resource.label() @@ -532,14 +513,9 @@ pub fn containment( } OutOfBoundsResource::ArgumentBufferTextureArray { buffer_binding, .. } => { slot(SlotClass::Buffer, buffer_binding)?; - // The handle table resolves a loaded id to a resident texture or the null handle; the - // identity handle domain masks the id's index onto the descriptor arrays. - let (resolved, medium) = match module.policy.handle_domain { - HandleDomain::Table => (module.handle_table, Medium::HandleTable), - HandleDomain::Identity => (true, Medium::ResourceId), - _ => return Err("a handle domain validation does not know".into()), - }; - if !resolved || !module.uses_family(census::HANDLE_LOOKUP) { + // A loaded id's index is masked onto the descriptor arrays. + let medium = Medium::ResourceId; + if !module.uses_family(census::HANDLE_LOOKUP) { return Err(format!( "the compiled module resolves no handle of {}", target.resource.label() diff --git a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs index 6d2ed40ec..8fe293032 100644 --- a/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs +++ b/crates/metal2vulkan-validation/src/executor_contract/out_of_bounds/tests.rs @@ -695,9 +695,6 @@ fn thread_memory_is_contained_by_the_typed_arrays_check_only() { stage: SymStage::Kernel, slots: &slots, attributes: &BTreeMap::new(), - resident_roots: true, - handle_table: true, - policy: DevicePolicy::RESIDENT_TABLES, strategies: &strategies, robust_views: false, }; @@ -778,9 +775,6 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id( .find(|entry| entry.tier.stem == "lavapipe") .unwrap() .profile; - let mut identity = DevicePolicy::default(); - identity.pointer_domain = PointerDomain::Identity; - identity.handle_domain = HandleDomain::Identity; let slots = BTreeMap::from([( SlotRef { stage: SymStage::Kernel, @@ -808,13 +802,10 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id( .insert(name.into(), StrategyUse::default()); } let attributes = BTreeMap::new(); - let module = |policy| ModuleFacts { + let module = || ModuleFacts { stage: SymStage::Kernel, slots: &slots, attributes: &attributes, - resident_roots: false, - handle_table: false, - policy, strategies: &strategies, robust_views: false, }; @@ -838,7 +829,7 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id( }, ContainmentForm::HandleArrayIndex, ); - let loaded = containment(&pointer, &module(identity), profile).unwrap(); + let loaded = containment(&pointer, &module(), profile).unwrap(); assert_eq!( (loaded.form, loaded.mechanism.label(), loaded.written), ( @@ -847,7 +838,7 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id( false ) ); - let masked = containment(&handles, &module(identity), profile).unwrap(); + let masked = containment(&handles, &module(), profile).unwrap(); assert_eq!( (masked.form, masked.mechanism.label()), ( @@ -859,18 +850,8 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id( read_rule(ContainmentForm::HandleArrayIndex, masked.mechanism, false), ReadRule::ResidentTexels ); - assert!( - containment(&pointer, &module(DevicePolicy::RESIDENT_TABLES), profile) - .unwrap_err() - .contains("no memory through a pointer loaded") - ); - assert!( - containment(&handles, &module(DevicePolicy::RESIDENT_TABLES), profile) - .unwrap_err() - .contains("resolves no handle") - ); // The unchecked target refuses the run, naming its form; the masked one runs. - match out_of_bounds_run(profile, &module(identity), &[pointer, handles.clone()]) { + match out_of_bounds_run(profile, &module(), &[pointer, handles.clone()]) { Err(ExecutorError::NotSupported(refused @ NotSupported::Uncontained { .. })) => { assert_eq!( refused.outcome(), @@ -883,7 +864,7 @@ fn the_identity_domains_leave_a_loaded_pointer_unchecked_and_mask_a_resource_id( } other => panic!("{other:?}"), } - let run = out_of_bounds_run(profile, &module(identity), &[handles]) + let run = out_of_bounds_run(profile, &module(), &[handles]) .unwrap() .unwrap(); assert_eq!(run.targets[0].mechanism, masked.mechanism); @@ -909,9 +890,6 @@ fn a_draws_targets_are_contained_by_their_fetch() { stage, slots: &slots, attributes, - resident_roots: false, - handle_table: false, - policy: DevicePolicy::RESIDENT_TABLES, strategies, robust_views: false, }; @@ -1054,17 +1032,11 @@ fn a_bound_kernel_s_storage_view_is_contained_by_robust_buffer_access_2() { )]); let strategies = StrategyCensus::default(); let attributes = BTreeMap::new(); - let mut identity = DevicePolicy::default(); - identity.pointer_domain = PointerDomain::Identity; - identity.handle_domain = HandleDomain::Identity; let contained = |robust_views, form| { let module = ModuleFacts { stage: SymStage::Kernel, slots: &slots, attributes: &attributes, - resident_roots: false, - handle_table: false, - policy: identity, strategies: &strategies, robust_views, }; @@ -1111,9 +1083,6 @@ fn threadgroup_memory_is_checked_nowhere_and_its_case_is_refused() { let slots = BTreeMap::new(); let attributes = BTreeMap::new(); let strategies = StrategyCensus::default(); - let mut identity = DevicePolicy::default(); - identity.pointer_domain = PointerDomain::Identity; - identity.handle_domain = HandleDomain::Identity; let target = OutOfBoundsTarget { resource: OutOfBoundsResource::ThreadgroupMemory { binding: 0 }, form: ContainmentForm::Threadgroup, @@ -1122,15 +1091,12 @@ fn threadgroup_memory_is_checked_nowhere_and_its_case_is_refused() { }; for committed in &profiles { let profile = &committed.profile; - for policy in [identity, DevicePolicy::RESIDENT_TABLES] { - let what = format!("{} under {policy:?}", committed.tier.label()); + { + let what = committed.tier.label().to_string(); let module = ModuleFacts { stage: SymStage::Kernel, slots: &slots, attributes: &attributes, - resident_roots: false, - handle_table: false, - policy, strategies: &strategies, robust_views: false, }; diff --git a/crates/metal2vulkan-validation/src/specialization/attempt.rs b/crates/metal2vulkan-validation/src/specialization/attempt.rs index 58b575dc4..83d786659 100644 --- a/crates/metal2vulkan-validation/src/specialization/attempt.rs +++ b/crates/metal2vulkan-validation/src/specialization/attempt.rs @@ -884,19 +884,14 @@ mod tests { replay_specialized(bitcode, entry, constants, &profile, None, None).attempt } - /// `description`'s profile under the resident-table domains: the inputs the binder supplies (a - /// storage texture's format, a tile function's member formats) are theirs, and the identity - /// domains refuse what needs them. - fn resident_tables( + /// `description`'s profile (`Device::from_queries`). + fn profile_of( description: metal2vulkan::device::DeviceDescription, ) -> metal2vulkan::device::DeviceProfile { - metal2vulkan::device::Device::from_queries( - description, - metal2vulkan::device::DevicePolicy::RESIDENT_TABLES, - ) - .unwrap() - .profile() - .clone() + metal2vulkan::device::Device::from_queries(description) + .unwrap() + .profile() + .clone() } fn row_plan(bitcode: &[u8], entry: &str) -> RowPlan { @@ -976,14 +971,15 @@ mod tests { assert_eq!(result.supplied, vec![Supplied::StageInputDescriptor]); } - /// A tile function is supplied each implicit imageblock member's format, under the - /// resident-table domains ([`resident_tables`]). + /// A tile function is supplied each implicit imageblock member's format, and its attempt is + /// refused, typed: the one form binds no resource through a descriptor beside a bound kernel's + /// storage views (`IdentityCause::Descriptor`). #[test] fn a_tile_function_is_supplied_its_members_formats() { let Some(bitcode) = bitcode(engine_dir().join("k10ts_tile_order.ll")) else { return; }; - let profile = resident_tables(crate::engine::load_description("moltenvk-m3").unwrap()); + let profile = profile_of(crate::engine::load_description("moltenvk-m3").unwrap()); let result = replay_specialized( &bitcode, "k10ts_tile_order", @@ -1000,7 +996,14 @@ mod tests { }], "{result:?}" ); - assert_eq!(result.attempt.outcome, Outcome::Translated, "{result:?}"); + assert_eq!( + result.attempt.detail.as_deref(), + Some( + "unsupported: IdentityDomains (a resource bound through a descriptor): \ + Descriptor; needs NotImplemented" + ), + "{result:?}" + ); } /// Every derived input crosses the worker boundary and the index as JSON unchanged. @@ -1071,10 +1074,11 @@ mod tests { } /// A storage texture on a profile without formatless storage access (`runtime-floor` without - /// `shaderStorageImageWriteWithoutFormat`, below the runtime's floor) is supplied the widest - /// format of its texel class, under the resident-table domains ([`resident_tables`]). + /// `shaderStorageImageWriteWithoutFormat`, below the runtime's floor) is supplied no format: + /// the one form holds formatless storage images alone, and the attempt is refused, typed + /// (`IdentityCause::StorageTextureFormat`). #[test] - fn a_storage_texture_is_supplied_the_widest_format_of_its_class() { + fn a_storage_texture_below_the_floor_is_refused_its_format() { let Some(bitcode) = bitcode(fixtures_dir().join("kernel_write_one_dimensional_textures.ll")) else { @@ -1084,7 +1088,7 @@ mod tests { assert!(description .features .remove(&metal2vulkan::device::VkFeature::ShaderStorageImageWriteWithoutFormat)); - let profile = resident_tables(description); + let profile = profile_of(description); let result = replay_specialized( &bitcode, "kernel_write_one_dimensional_textures", @@ -1094,16 +1098,10 @@ mod tests { None, ) .attempt; - assert!( - result - .supplied - .iter() - .any(|s| matches!(s, Supplied::StorageTextureFormat { .. })), - "{result:?}" - ); - assert_ne!( - result.attempt.outcome.key(), - "StorageTextureFormat", + assert!(result.supplied.is_empty(), "{result:?}"); + assert_eq!( + result.attempt.detail.as_deref(), + Some("unsupported: IdentityDomains: StorageTextureFormat; needs NotImplemented"), "{result:?}" ); } diff --git a/crates/metal2vulkan-validation/src/worker/compile.rs b/crates/metal2vulkan-validation/src/worker/compile.rs index 3569f24d7..28842faf5 100644 --- a/crates/metal2vulkan-validation/src/worker/compile.rs +++ b/crates/metal2vulkan-validation/src/worker/compile.rs @@ -16,8 +16,8 @@ //! they link, each a [`RowSource`]: its bitcode, or AIR text (a public row that retains none, a //! generated companion) the child assembles with `llvm-as` under its own deadline; the //! [`PipelineRequest`] (kind, entries, function constants, linked functions); and the device's -//! `DeviceDescription` and `DevicePolicy` ([`WorkerDevice`]), from which the child rebuilds the -//! parent's `Device`. The parent writes it to the file that becomes the child's stdin. +//! `DeviceDescription` ([`WorkerDevice`]), from which the child rebuilds the parent's +//! `Device`. The parent writes it to the file that becomes the child's stdin. //! 2. The child ([`serve_if_requested`]) refuses to serve without the counting allocator, sets its //! 500-MiB budget, and compiles through the public API ([`compile_pipeline`]: //! `Device::compile_compute_pipeline` or `Device::compile_render_pipeline`) under a `Budget` @@ -56,7 +56,7 @@ use crate::hash::sha256_bytes; use crate::observation::TRANSLATOR_FINGERPRINT; use crate::ScratchDir; use metal2vulkan::cache::{ArtifactError, PipelineArtifact}; -use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy}; +use metal2vulkan::device::{Device, DeviceDescription}; use metal2vulkan::error::Error; use metal2vulkan::library::FunctionConstantValues; use metal2vulkan::pipeline::{ComputePipeline, RenderPipeline}; @@ -167,25 +167,20 @@ const LIB_TESTS_SERVE: &str = "serve"; #[cfg(test)] const LIB_TESTS_STACK: usize = 8 << 20; -/// The device a worker compiles for: the description and policy the child rebuilds it from, and -/// the parent's `Device` built from exactly that pair, against which the artifact is decoded. +/// The device a worker compiles for: the description the child rebuilds it from, and the parent's +/// `Device` built from exactly that description, against which the artifact is decoded. #[derive(Clone, Debug)] pub struct WorkerDevice { description: DeviceDescription, - policy: DevicePolicy, device: Device, } impl WorkerDevice { - /// Derive the `Device` of `description` under `policy` (`Device::from_queries`'s refusals are its own). - pub fn new( - description: DeviceDescription, - policy: DevicePolicy, - ) -> Result { - let device = Device::from_queries(description.clone(), policy)?; + /// Derive the `Device` of `description` (`Device::from_queries`'s refusals are its own). + pub fn new(description: DeviceDescription) -> Result { + let device = Device::from_queries(description.clone())?; Ok(WorkerDevice { description, - policy, device, }) } @@ -199,11 +194,6 @@ impl WorkerDevice { pub fn description(&self) -> &DeviceDescription { &self.description } - - /// The policy the child rebuilds the `Device` under. - pub fn policy(&self) -> &DevicePolicy { - &self.policy - } } /// Why a worker compile built no pipeline. @@ -275,7 +265,6 @@ pub fn compile_render_request( #[derive(Debug, Serialize, Deserialize)] struct CompileInput<'a> { description: DeviceDescription, - policy: DevicePolicy, request: PipelineRequest, /// The source of each library the compile takes, in the request's order. libraries: Vec>, @@ -416,7 +405,6 @@ fn compile_input<'a>( ) -> CompileInput<'a> { CompileInput { description: device.description.clone(), - policy: device.policy, request: request.clone(), libraries: libraries.to_vec(), } @@ -553,7 +541,7 @@ fn serve( } } } - let device = match Device::from_queries(decoded.description, decoded.policy) { + let device = match Device::from_queries(decoded.description) { Ok(device) => device, Err(error) => return Ok(output(not_compiled(&error), None)), }; @@ -623,11 +611,7 @@ mod tests { } fn worker_device(stem: &str) -> WorkerDevice { - WorkerDevice::new( - crate::engine::load_description(stem).unwrap(), - DevicePolicy::default(), - ) - .unwrap() + WorkerDevice::new(crate::engine::load_description(stem).unwrap()).unwrap() } /// The worker's compile of `input` from `started`, with the artifact it wrote. diff --git a/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs b/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs index ea492162f..f9165f322 100644 --- a/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs +++ b/crates/metal2vulkan-validation/tests/integration/authored_compile_census.rs @@ -277,7 +277,6 @@ fn the_census_refuses_command_buffer_cases_by_their_requirements() { }; let lavapipe = metal2vulkan_validation::worker::compile::WorkerDevice::new( metal2vulkan_validation::engine::load_description("lavapipe").unwrap(), - metal2vulkan::device::DevicePolicy::RESIDENT_TABLES, ) .unwrap(); let (scratch, case) = @@ -297,13 +296,13 @@ fn the_census_refuses_command_buffer_cases_by_their_requirements() { assert_eq!(cells[0].artifact, None, "{cells:?}"); } -/// An object or mesh case, which no candidate draws (`mesh_render_pipeline`), still compiles its -/// mesh render pipeline in the census: a run's preparation refuses the committed public mesh and -/// object cases by that requirement alone, the census's prepares them, and each one's pipeline, -/// its partners' stages with it, compiles in the worker as its one compile. Under the resident-table -/// domains: the identity domains refuse every stage but kernel, vertex and fragment. +/// An object or mesh case, which no candidate draws (`mesh_render_pipeline`), is still attempted +/// in the census: a run's preparation refuses the committed public mesh and object cases by that +/// requirement alone, the census's prepares them, and each one's pipeline, its partners' stages +/// with it, is the worker's one compile, refused, typed: the one form compiles no stage but +/// kernel, vertex and fragment. #[test] -fn the_census_compiles_the_mesh_pipelines_no_candidate_draws() { +fn the_census_refuses_the_mesh_pipelines_no_candidate_draws() { use metal2vulkan_validation::authored_compile::compile_case; use metal2vulkan_validation::candidate::engine::{case_compile, prepare_case, prepare_compile}; use metal2vulkan_validation::check::admission::{ @@ -321,7 +320,6 @@ fn the_census_compiles_the_mesh_pipelines_no_candidate_draws() { }; let lavapipe = metal2vulkan_validation::worker::compile::WorkerDevice::new( metal2vulkan_validation::engine::load_description("lavapipe").unwrap(), - metal2vulkan::device::DevicePolicy::RESIDENT_TABLES, ) .unwrap(); let device = DeviceType::Cpu; @@ -349,9 +347,12 @@ fn the_census_compiles_the_mesh_pipelines_no_candidate_draws() { case_compile(&prepared).unwrap(); let cells = compile_case(scratch.path(), &worker, &case, &[&lavapipe]); assert_eq!(cells.len(), 1, "{name}"); + // The one form compiles no object or mesh stage: the pipeline is refused, typed. assert_eq!( cells[0].outcome, - Ok(CellOutcome::Compiled), + Ok(CellOutcome::Refused( + "not_supported{unsupported:not_implemented IdentityDomains}".into() + )), "{name}: {cells:?}" ); assert_eq!(cells[0].compiles, 1, "{name}"); @@ -375,7 +376,6 @@ fn the_census_compiles_a_texture_buffer_an_argument_buffer_holds() { }; let lavapipe = metal2vulkan_validation::worker::compile::WorkerDevice::new( metal2vulkan_validation::engine::load_description("lavapipe").unwrap(), - metal2vulkan::device::DevicePolicy::default(), ) .unwrap(); let holding = CorpusStore::new(metal2vulkan_validation::source::corpus_root()) diff --git a/crates/metal2vulkan-validation/tests/integration/compile_worker.rs b/crates/metal2vulkan-validation/tests/integration/compile_worker.rs index a6dc17a32..e429d63e7 100644 --- a/crates/metal2vulkan-validation/tests/integration/compile_worker.rs +++ b/crates/metal2vulkan-validation/tests/integration/compile_worker.rs @@ -2,20 +2,17 @@ //! compiles engine pipelines for a device serves the worker, and what comes back through the //! pipeline's cache artifact bytes is the pipeline the public API compiles in process. A pipeline //! holding a constant blob crosses it without the worker copying the blob. - -use metal2vulkan::device::DevicePolicy; use metal2vulkan::library::FunctionConstantValues; -use metal2vulkan::pipeline::ComputePipeline; use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; use metal2vulkan_validation::acceptance::{ compile_draw_in_worker, compile_pipeline, compile_row_in_worker, retained, row, AcceptancePipeline, PipelineRequest, RequestFunction, RowCompile, RowPipeline, RowStage, }; -use metal2vulkan_validation::engine::{load_description, RowSource}; +use metal2vulkan_validation::engine::load_description; use metal2vulkan_validation::worker::compile::{ - compile_compute, CompileWorker, NotCompiled, WorkerCompile, WorkerDevice, + compile_compute, CompileWorker, NotCompiled, WorkerDevice, }; -use metal2vulkan_validation::worker::{WorkerFailure, DEADLINE, MEMORY_LIMIT_BYTES}; +use metal2vulkan_validation::worker::{WorkerFailure, DEADLINE}; use std::path::{Path, PathBuf}; fn fixture(name: &str) -> Option> { @@ -42,7 +39,7 @@ fn worker(program: &Path) -> CompileWorker { } fn device(stem: &str) -> WorkerDevice { - WorkerDevice::new(load_description(stem).unwrap(), DevicePolicy::default()).unwrap() + WorkerDevice::new(load_description(stem).unwrap()).unwrap() } /// Every binary that compiles through the worker serves it (and installs the allocator it @@ -236,114 +233,3 @@ fn a_program_that_does_not_serve_the_worker_is_a_worker_failure() { other => panic!("{other:?}"), } } - -/// A kernel reading two words of `@g`, a closed constant struct DAG `depth` levels deep -/// (`%e1 = { i32, i32 }`, `%e{k} = { %e{k-1}, %e{k-1} }`), all zero: past 14 levels `@g` is in -/// the constant blob, `2^(depth+2)` bytes (the product's `tests/constant_blob_footprint.rs`). -fn blob_kernel(depth: u32) -> String { - let mut types = String::from("%e1 = type { i32, i32 }\n"); - for k in 2..=depth { - types += &format!("%e{k} = type {{ %e{p}, %e{p} }}\n", p = k - 1); - } - format!( - r#"target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" -target triple = "air64_v28-apple-macosx26.0.0" - -{types}@g = internal addrspace(2) constant %e{depth} zeroinitializer, align 4 - -define void @blob(ptr addrspace(1) %out, i32 %t) {{ - %v0 = load i32, ptr addrspace(2) @g, align 4 - %q = getelementptr inbounds i8, ptr addrspace(2) @g, i32 4 - %v1 = load i32, ptr addrspace(2) %q, align 4 - %i0 = shl i32 %t, 1 - %o0 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %i0 - store i32 %v0, ptr addrspace(1) %o0, align 4 - %i1 = add i32 %i0, 1 - %o1 = getelementptr inbounds i32, ptr addrspace(1) %out, i32 %i1 - store i32 %v1, ptr addrspace(1) %o1, align 4 - ret void -}} - -!air.kernel = !{{!0}} -!0 = !{{ptr @blob, !1, !2}} -!1 = !{{}} -!2 = !{{!3, !4}} -!3 = !{{i32 0, !"air.buffer", !"air.location_index", i32 0, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"}} -!4 = !{{i32 1, !"air.thread_index_in_threadgroup", !"air.arg_type_name", !"uint", !"air.arg_name", !"t"}} -"# - ) -} - -/// Compile [`blob_kernel`] `depth` levels deep for `lavapipe` through `corpus-pipeline`'s compile -/// worker (the child assembles the text): the compile, and its blob's length, `2^(depth+2)`. -/// Under the resident-table domains: the identity domains refuse constant data over 64 KiB. -fn compile_blob(depth: u32) -> (WorkerCompile, u64) { - let worker = worker(&bin_exe!("corpus-pipeline")); - let text = blob_kernel(depth); - let compiled = compile_compute( - &worker, - &WorkerDevice::new( - load_description("lavapipe").unwrap(), - DevicePolicy::RESIDENT_TABLES, - ) - .unwrap(), - &RowSource::Text(text.as_str().into()), - "blob", - &FunctionConstantValues::defaults(), - ) - .unwrap_or_else(|failure| panic!("{depth} levels: {}", failure.message())); - let blob = match &compiled.result { - Ok(compiled) => compiled - .stage - .constant_blob - .as_ref() - .map_or(0, |blob| blob.len() as u64), - Err(refused) => panic!("{depth} levels: {refused:?}"), - }; - assert_eq!(blob, 4 << depth, "{depth} levels"); - (compiled, blob) -} - -/// The worker reports a pipeline holding a constant blob without copying the blob: it writes the -/// artifact to the parent's file a chunk at a time, so its process's allocator peak passes its -/// compile's by under a quarter of the blob (4 MiB at 20 levels). Encoding the artifact whole and -/// then as base64 for the report held over twice the blob beside the pipeline. -#[test] -fn a_constant_blob_crosses_the_worker_without_a_copy() { - if fixture("store_const.ll").is_none() { - return; - } - let (compiled, blob) = compile_blob(20); - let process = compiled.measured.allocator_peak_bytes.unwrap(); - let compile = compiled.allocator_peak.unwrap(); - eprintln!("20 levels: process peak {process} bytes, compile peak {compile} bytes, blob {blob}"); - assert!( - process < compile + blob / 4, - "process peak {process} bytes, compile peak {compile} bytes, blob {blob}" - ); -} - -/// The largest closed constant the ledger admits, 26 levels (a 256-MiB blob), compiles through -/// the worker boundary within its ceilings: under 500 MiB, the sampled resident set and the -/// allocator's peak alike, and within the 20-second deadline. The ceilings are release-mode -/// contracts, so this runs in release, ignored otherwise. -#[test] -#[ignore = "a release-mode measurement of the worker's ceilings"] -fn the_largest_admitted_constant_blob_compiles_within_the_worker_ceilings() { - if fixture("store_const.ll").is_none() { - return; - } - let (compiled, blob) = compile_blob(26); - let measured = compiled.measured; - eprintln!( - "26 levels: blob {blob} bytes, {:?}, resident peak {:?} bytes, allocator peak {:?} \ - bytes, compile peak {:?} bytes", - measured.elapsed, - measured.peak_resident_bytes, - measured.allocator_peak_bytes, - compiled.allocator_peak - ); - assert!(measured.elapsed < DEADLINE, "{:?}", measured.elapsed); - let peak = measured.peak_bytes().unwrap(); - assert!(peak < MEMORY_LIMIT_BYTES, "{peak} bytes"); -} diff --git a/crates/metal2vulkan-validation/tests/integration/engine_linked_cases.rs b/crates/metal2vulkan-validation/tests/integration/engine_linked_cases.rs index e56cc6c9e..3dfff66f0 100644 --- a/crates/metal2vulkan-validation/tests/integration/engine_linked_cases.rs +++ b/crates/metal2vulkan-validation/tests/integration/engine_linked_cases.rs @@ -6,7 +6,6 @@ //! it compiles for. No device is opened: the GPU run (Metal and the candidate) is the operator's. use base64::Engine as _; -use metal2vulkan::device::DevicePolicy; use metal2vulkan_devtools::{engine_dir, llvm_assemble, AssembleError}; use metal2vulkan_validation::acceptance::{retained, LinkedLibrary}; use metal2vulkan_validation::candidate::engine::{ @@ -148,8 +147,7 @@ fn a_case_with_visible_function_references_compiles_linked_through_the_worker() let worker = worker(); for stem in ["moltenvk-m3", "runtime-floor", "lavapipe"] { - let device = - WorkerDevice::new(load_description(stem).unwrap(), DevicePolicy::default()).unwrap(); + let device = WorkerDevice::new(load_description(stem).unwrap()).unwrap(); let profile = device.device().profile(); let compile = |linked: &[LinkedModule]| { let (request, libraries) = kernel_request(&retained(&caller), linked, &compute); diff --git a/crates/metal2vulkan/examples/api_preview.rs b/crates/metal2vulkan/examples/api_preview.rs index ba5317478..b42235bfe 100644 --- a/crates/metal2vulkan/examples/api_preview.rs +++ b/crates/metal2vulkan/examples/api_preview.rs @@ -21,7 +21,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; use metal2vulkan::cache::PipelineArtifact; -use metal2vulkan::device::{Device, DeviceDescription, DevicePolicy}; +use metal2vulkan::device::{Device, DeviceDescription}; use metal2vulkan::error::{Error, Needs, RuntimeInput}; use metal2vulkan::library::{ CompiledFunction, FunctionConstantValue, FunctionConstantValues, Library, @@ -69,12 +69,11 @@ fn profile_json(stem: &str) -> Result { )))?) } -/// The device a runtime compiles for on committed profile `stem`: the default policy, the -/// identity domains. +/// The device a runtime compiles for on committed profile `stem`. fn runtime_device(stem: &str) -> Result { let json = profile_json(stem)?; let description = DeviceDescription::from_khronos_json(&json, None)?; - let device = Device::from_queries(description, DevicePolicy::default())?; + let device = Device::from_queries(description)?; Ok(device) } diff --git a/crates/metal2vulkan/src/api_reference.md b/crates/metal2vulkan/src/api_reference.md index 9b2c9bd2d..facddb7e7 100644 --- a/crates/metal2vulkan/src/api_reference.md +++ b/crates/metal2vulkan/src/api_reference.md @@ -35,9 +35,8 @@ This reference shows exactly the API's frozen surface. A walkthrough with a runn # The flow -1. **A device.** Describe the Vulkan device as created ([`device::DeviceDescription`]) and pick a - [`device::DevicePolicy`]; [`device::Device::from_queries`] derives the profile every compile - decides by. +1. **A device.** Describe the Vulkan device as created ([`device::DeviceDescription`]); + [`device::Device::from_queries`] derives the profile every compile decides by. 2. **A library.** [`library::Library::parse`] reads a metallib or AIR bitcode; [`library::Library::function`] finds a function, and [`library::Function::reflection`] answers what its arguments bind, in Metal's shape ([`reflection`]). diff --git a/crates/metal2vulkan/src/ash_interop/query.rs b/crates/metal2vulkan/src/ash_interop/query.rs index d3f9893fe..92407336f 100644 --- a/crates/metal2vulkan/src/ash_interop/query.rs +++ b/crates/metal2vulkan/src/ash_interop/query.rs @@ -1198,14 +1198,12 @@ fn limits(l: &avk::PhysicalDeviceLimits, p: &PropertyChain, chained: &Properties max_per_stage_descriptor_storage_buffers: l.max_per_stage_descriptor_storage_buffers, max_per_stage_descriptor_sampled_images: l.max_per_stage_descriptor_sampled_images, max_per_stage_descriptor_storage_images: l.max_per_stage_descriptor_storage_images, - max_per_stage_descriptor_input_attachments: l.max_per_stage_descriptor_input_attachments, max_per_stage_resources: l.max_per_stage_resources, max_descriptor_set_samplers: l.max_descriptor_set_samplers, max_descriptor_set_uniform_buffers: l.max_descriptor_set_uniform_buffers, max_descriptor_set_storage_buffers: l.max_descriptor_set_storage_buffers, max_descriptor_set_sampled_images: l.max_descriptor_set_sampled_images, max_descriptor_set_storage_images: l.max_descriptor_set_storage_images, - max_descriptor_set_input_attachments: l.max_descriptor_set_input_attachments, max_descriptor_set_update_after_bind_samplers: v12 .max_descriptor_set_update_after_bind_samplers, max_descriptor_set_update_after_bind_sampled_images: v12 diff --git a/crates/metal2vulkan/src/ash_interop/tests.rs b/crates/metal2vulkan/src/ash_interop/tests.rs index faa46189b..17f97d23c 100644 --- a/crates/metal2vulkan/src/ash_interop/tests.rs +++ b/crates/metal2vulkan/src/ash_interop/tests.rs @@ -17,7 +17,7 @@ use super::query::{ use crate::device::description::FormatProperties; use crate::device::profile::Independence; use crate::device::requirements::{ApiVersion, VkExtension, VkFeature}; -use crate::device::{AllocationLimits, Device, DeviceDescription, DevicePolicy, FormatSupport}; +use crate::device::{AllocationLimits, Device, DeviceDescription, FormatSupport}; use crate::error::{Capability, Error, Feature, Unsupported}; use crate::vk; @@ -1155,7 +1155,7 @@ fn a_queried_description_derives_a_device() { dev.v11_props.subgroup_supported_stages = avk::ShaderStageFlags::ALL; dev.v11_props.subgroup_supported_operations = avk::SubgroupFeatureFlags::from_raw(0xff); let desc = dev.query().unwrap(); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("queried description derives"); + Device::from_queries(desc).expect("queried description derives"); } #[test] diff --git a/crates/metal2vulkan/src/bind/heap.rs b/crates/metal2vulkan/src/bind/heap.rs index 8378525c5..f7be7f62b 100644 --- a/crates/metal2vulkan/src/bind/heap.rs +++ b/crates/metal2vulkan/src/bind/heap.rs @@ -22,8 +22,6 @@ //! - [`storage_conversions`]: the aliases a storage access through a handle converts by (an 8-bit //! sRGB texture's UNORM twin, a blue-first texture's RGBA-order twin), where the handle carries //! the texture's class and red-blue order. -//! - The bits of `SpecKey::HeapRawTextures` ([`HELD`], [`FILTERED`]) and of -//! `SpecKey::HeapNanFamilies` ([`NAN_SIXTEEN`], [`NAN_WIDE`], [`NAN_SMALL`], [`NAN_OTHER`]). use std::collections::{BTreeMap, BTreeSet}; @@ -236,32 +234,6 @@ pub(crate) fn raw_held(shape: &TextureShape) -> bool { .is_some() } -/// The bit of `SpecKey::HeapRawTextures`' value that a texture the stage's handles can name is held -/// by its raw texels alone, whose decode the function's `float` read, sample or -/// gather takes (`lower::texture::heap_raw`). -pub(crate) const HELD: u32 = 1; - -/// The bit of `SpecKey::HeapRawTextures`' value that such a texture is of a form whose sample the -/// function filters (`lower::sampler::heap_raw`): every form of `ExtendedRange::HEAP_READ` but a -/// bfloat one, whose sample reads the nearest texel under either filter. -pub(crate) const FILTERED: u32 = 2; - -/// The bit of `SpecKey::HeapNanFamilies` of a 16-bit float format: its written NaN, a `half`'s or -/// a `float`'s, is the device's conversion's. -pub(crate) const NAN_SIXTEEN: u32 = 1; - -/// The bit of `SpecKey::HeapNanFamilies` of a 32-bit float format: its written `half` NaN is the -/// device's widening's. -pub(crate) const NAN_WIDE: u32 = 2; - -/// The bit of `SpecKey::HeapNanFamilies` of a packed small float format (`RG11B10Float`, -/// `RGB9E5Float`): its written NaN is the device's conversion's. -pub(crate) const NAN_SMALL: u32 = 4; - -/// The bit of `SpecKey::HeapNanFamilies` of a float format of none of those families whose texels -/// may hold a NaN: its written NaN is the device's. -pub(crate) const NAN_OTHER: u32 = 8; - /// The format of the view through which the storage heap array of `class` holds a member of /// facts `shape` on `profile`: the direct format (an `A8Unorm` texture held in red its /// `R8_UNORM` image), which the class's formatless declaration must serve. A member whose choice diff --git a/crates/metal2vulkan/src/bind/heap/tests.rs b/crates/metal2vulkan/src/bind/heap/tests.rs index 8115cf9ef..8cda91a39 100644 --- a/crates/metal2vulkan/src/bind/heap/tests.rs +++ b/crates/metal2vulkan/src/bind/heap/tests.rs @@ -27,7 +27,6 @@ fn class( fn shape(ty: TextureType, pf: PixelFormat, samples: u32, usage: TextureUsage) -> TextureShape { TextureShape::Texture { - address_modes: crate::metal::sampler::AddressModeMap::IDENTITY, offset_base_axes: 0, texture_type: ty, pixel_format: pf, diff --git a/crates/metal2vulkan/src/bind/mod.rs b/crates/metal2vulkan/src/bind/mod.rs index 7be6f3cb0..229cce980 100644 --- a/crates/metal2vulkan/src/bind/mod.rs +++ b/crates/metal2vulkan/src/bind/mod.rs @@ -42,9 +42,7 @@ pub(crate) mod pvrtc_decode; pub(crate) mod rate_map; pub(crate) mod replay; pub(crate) mod state; -pub(crate) mod status; pub(crate) mod table; -pub(crate) mod texel_parts; pub(crate) mod ycbcr_convert; pub use argument_buffer::{ @@ -68,5 +66,4 @@ pub use state::{SamplerDescriptor, StageInRegion}; #[cfg(test)] pub(crate) use table::FunctionTableWords; pub use table::{function_table_entry_offset, function_table_header}; -pub(crate) use texel_parts::part_texels; pub(crate) use ycbcr_convert::{YCbCrCodes, YCbCrOutput}; diff --git a/crates/metal2vulkan/src/bind/state.rs b/crates/metal2vulkan/src/bind/state.rs index 4267fa1cd..e2fdd4cbb 100644 --- a/crates/metal2vulkan/src/bind/state.rs +++ b/crates/metal2vulkan/src/bind/state.rs @@ -28,9 +28,8 @@ impl TextureFacts { /// The facts of an image texture that can change the variant, specialization or views a slot /// binds it through (its view facts): the type, the pixel format, the sample count, the /// usage, whether it is sparse, its level count, which decides a storage slot's level views - /// and pushed level count, its swizzle, its address-mode map and its - /// [`offset_base_axes`](Self::offset_base_axes). Its array length only changes the view's - /// subresource range, which is every layer. + /// and pushed level count, its swizzle and its [`offset_base_axes`](Self::offset_base_axes). + /// Its array length only changes the view's subresource range, which is every layer. /// /// The level count is stated whatever the usage: plain Metal writes a texture made without /// `ShaderWrite` at every level, through every write form, as one made with it. @@ -43,7 +42,6 @@ impl TextureFacts { mipmap_level_count: self.mipmap_level_count, sparse: self.sparse, swizzle: self.swizzle, - address_modes: self.address_modes, offset_base_axes: self.offset_base_axes(), } } @@ -76,8 +74,6 @@ impl SamplerDescriptor { linear: self.min_filter == metal::SamplerMinMagFilter::Linear || self.mag_filter == metal::SamplerMinMagFilter::Linear || self.mip_filter == metal::SamplerMipFilter::Linear, - cubic: self.min_filter == metal::SamplerMinMagFilter::Cubic - || self.mag_filter == metal::SamplerMinMagFilter::Cubic, } } } @@ -105,11 +101,6 @@ pub struct TextureFacts { /// an opaque-black border the device replaces is checked against it. #[cfg_attr(feature = "serde", serde(default))] pub swizzle: metal::TextureSwizzleChannels, - /// The texture's address-mode map (`metal::sampler::AddressModeMap`, the runtime's - /// extension): a slot a constexpr sampler samples takes it through the pipeline variant - /// (`VariantKey::address_maps`) where it is not the identity. - #[cfg_attr(feature = "serde", serde(default))] - pub address_modes: metal::sampler::AddressModeMap, /// The level of the texture whose levels a view presents at which the view's first level /// lies (`MTLTexture.parentRelativeLevel`): 0 for a texture that is not a view, and for a /// view that starts at its parent's base level. @@ -137,7 +128,6 @@ impl TextureFacts { mipmap_level_count: 1, sparse: false, swizzle: metal::TextureSwizzleChannels::DEFAULT, - address_modes: metal::sampler::AddressModeMap::IDENTITY, parent_relative_level: 0, parent_base_size: [0; 3], } @@ -280,11 +270,6 @@ pub enum TextureShape { /// against it. #[cfg_attr(feature = "serde", serde(default))] swizzle: metal::TextureSwizzleChannels, - /// The texture's address-mode map ([`TextureFacts::address_modes`]): a slot a constexpr - /// sampler samples compiles under it where it is not the identity - /// (`VariantKey::address_maps`). - #[cfg_attr(feature = "serde", serde(default))] - address_modes: metal::sampler::AddressModeMap, /// The plane axes on which the base-level size Metal's texel-offset rule reads, a view's /// parent's, is not a power of two where the texture's own is /// ([`TextureFacts::offset_base_axes`]): a slot whose function places an offset by that @@ -325,9 +310,4 @@ pub struct SamplerShape { /// (`metal::sampler::vk_filtering`), which the binder checks where the sampler meets textures /// through separate descriptors. pub linear: bool, - /// The min or the mag filter is `Cubic`: Metal samples through the sampler with its bicubic - /// filter whatever the level, which a function emulates under its pipeline variant's - /// cubic samplers (`VariantKey::cubic_samplers`). - #[cfg_attr(feature = "serde", serde(default))] - pub cubic: bool, } diff --git a/crates/metal2vulkan/src/bind/status.rs b/crates/metal2vulkan/src/bind/status.rs deleted file mode 100644 index 7b3de49e2..000000000 --- a/crates/metal2vulkan/src/bind/status.rs +++ /dev/null @@ -1,52 +0,0 @@ -//! `ExecutionStatus` buffer layout: word indices and status bits. -//! -//! One 16-byte buffer per command buffer, shared by every pipeline in it, which the consumer -//! zeroes before the command buffer's first use; the resident-set miss counter, an absent -//! argument's read, a sample through a cubic argument sampler, and a sequentially consistent -//! fence write the words named here. - -/// A word of the `ExecutionStatus` buffer. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum StatusWord { - /// Status bits ([`StatusBits`]). Initial 0. - Status, - /// Resident-miss count. Initial 0. - ResidentMisses, - /// The word every sequentially consistent fence of the command buffer increments with an - /// acquire-release atomic at the fence's scope (`lower::sync::barrier::seq_cst_order`), so - /// that the fences of one command buffer are totally ordered, as Metal's are. Its value means - /// nothing; the decode does not read it. Initial 0. It is the buffer's last word, after one - /// that nothing writes. - SeqCstFences, -} - -impl StatusWord { - /// The word's index in the buffer. - pub const fn index(self) -> u32 { - match self { - StatusWord::Status => 0, - StatusWord::ResidentMisses => 1, - StatusWord::SeqCstFences => 3, - } - } - - /// The word's byte offset in the buffer. - pub const fn byte_offset(self) -> u32 { - self.index() * 4 - } -} - -/// Bits of [`StatusWord::Status`]. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub struct StatusBits(pub u32); - -impl StatusBits { - /// An access missed the resident set. - pub const RESIDENT_MISS: StatusBits = StatusBits(1 << 0); - /// A function sampled, gathered, or queried through a sampler an argument buffer holds whose - /// min or mag filter is `Cubic`, whose bicubic filter it does not emulate there - /// (`RuntimeFact::CubicArgumentSampler`): its result is the device's through a nearest - /// placeholder, not Metal's. - pub const CUBIC_ARGUMENT_SAMPLER: StatusBits = StatusBits(1 << 3); -} diff --git a/crates/metal2vulkan/src/bind/texel_parts.rs b/crates/metal2vulkan/src/bind/texel_parts.rs deleted file mode 100644 index 64c3a05a5..000000000 --- a/crates/metal2vulkan/src/bind/texel_parts.rs +++ /dev/null @@ -1,68 +0,0 @@ -//! A texture buffer wider than one texel buffer view holds, read and written through several -//! views of its bytes, its parts. -//! -//! **Where.** Metal makes a texture buffer of up to 2^28 texels on every Mac. One texel buffer -//! view holds at most the device's `maxTexelBufferElements` texels -//! (`VUID-VkBufferViewCreateInfo-range-00930`): 2^27 on ANV and lavapipe, 2^26 on MoltenVK. The -//! consumer states with a texture buffer's binding how many parts its texels take -//! (its texels over [`part_texels`], rounded up): one for every texture buffer within the limit, -//! which binds one view. -//! -//! **The views.** Part `k` views the texels from `k · P`, `P` the device's [`part_texels`] (its -//! `maxTexelBufferElements` rounded down to a multiple of its `minTexelBufferOffsetAlignment`, so -//! each part starts on that alignment where the texture buffer does): `P` texels for every part -//! but the last, which holds the rest. Each is a view of the device's own in the format one view -//! would take, so a read converts its texel as that view does, the device's conversion -//! (Uniform Texel Buffer, Storage Texel Buffer). -//! -//! **What a function reads.** A slot whose function reads, writes, updates by an atomic or asks -//! the width of the texture buffer bound there, and does nothing else with it -//! (`RuntimeFact::TexelBufferParts`), on a device that indexes arrays of its kind of texel buffer -//! by a `NonUniform` value, takes the parts variant where the bound texture buffer takes more than -//! one part (`VariantKey::texel_buffer_parts`). Under it the slot is declared as an array of its -//! parts, and texel `i` is texel `i − k · P` of part `k = min(⌊i / P⌋, parts − 1)`. A texel past -//! the last lies past the last part's end, so its read is Metal's out-of-bounds texel and its -//! write is dropped, by the device's robustness or the function's own check as through one view. -//! The width is `(parts − 1) · P` plus the last part's. Any other slot binds one view, which -//! `maxTexelBufferElements` bounds. - -use crate::device::Limits; - -/// The texels of each part but the last of a texture buffer of more texels than one texel buffer -/// view holds, which binds through views of its parts (part `k` from texel `k · P`, the last -/// holding the rest): the device's `maxTexelBufferElements` rounded down to a multiple of its -/// `minTexelBufferOffsetAlignment`, so that a part starts on that alignment wherever the texture -/// buffer does (a texel is at least a byte). 0 on a device whose limit is below its alignment, -/// which binds no parts. -pub fn part_texels(limits: &Limits) -> u64 { - let max = u64::from(limits.max_texel_buffer_elements); - let alignment = limits.min_texel_buffer_offset_alignment.max(1); - max - max % alignment -} - -#[cfg(test)] -mod tests { - use super::*; - - fn limits(max: u32, alignment: u64) -> Limits { - Limits { - max_texel_buffer_elements: max, - min_texel_buffer_offset_alignment: alignment, - ..Limits::default() - } - } - - /// A part holds the limit's texels: 2^27 on lavapipe's limits. - #[test] - fn parts_hold_the_limit_s_texels_each() { - assert_eq!(part_texels(&limits(1 << 27, 16)), 1 << 27); - } - - /// A limit off the offset alignment: each part holds the limit rounded down to it, so the next - /// starts on it; a limit below the alignment holds no aligned part. - #[test] - fn parts_start_on_the_offset_alignment() { - assert_eq!(part_texels(&limits(1000, 64)), 960); - assert_eq!(part_texels(&limits(32, 64)), 0); - } -} diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 11c50585b..fd4ee284f 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -33,20 +33,20 @@ use crate::metal::format::{ExtendedRange, WordAttachment, WordField}; use crate::metal::{CompareFunction, TextureWriteRoundingMode}; use crate::pipeline::artifact::{ ComputePipeline, ComputePipelineMetalInfo, ModuleStats, PrecisionNote, Reconvergence, - RenderPipeline, RuntimeDependency, SpecClause, SpecConstant, SpecTest, SpecializationLayout, - SpecializedNote, StageModule, StrategyCensus, StrategyUse, + RenderPipeline, RuntimeDependency, SpecConstant, SpecializationLayout, StageModule, + StrategyCensus, StrategyUse, }; use crate::pipeline::descriptor::TessellationDescriptor; use crate::pipeline::facts::{Mechanism, RuntimeFact}; use crate::pipeline::graphics::{ - BandPrimitive, BlendState, ColorAttachmentState, GraphicsState, InputAttachmentUse, - LineBandState, TessellationState, + BandPrimitive, BlendState, ColorAttachmentState, GraphicsState, LineBandState, + TessellationState, }; use crate::pipeline::interface::{ AccessSet, BufferForm, BufferKind, BufferSlot, CommandWrites, NumberedSampler, PatchDomain, - PipelineInterface, PlacedField, PushLoc, PushPlacement, SamplerArray, SamplerSlot, - SlotInterface, StageDescriptor, StageInterface, StageSpec, TessellationStage, TextureAccess, - TextureSlot, ThreadgroupArgument, Window, + PipelineInterface, PlacedField, PushLoc, PushPlacement, SamplerSlot, SlotInterface, + StageDescriptor, StageInterface, StageSpec, TessellationStage, TextureAccess, TextureSlot, + ThreadgroupArgument, Window, }; use crate::pipeline::layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, @@ -838,40 +838,30 @@ codec_enum! { StorageFormatClass { NotStorage, Unknown, Format(f0) } HandleClass { Image(f0), Sampler { compare, integer }, FunctionTable } SyntheticBinding { - ArgumentTable, ExecutionStatus, RootTable, HandleTable, ConstantBlob, TessellationFactors, Imageblock, - SamplerTable, - FunctionTableDirectory, - PatchIndices, - ControlPointIndices, - TileMemory, - FunctionTableSnapshot, + Imageblock, FunctionTableDirectory, TileMemory, FunctionTableSnapshot, } ResourceKind { - Buffer, Texture, Sampler, Heap(f0), Synthetic(f0), InputAttachment(f0), - CombinedTextureSampler(f0), HeapSampler(f0), AccelerationStructure(f0), TileAttachment(f0), - TileMap, SeparateTexture(f0), SeparateSampler(f0), - SamplerArray { compare, integer }, + Buffer, Heap(f0), Synthetic(f0), AccelerationStructure(f0), TileAttachment(f0), TileMap, } AccelerationStructureLevel { Primitive, Instance } SamplerRef { Slot(f0), Constexpr(f0) } SpecKey { LocalSize(f0), FlatLocalSize, MultiRegion, TgLength(f0), Presence(f0), SampleCount, AmplificationCount, ImageblockWidth, ImageblockHeight, - RenderAreaWidth, RenderAreaHeight, OutOfBoundsAlpha(f0), BicubicTexels(f0), - SparseTexture(f0), SamplerState { slot, fields }, - TgOffset(f0), TileThreadgroupLength, TileGridWidth, TextureSwizzle(f0), + RenderAreaWidth, RenderAreaHeight, OutOfBoundsAlpha(f0), SparseTexture(f0), TgOffset(f0), + TileThreadgroupLength, TileGridWidth, TextureSwizzle(f0), ObjectLocalSize(f0), ObjectFlatLocalSize, ObjectMultiRegion, SamplerMinLevel(f0), - ConstantLanes(f0), BoundTexelFormat(f0), OffsetBaseAxes(f0), SamplerAnisotropy(f0), - NearestPixelSampler(f0), BoundSamplerWord(f0), - HeapRawTextures(f0), BorderTexels(f0), HeapNanFamilies(f0), DeepThreadgroup, + OffsetBaseAxes(f0), SamplerAnisotropy(f0), + NearestPixelSampler(f0), + BorderTexels(f0), DeepThreadgroup, WorkgroupSize(f0), TexelBufferWords { stage, handles }, } PushField { - RootTableAddress, ExecutionStatusAddress, DispatchRegion, BaseVertexInstance, + RootTableAddress, DispatchRegion, BaseVertexInstance, SlotBindOffset(f0), SlotGuestBase(f0), VertexBufferStride(f0), StageInRegion, TessellationFactorOffset, TessellationFactorInstanceStride, TessellationFactorScale, - TextureLevels(f0), InstanceCount(f0), CommandRecordsAddress, ReplayRegionAddress, - IndexCapacity, ViewportCount, RenderTargetArrayLength, + TextureLevels(f0), InstanceCount(f0), ReplayRegionAddress, + ViewportCount, RenderTargetArrayLength, PatchIndexOffset, PatchIndexBound, ControlPointIndexOffset, StageInStride(f0), AmplificationId, AmplificationLayerOffset, AmplificationViewportOffset, DepthClampRange, @@ -879,7 +869,6 @@ codec_enum! { CaptureIndexAddress, TextureIntegerChannels(f0), BicubicTexels(f0), - HalfBlendColor, VerticesPerPrimitive, MergedDrawAddress, AlphaTestReference, @@ -1045,10 +1034,9 @@ codec_enum! { MaxSubgroupSize, MaxPushConstantsSize, MaxPushDescriptors, MaxBoundDescriptorSets, MaxPerStageDescriptorSamplers, MaxPerStageDescriptorUniformBuffers, MaxPerStageDescriptorStorageBuffers, MaxPerStageDescriptorSampledImages, - MaxPerStageDescriptorStorageImages, MaxPerStageDescriptorInputAttachments, - MaxPerStageResources, MaxDescriptorSetSamplers, MaxDescriptorSetUniformBuffers, + MaxPerStageDescriptorStorageImages, MaxPerStageResources, MaxDescriptorSetSamplers, MaxDescriptorSetUniformBuffers, MaxDescriptorSetStorageBuffers, MaxDescriptorSetSampledImages, - MaxDescriptorSetStorageImages, MaxDescriptorSetInputAttachments, + MaxDescriptorSetStorageImages, MaxDescriptorSetUpdateAfterBindSamplers, MaxDescriptorSetUpdateAfterBindSampledImages, MaxDescriptorSetUpdateAfterBindStorageImages, MaxPerStageDescriptorUpdateAfterBindSamplers, @@ -1107,13 +1095,11 @@ codec_enum! { codec_struct! { CommandWrites { operations, primitive_types, kinds } StageInterface { - stage, slots, threadgroup, push, descriptors, spec, needs_pointer_translation, - needs_handle_translation, io, tessellation, writes_memory, payload, reaches_command_buffers, command_writes, writes_textures, + stage, slots, threadgroup, push, descriptors, spec, io, tessellation, writes_memory, payload, reaches_command_buffers, command_writes, writes_textures, reads_unbound_resources, writes_unbound_resources, unbound_storage_textures, numbered_samplers, own_pixel_textures, - private_bytes, sampler_arrays, + private_bytes, } - SamplerArray { slot, samplers } TessellationStage { domain, control_points } TessellationDescriptor { max_tessellation_factor, partition_mode, factor_format, factor_step_function, @@ -1199,11 +1185,9 @@ codec_enum! { RuntimeFact { ThreadsPerThreadgroup, ThreadgroupMemoryLength { index }, LocalSizeConstraint { multiple }, LocalSizeLimits, DispatchGrid, IndirectGroupCount, - ResourcePresence { slot }, SampleCount, StorageTextureFormat { slot }, - SamplerCoordinates { slot }, SamplerReduction { slot }, ImageViewShape { slot }, + ResourcePresence { slot }, SampleCount, ImageViewShape { slot }, VertexFetch { attr }, VertexBufferStride { layout }, BaseVertexInstance, - DeviceAddresses { slot }, BufferRangeLimit { slot }, TexelBufferRange { slot }, - FramebufferFetch { color }, ExecutionStatus, HeapNumericType { class }, + DeviceAddresses { slot }, FramebufferFetch { color }, SimdgroupEmulation { bytes_per_simdgroup, arena }, AmplificationCount, EmulatedSimdgroups, ImageblockSize { cell_bytes }, @@ -1212,13 +1196,11 @@ codec_enum! { TileFunction, TileAttachmentFormat { color, format }, StorageTextureNumericType { slot }, OutOfBoundsAlpha { slot }, - BicubicTexels { slot }, StorageTextureLevels { slot }, StorageTextureLevelViews { slot }, SparseTexture { slot, sparse_arm, tile_map }, AccelerationStructureInstanceCount { slot }, - PredicationVote, SrgbTexture { slot }, - ViewportCount, + PredicationVote, ViewportCount, AliasedImageblock { data_size }, CallStackDepth { depth }, OpenClMode, @@ -1226,7 +1208,6 @@ codec_enum! { RowLockstep, FlatGrid, CallThreadgroups, - SparseTextureWrites { slot, atomic }, TileThreadgroupMemory { index }, TextureSwizzle { slot }, TileImageblock { data_size, alignment }, @@ -1237,19 +1218,8 @@ codec_enum! { DroppedColor { color }, DepthClampRange, RotatedWeights, - ConstantLanes { slot }, FunctionTableRange { addressed }, TileThreadgroup { tile_sized }, - ConstexprSampled { slot, modes }, - CubicSampler { slot }, - CubicArgumentSampler { stage }, - HeapRawSamples { stage, sampler }, - CrossClassReads { slot }, - HeapCrossClassNeutral { stage, class, every_member }, - HeapResidency { stage }, - HeapStorageReads { stage, class }, - AnisotropicSampler { slot }, - StorageTextureIntegerChannels { slot }, ObjectThreadgroupArena { static_bytes, payload }, MergedDraws, QuadPrimitiveIds, @@ -1258,7 +1228,6 @@ codec_enum! { BorderTexels { slot }, RegionViewports, PartialThreadgroups, - TexelBufferParts { slot }, AddressAlignment { slot, align }, GridTiles, PrivateArena { slot_bytes }, @@ -1268,7 +1237,7 @@ codec_enum! { Mechanism { Specialization, Variant, PushConstant, DynamicState, DynamicStateOrPushConstant, Builtin, PlanTimeCheck, BinderView, KeyProjection, RegionSelected, - SyntheticBinding, RenderPassContract, None, PipelineStateOrPushConstant, + RenderPassContract, None, PipelineStateOrPushConstant, PipelineState, } } @@ -1278,8 +1247,8 @@ codec_enum! { codec_struct! { RelocatableModule { words, relocs, requirements } FunctionArtifact { - key, module, interface, facts, subgroup, reconvergence, precision, strategies, blob, - requirements, variant_bits, profile, kernel, reflection, slot_writes, specialized, stats, + key, module, interface, facts, subgroup, reconvergence, precision, strategies, + requirements, variant_bits, profile, kernel, reflection, slot_writes, stats, } StageReflection { bindings, attributes } SlotWrite { name, parameter, binding_type, index, count, used, access, writes } @@ -1316,13 +1285,9 @@ codec_struct! { } StageModule { stage, entry_point, spirv, specialization, required_subgroup_size, stage_flags, - reconvergence, precision_notes, strategies, constant_blob, rounded_colors, - specialized_notes, own_pixel_textures, + reconvergence, precision_notes, strategies, rounded_colors, own_pixel_textures, private_bytes, stats, } - SpecializedNote { note, when } - SpecClause { all } - SpecTest { key, mask, bits, equal } SpecializationLayout { constants } SpecConstant { id, key, size, default, unread_bits } RuntimeDependency { fact, mechanism } @@ -1332,7 +1297,7 @@ codec_struct! { metal_max_total_threads_per_threadgroup, } PipelineInterface { - slots, threadgroup, needs_pointer_translation, needs_handle_translation, push, + slots, threadgroup, push, reaches_command_buffers, command_writes, texture_writing_stages, reads_unbound_resources, writes_unbound_resources, unbound_storage_textures, writes_memory, numbered_samplers, stage_in, @@ -1340,8 +1305,7 @@ codec_struct! { PipelineLayout { sets, push_constants } DescriptorSetLayout { set, bindings, flags } DescriptorBinding { - binding, ty, count, stages, source, immutable_sampler, flags, variables, - immutable_samplers, + binding, ty, count, stages, source, flags, variables, } PushConstantRange { stages, offset, size } VertexInputState { bindings, attributes, pulled } @@ -1350,7 +1314,7 @@ codec_struct! { PulledAttribute { attribute, buffer_index, format, offset, step_function, step_rate, stride } GraphicsState { topology, color_attachments, depth_format, stencil_format, rasterization_samples, - alpha_to_coverage, alpha_to_one, rasterizer_discard, dynamic_states, input_attachments, + alpha_to_coverage, alpha_to_one, rasterizer_discard, dynamic_states, max_vertex_amplification_count, declares_layer, tessellation, vertex_writes_memory, writes_viewport_index, writes_point_size, writes_depth, reads_barycentric_coord, reads_primitive_id, interpolates_at_sample, @@ -1364,7 +1328,6 @@ codec_struct! { LineBandState { push_offset, primitive } ColorAttachmentState { format, write_mask, blend } BlendState { src_color, dst_color, color_op, src_alpha, dst_alpha, alpha_op } - InputAttachmentUse { color_index, input_attachment_index, format_class } } codec_enum! { @@ -1450,12 +1413,8 @@ codec_enum! { DeviceHalfDenormals, } BindingSource { - Buffer(f0), Texture(f0), Sampler(f0), CombinedTextureSampler { texture, sampler }, - Synthetic { stage, binding }, Heap(f0), InputAttachment(f0), HeapSampler { stage, sampler }, + Buffer(f0), Synthetic { stage, binding }, IdentityArray, AccelerationStructure { slot, level }, TileAttachment(f0), TileMap(f0), - SeparateTexture { texture, sampler }, SeparateSampler { stage, sampler }, - SamplerArray { stage, compare, integer }, - IdentityArray, } VertexStride { Static(f0), PerBind } } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 1524b3820..1d19a6e42 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2354; +pub const SEMANTICS_VERSION: u32 = 2355; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 2354; /// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag /// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that /// bumps it says what changed; this comment keeps no history. -pub const ARTIFACT_FORMAT_VERSION: u32 = 606; +pub const ARTIFACT_FORMAT_VERSION: u32 = 607; /// The version of what this crate gives a runtime for the runs of a compiled pipeline, beside the /// compile: the device a run opens and what it enables, the Vulkan and Metal vocabularies a runtime @@ -131,8 +131,7 @@ impl fmt::Debug for PipelineKey { } /// The per-function variant choices of a pipeline: storage-image choices for slots whose -/// `StorageTextureFormat` fact maps to `Variant`, slots that a `BufferRangeLimit` variant moves to -/// `BufferForm::Psb`, vertex buffers fetched in the shader, a kernel's emulated simdgroups, and the +/// `StorageTextureFormat` fact maps to `Variant`, vertex buffers fetched in the shader, a kernel's emulated simdgroups, and the /// other forms each field names. Canonical (ordered maps) and empty on the common path. /// /// [`VariantKey::lowering_inputs`] is each function's `LoweringInputs` under the key, so the @@ -144,41 +143,11 @@ impl fmt::Debug for PipelineKey { pub struct VariantKey { #[cfg_attr(feature = "serde", serde(with = "crate::pipeline::serde_pairs"))] pub storage_images: BTreeMap, - pub psb_slots: BTreeSet, /// The kernel's simdgroups run in the emulated tier, which is exact for every threadgroup size: /// a dispatch whose threadgroup has a partial simdgroup asks for it where the kernel's own tier /// runs simdgroups on whole subgroups. #[cfg_attr(feature = "serde", serde(default))] pub emulated_simdgroups: bool, - /// Texture slots bound to an 8-bit sRGB texture the device cannot sample, which the runtime - /// holds as the format's UNORM twin (`metal::format::srgb_raw_twin`), whose views read the - /// codes (`c / 255`): every slot of a `RuntimeFact::SrgbTexture` the shape binds in such a - /// format (`metal::texel_format::srgb_twin_on`). The function decodes what it reads there by - /// the MSL transfer through the device's `Pow`, as the device would through an sRGB view it - /// lacks (`LoweringInputs::srgb_textures`); a slot bound in an sRGB format the device samples - /// reads the device's decode and is no slot of this. - #[cfg_attr(feature = "serde", serde(default))] - pub srgb_textures: BTreeSet, - /// Texture-buffer slots whose function reads it through its parts, each with the parts of the - /// texture buffer the shape binds there: every slot of a `RuntimeFact::TexelBufferParts` the - /// shape binds a texture buffer of more texels than one view holds at. Each such slot binds an array of that many texel buffer - /// views (`bind::texel_parts`). A texture buffer one view holds adds nothing, so its draws - /// keep their key. - #[cfg_attr( - feature = "serde", - serde(default, with = "crate::pipeline::serde_pairs") - )] - pub texel_buffer_parts: BTreeMap, - /// Texture slots a constexpr sampler samples, each with the address-mode map of the texture the - /// shape binds there where it is not the identity: every slot of a - /// `RuntimeFact::ConstexprSampled` the shape binds such a texture at. The function's constexpr - /// samplers sample the slot with their modes mapped. A texture of the identity map adds - /// nothing, so ordinary draws keep their key. - #[cfg_attr( - feature = "serde", - serde(default, with = "crate::pipeline::serde_pairs") - )] - pub address_maps: BTreeMap, /// The kernel runs its grid flat (`LoweringInputs::flat_grid`): one variant runs every grid /// and threadgroup size of a kernel that does not observe its threadgroup partition /// (`KernelFacts::partition_oblivious`), reading the grid from the region record at its @@ -291,15 +260,6 @@ pub struct VariantKey { /// (`FunctionTablesShape::bytes_class`). #[cfg_attr(feature = "serde", serde(default))] pub addressed_function_tables: bool, - /// The runtime sampler slots of a `RuntimeFact::CubicSampler` that the shape binds to a sampler - /// whose min or mag filter is `Cubic`, each with the bound word masked by - /// `SamplerWord::CUBIC_STATE` (`LoweringInputs::cubic_samplers`): the variant whose function - /// samples through each with Metal's bicubic filter of that state. - #[cfg_attr( - feature = "serde", - serde(default, with = "crate::pipeline::serde_pairs") - )] - pub cubic_samplers: BTreeMap, /// The de-indexed form of a pipeline whose vertex function writes the primitive ID's varying /// (`LoweringInputs::primitive_id_indices`): the vertex /// function of an indexed draw of this index type runs the draw's indices as `index count` @@ -321,18 +281,7 @@ pub struct VariantKey { /// a list's base vertex cannot carry (`RuntimeFact::PrivateList`). #[cfg_attr(feature = "serde", serde(default))] pub private_list: bool, - /// Sampled texture slots whose compile states `RuntimeFact::CrossClassReads` bound to a - /// texture of a color format whose numeric class is not the slot's declared one, by the - /// bound format's class (`LoweringInputs::cross_class`): the variant's function reads, - /// samples and gathers the texture in its own class and hands back its words as the declared - /// type, as plain Metal does. - #[cfg_attr( - feature = "serde", - serde(default, with = "crate::pipeline::serde_pairs") - )] - pub cross_class: BTreeMap, - /// The runtime sampler slots of a `RuntimeFact::AnisotropicSampler` that the shape binds to a - /// sampler whose word states anisotropy (`SamplerWord::ANISOTROPIC`, + /// The runtime sampler slots that the shape binds to a sampler whose word states anisotropy (`SamplerWord::ANISOTROPIC`, /// `LoweringInputs::anisotropic_samplers`): the variant whose function takes Metal's /// anisotropic filter, emulated, at each one's samples. #[cfg_attr(feature = "serde", serde(default))] @@ -360,11 +309,7 @@ impl VariantKey { /// Whether nothing needs a variant (the common path). pub fn is_empty(&self) -> bool { self.storage_images.is_empty() - && self.psb_slots.is_empty() && !self.emulated_simdgroups - && self.srgb_textures.is_empty() - && self.texel_buffer_parts.is_empty() - && self.address_maps.is_empty() && !self.flat_grid && !self.call_threadgroups && !self.replay_bindings @@ -381,18 +326,16 @@ impl VariantKey { && self.line_band.is_none() && self.swizzled_storage.is_empty() && !self.addressed_function_tables - && self.cubic_samplers.is_empty() && self.primitive_id_indices.is_none() && !self.quad_primitive_ids && !self.private_list - && self.cross_class.is_empty() && self.anisotropic_samplers.is_empty() && self.open_cl_lines.is_empty() && !self.region_viewports } /// The lowering inputs of the function of `stage` under this key: its storage-image choices, - /// device-address slots, kept storage views, raw sRGB slots, cubic and anisotropic samplers, + /// device-address slots, kept storage views, raw sRGB slots, anisotropic samplers, /// for the kernel the emulated simdgroups, the flat grid, the folded groups, the partial /// threadgroups and the replay's bindings, for the vertex and fragment functions the draws of one amplification each, for /// the fragment function the colors it writes zero to and those it drops, its depth's clamp @@ -414,12 +357,6 @@ impl VariantKey { .filter(|(s, _)| s.stage == stage) .map(|(s, c)| (*s, *c)) .collect(); - out.psb_slots = self - .psb_slots - .iter() - .filter(|s| s.stage == stage) - .copied() - .collect(); out.emulated_simdgroups = self.emulated_simdgroups && stage == crate::pipeline::sym::Stage::Kernel; out.flat_grid = self.flat_grid && stage == crate::pipeline::sym::Stage::Kernel; @@ -446,30 +383,6 @@ impl VariantKey { .filter(|_| stage != crate::pipeline::sym::Stage::Kernel); out.region_viewports = self.region_viewports && stage == crate::pipeline::sym::Stage::Vertex; - out.srgb_textures = self - .srgb_textures - .iter() - .filter(|s| s.stage == stage) - .copied() - .collect(); - out.texel_buffer_parts = self - .texel_buffer_parts - .iter() - .filter(|(s, _)| s.stage == stage) - .map(|(s, parts)| (*s, *parts)) - .collect(); - out.address_maps = self - .address_maps - .iter() - .filter(|(s, _)| s.stage == stage) - .map(|(s, m)| (*s, *m)) - .collect(); - out.cubic_samplers = self - .cubic_samplers - .iter() - .filter(|(s, _)| s.stage == stage) - .map(|(s, w)| (*s, *w)) - .collect(); out.anisotropic_samplers = self .anisotropic_samplers .iter() @@ -494,12 +407,6 @@ impl VariantKey { .filter(|s| s.stage == stage) .copied() .collect(); - out.cross_class = self - .cross_class - .iter() - .filter(|(s, _)| s.stage == stage) - .map(|(s, c)| (*s, *c)) - .collect(); if stage == crate::pipeline::sym::Stage::Fragment { out.zeroed_colors = self.zeroed_colors.clone(); out.dropped_colors = self.dropped_colors.clone(); diff --git a/crates/metal2vulkan/src/cache/tests.rs b/crates/metal2vulkan/src/cache/tests.rs index f9fcaafe9..1de0abe9d 100644 --- a/crates/metal2vulkan/src/cache/tests.rs +++ b/crates/metal2vulkan/src/cache/tests.rs @@ -5,7 +5,7 @@ //! `llvm-as` assembles the owned fixtures; a missing tool skips a test visibly. use crate::budget::Budget; -use crate::device::{Device, DeviceDescription, DevicePolicy}; +use crate::device::{Device, DeviceDescription}; use crate::library::{CompiledFunction, FunctionStage, Library}; use crate::metal; use crate::pipeline::artifact::{ComputePipeline, RenderPipeline}; @@ -37,14 +37,14 @@ fn fixture(stem: &str) -> Option> { } } -/// Committed profile `stem` as a device with the resident-table domains. +/// Committed profile `stem` as a device. fn device(stem: &str) -> Device { let path = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../metal2vulkan-validation/profiles") .join(format!("{stem}.json")); let text = std::fs::read_to_string(&path).expect("profile"); let desc = DeviceDescription::from_khronos_json(&text, None).expect("description"); - Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).expect("device") + Device::from_queries(desc).expect("device") } /// `store_const` compiled on `dev`, with its compute pipeline. @@ -365,41 +365,6 @@ fn earlier_format_versions_are_stale() { } } -/// The fact format version 4 added encodes and decodes. -#[test] -fn the_heap_numeric_type_fact_round_trips() { - use crate::pipeline::facts::RuntimeFact; - use crate::pipeline::sym::{ - ImageAccess, ImageDim, ImageHandleClass, SampledType, StorageFormatClass, - }; - let fact = RuntimeFact::HeapNumericType { - class: ImageHandleClass { - dim: ImageDim::D2, - arrayed: true, - multisampled: false, - sampled_type: SampledType::Float, - depth_compare: false, - access: ImageAccess::Storage, - format: StorageFormatClass::Unknown, - }, - }; - assert_eq!(decode::(&encode(&fact)), Ok(fact)); -} - -/// The `AnisotropicSampler` fact encodes and decodes. -#[test] -fn the_anisotropic_sampler_fact_round_trips() { - use crate::pipeline::facts::RuntimeFact; - let fact = RuntimeFact::AnisotropicSampler { - slot: SlotRef { - stage: Stage::Fragment, - class: SlotClass::Sampler, - index: 3, - }, - }; - assert_eq!(decode::(&encode(&fact)), Ok(fact)); -} - /// The members format version 178 appends encode and decode, and each decodes as itself: /// `VkFeature::Maintenance5` and the three framebuffer `VkLimit`s. #[test] @@ -418,13 +383,10 @@ fn the_version_178_members_round_trip() { /// The members format version 179 appends encode and decode, and each decodes as itself: /// `VkFeature::{OcclusionQueryPrecise, DepthBiasControl, FloatRepresentation, DepthBiasExact}`, -/// `VkExtension::ExtDepthBiasControl`, and `PushField::IndexCapacity`. +/// and `VkExtension::ExtDepthBiasControl`. #[test] fn the_version_179_members_round_trip() { use crate::device::requirements::{VkExtension, VkFeature}; - use crate::pipeline::sym::PushField; - let field = PushField::IndexCapacity; - assert_eq!(decode::(&encode(&field)), Ok(field)); for feature in [ VkFeature::OcclusionQueryPrecise, VkFeature::DepthBiasControl, @@ -655,23 +617,6 @@ fn the_version_253_members_round_trip() { assert_eq!(decode::(&encode(&key)), Ok(key)); } -/// The members format version 267 appends encode and decode as themselves: a sparse texture slot's -/// constant lanes, as a specialization and as a fact. -#[test] -fn the_version_267_members_round_trip() { - use crate::pipeline::facts::RuntimeFact; - use crate::pipeline::sym::SpecKey; - let slot = SlotRef { - stage: Stage::Fragment, - class: SlotClass::Texture, - index: 3, - }; - let key = SpecKey::ConstantLanes(slot); - assert_eq!(decode::(&encode(&key)), Ok(key)); - let fact = RuntimeFact::ConstantLanes { slot }; - assert_eq!(decode::(&encode(&fact)), Ok(fact)); -} - /// The member format version 374 appends encodes and decodes as itself: the axes on which a texture /// slot's bound view's parent's base-level size, which Metal's texel-offset rule reads, is not a /// power of two where the view's own is. @@ -685,22 +630,6 @@ fn the_version_374_member_round_trips() { }; let key = SpecKey::OffsetBaseAxes(slot); assert_eq!(decode::(&encode(&key)), Ok(key)); - assert_ne!(encode(&key), encode(&SpecKey::BoundTexelFormat(slot))); -} - -/// The member format version 485 appends encodes and decodes as itself: the word of the sampler -/// bound at a slot, which a specialized note's test alone reads. -#[test] -fn the_version_485_member_round_trips() { - use crate::pipeline::sym::SpecKey; - let slot = SlotRef { - stage: Stage::Fragment, - class: SlotClass::Sampler, - index: 2, - }; - let key = SpecKey::BoundSamplerWord(slot); - assert_eq!(decode::(&encode(&key)), Ok(key)); - assert_ne!(encode(&key), encode(&SpecKey::NearestPixelSampler(slot))); } /// The member format version 535 appends encodes and decodes as itself: a kernel's image-only @@ -741,30 +670,13 @@ fn the_version_602_member_round_trips() { assert_eq!(decode::(&encode(¬e)), Ok(note)); } -/// The members format versions 153, 154, 155, 157 and 161 joined from every side encode and -/// decode together in one render pipeline: `PrecisionNote::CubeGradientFootprint` and -/// `CombinedSampler`, `RuntimeFact::SrgbTexture` and -/// `SrgbTexture`, `PrecisionNote::HalfTexelConversion` and `SrgbTexelDecode`, -/// `HandleClass::Sampler { compare, integer }` and -/// `SyntheticBinding::SamplerTable`, each beside the others rather than only on its own side's -/// fixtures. +/// The precision notes format versions 153, 155 and 161 joined from every side encode and decode +/// together in one render pipeline: `PrecisionNote::CubeGradientFootprint`, +/// `HalfTexelConversion` and `SrgbTexelDecode`, each beside the others rather than only on its own +/// side's fixtures. #[test] fn the_merged_members_round_trip_in_one_render_pipeline() { - use crate::pipeline::artifact::{PrecisionNote, RuntimeDependency, SpecConstant}; - use crate::pipeline::facts::{Mechanism, RuntimeFact}; - use crate::pipeline::layout::{BindingSource, DescriptorBinding, DescriptorSetLayout}; - use crate::pipeline::sym::{ - CombinedSampler, HandleClass, ResourceKind, SamplerRef, SpecKey, SyntheticBinding, - }; - use crate::vk; - let texture = SlotRef { - stage: Stage::Fragment, - class: SlotClass::Texture, - index: 3, - }; - let sampler = CombinedSampler::new(SamplerRef::Slot(1), true, false); - let kind = ResourceKind::CombinedTextureSampler(sampler); - assert_eq!(decode::(&encode(&kind)), Ok(kind)); + use crate::pipeline::artifact::PrecisionNote; let notes = [ PrecisionNote::CubeGradientFootprint, PrecisionNote::HalfTexelConversion, @@ -784,82 +696,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() { .compile_render_pipeline(&d, &Budget::standard()) .expect("pipeline"); p.stages[0].precision_notes.extend(notes); - let id = p.stages[0].specialization.constants.len() as u32; - p.stages[0].specialization.constants.push(SpecConstant { - id, - key: SpecKey::BicubicTexels(texture), - size: 4, - default: 0, - unread_bits: 0, - }); - let set = p.layout.sets.len() as u32; - p.layout.sets.push(DescriptorSetLayout { - set, - bindings: vec![ - DescriptorBinding { - binding: 0, - ty: vk::DescriptorType::COMBINED_IMAGE_SAMPLER, - count: 1, - stages: vk::ShaderStageFlags::FRAGMENT, - source: BindingSource::CombinedTextureSampler { texture, sampler }, - immutable_sampler: None, - flags: vk::DescriptorBindingFlags::empty(), - variables: 1, - immutable_samplers: Vec::new(), - }, - DescriptorBinding { - binding: 1, - ty: vk::DescriptorType::SAMPLED_IMAGE, - count: 1, - stages: vk::ShaderStageFlags::FRAGMENT, - source: BindingSource::Texture(texture), - immutable_sampler: None, - flags: vk::DescriptorBindingFlags::empty(), - variables: 1, - immutable_samplers: Vec::new(), - }, - ], - flags: vk::DescriptorSetLayoutCreateFlags::empty(), - }); - // An argument buffer's sampler array of a comparison use of an integer texel, and the stage's - // sampler table. - let argument_samplers = vec![ - DescriptorBinding { - binding: 2, - ty: vk::DescriptorType::SAMPLER, - count: 16, - stages: vk::ShaderStageFlags::FRAGMENT, - source: BindingSource::Heap(HandleClass::Sampler { - compare: true, - integer: true, - }), - immutable_sampler: None, - flags: vk::DescriptorBindingFlags::PARTIALLY_BOUND, - variables: 1, - immutable_samplers: Vec::new(), - }, - DescriptorBinding { - binding: 3, - ty: vk::DescriptorType::STORAGE_BUFFER, - count: 1, - stages: vk::ShaderStageFlags::FRAGMENT, - source: BindingSource::Synthetic { - stage: Stage::Fragment, - binding: SyntheticBinding::SamplerTable, - }, - immutable_sampler: None, - flags: vk::DescriptorBindingFlags::empty(), - variables: 1, - immutable_samplers: Vec::new(), - }, - ]; - if let Some(last) = p.layout.sets.last_mut() { - last.bindings.extend(argument_samplers); - } - p.dependencies.push(RuntimeDependency { - fact: RuntimeFact::SrgbTexture { slot: texture }, - mechanism: Mechanism::Variant, - }); let bytes = encode(&p); let back = decode::(&bytes).expect("decoded"); assert_eq!(back, p); @@ -869,130 +705,6 @@ fn the_merged_members_round_trip_in_one_render_pipeline() { assert!(notes .iter() .all(|n| sealed.stages[0].precision_notes.contains(n))); - assert!(sealed.stages[0] - .specialization - .constants - .iter() - .any(|c| c.key == SpecKey::BicubicTexels(texture))); - let bindings = sealed.layout.sets.last().map(|s| &s.bindings[..]); - assert!(matches!( - bindings.map(|b| &b[0].source), - Some(BindingSource::CombinedTextureSampler { sampler, .. }) - if sampler.compare - )); - assert_eq!( - bindings.map(|b| &b[1].source), - Some(&BindingSource::Texture(texture)) - ); - assert!(matches!( - bindings.map(|b| &b[2].source), - Some(BindingSource::Heap(HandleClass::Sampler { - compare: true, - integer: true - })) - )); - assert!(matches!( - bindings.map(|b| &b[3].source), - Some(BindingSource::Synthetic { - binding: SyntheticBinding::SamplerTable, - .. - }) - )); - let fact = RuntimeFact::SrgbTexture { slot: texture }; - assert!( - sealed.dependencies.iter().any(|d| d.fact == fact), - "{fact:?}" - ); -} - -/// A kernel compiled under the storage-view variant round trips with its uniform-view facts (kept, -/// viewed, spare, and the alias check), and the decoded pipeline's plan for a shape that binds a -/// large buffer at the kept slot states the variant, so a cached variant settles as the compiled -/// one does. Format version 158's members: a pipeline whose stage takes its combined image samplers -/// apart (`smp_runtime_array` on `moltenvk-m3`) round-trips its separate texture and separate -/// sampler bindings, and the symbols its relocations name. -#[test] -fn the_separate_bindings_round_trip() { - use crate::pipeline::layout::BindingSource; - let dev = device("moltenvk-m3"); - let Some(bc) = fixture("smp_runtime_array") else { - return; - }; - let f = Library::from_air(&bc) - .and_then(|lib| lib.function("smp_runtime_array")) - .expect("kernel"); - let d = ComputePipelineDescriptor::new(StageSource::Function(FunctionDescriptor::new(f))); - let pipeline = dev - .compile_compute_pipeline(&d, &Budget::standard()) - .expect("pipeline"); - let sources: Vec<_> = pipeline.layout.sets[0] - .bindings - .iter() - .map(|b| b.source) - .collect(); - assert_eq!( - sources - .iter() - .filter(|s| matches!(s, BindingSource::SeparateTexture { .. })) - .count(), - 32 - ); - assert!(sources - .iter() - .any(|s| matches!(s, BindingSource::SeparateSampler { .. }))); - let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &dev).expect("decoded"); - assert_eq!(decoded, pipeline); - assert_eq!( - decoded.to_bytes(), - pipeline.to_bytes(), - "the encoding is canonical" - ); - // Within the limit the same kernel keeps its combined bindings, which round-trip alike. - let within = device("lavapipe"); - let pipeline = within - .compile_compute_pipeline(&d, &Budget::standard()) - .expect("pipeline"); - assert_eq!( - pipeline.layout.sets[0] - .bindings - .iter() - .filter(|b| matches!(b.source, BindingSource::CombinedTextureSampler { .. })) - .count(), - 32 - ); - let decoded = ComputePipeline::from_bytes(&pipeline.to_bytes(), &within).expect("decoded"); - assert_eq!(decoded, pipeline); -} - -/// A combined binding's symbol and a separate texture's, whose index packs its use above its -/// texture slot, round-trip through the codec for every use, at the slots' bounds. -#[test] -fn combined_and_separate_texture_symbols_round_trip() { - use crate::pipeline::sym::{CombinedSampler, ResourceKind, ResourceSlot, SamplerRef}; - for sampler in [ - SamplerRef::Slot(3), - SamplerRef::Constexpr([u64::MAX >> 1, 7]), - ] { - for rank in 0..4u32 { - let c = CombinedSampler::new(sampler, rank & 2 != 0, rank & 1 != 0); - for texture in [0, 127, (1 << 28) - 1] { - let combined = ResourceSlot { - stage: Stage::Fragment, - kind: ResourceKind::CombinedTextureSampler(c), - index: texture, - }; - let separate = - ResourceSlot::separate_texture(Stage::Fragment, texture, c).expect("symbol"); - for s in [combined, separate] { - assert_eq!(decode::(&encode(&s)), Ok(s)); - } - assert_eq!( - decode::(&encode(&separate)).map(|s| s.separate_texture_of()), - Ok(Some((texture, c))) - ); - } - } - } } /// A body that passes the checksum is still decoded strictly (every byte used) and scanned: a @@ -1179,39 +891,6 @@ fn a_chunked_encoding_is_the_encoding() { assert_eq!(decode::>(&short), Err(Malformed)); } -/// A pipeline whose constant blob is non-zero and longer than a chunk (196,615 bytes) writes -/// exactly `to_bytes`' bytes, also through a writer that takes 7 bytes per call, and they decode -/// to the pipeline. -#[test] -fn a_pipeline_with_a_long_blob_writes_its_bytes() { - /// A writer that takes at most 7 bytes per call. - struct Short(Vec); - impl std::io::Write for Short { - fn write(&mut self, bytes: &[u8]) -> std::io::Result { - let n = bytes.len().min(7); - self.0.extend_from_slice(&bytes[..n]); - Ok(n) - } - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } - } - let dev = device("moltenvk-m3"); - let Some((_, mut p)) = store_const(&dev) else { - return; - }; - let blob: std::sync::Arc<[u8]> = (0..3 * CHUNK + 7).map(|i| (i % 251) as u8 + 1).collect(); - p.stage.constant_blob = Some(blob); - let bytes = p.to_bytes(); - let mut whole = Vec::new(); - p.write_to(&mut whole).expect("write"); - assert_eq!(whole, bytes); - let mut short = Short(Vec::new()); - p.write_to(&mut short).expect("write"); - assert_eq!(short.0, bytes); - assert_eq!(ComputePipeline::from_bytes(&bytes, &dev), Ok(p)); -} - /// The frame layout is stable: a change fails here and needs an `ARTIFACT_FORMAT_VERSION` bump. #[test] fn the_frame_layout_is_pinned() { diff --git a/crates/metal2vulkan/src/device/check.rs b/crates/metal2vulkan/src/device/check.rs index ba885b679..d5564e7ea 100644 --- a/crates/metal2vulkan/src/device/check.rs +++ b/crates/metal2vulkan/src/device/check.rs @@ -180,16 +180,12 @@ impl DeviceProfile { VkLimit::MaxPerStageDescriptorStorageImages => { up(l.max_per_stage_descriptor_storage_images) } - VkLimit::MaxPerStageDescriptorInputAttachments => { - up(l.max_per_stage_descriptor_input_attachments) - } VkLimit::MaxPerStageResources => up(l.max_per_stage_resources), VkLimit::MaxDescriptorSetSamplers => up(l.max_descriptor_set_samplers), VkLimit::MaxDescriptorSetUniformBuffers => up(l.max_descriptor_set_uniform_buffers), VkLimit::MaxDescriptorSetStorageBuffers => up(l.max_descriptor_set_storage_buffers), VkLimit::MaxDescriptorSetSampledImages => up(l.max_descriptor_set_sampled_images), VkLimit::MaxDescriptorSetStorageImages => up(l.max_descriptor_set_storage_images), - VkLimit::MaxDescriptorSetInputAttachments => up(l.max_descriptor_set_input_attachments), VkLimit::MaxDescriptorSetUpdateAfterBindSamplers => { up(l.max_descriptor_set_update_after_bind_samplers) } diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index 476ebcbc6..86c401fc1 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -1,7 +1,7 @@ //! `Device::from_queries`: the only producer of a `DeviceProfile`. //! -//! The profile is a pure function of the description's Vulkan queries and the policy: no driver or -//! GPU identity decides anything. Memory's A/F split is the +//! The profile is a pure function of the description's Vulkan queries: no driver or GPU identity +//! decides anything. Memory's A/F split is the //! only field that selects a pointer model; every other field selects leaf encodings or feeds the //! requirement check. @@ -13,22 +13,21 @@ use crate::device::description::{ }; use crate::device::function_storage; use crate::device::metal::MetalDeviceProperties; -use crate::device::policy::DevicePolicy; use crate::device::profile::{ BufferAccess, DescriptorCaps, DeviceProfile, EnabledCaps, FormatTable, FragmentCaps, - FunctionStorage, HandleDomain, ImageCaps, Independence, LeafCaps, PointerDomain, ProfileFields, + FunctionStorage, ImageCaps, Independence, LeafCaps, ProfileFields, }; use crate::device::requirements::{ ApiVersion, FloatControl, FloatWidth, FormatUsage, ResolveMode, SubgroupOp, VkExtension, VkFeature, VkLimit, VkProperty, }; use crate::device::subgroup::{OpBits, StageSubgroup, SubgroupModel, SubgroupSizes}; -use crate::error::{Capability, DescriptorError, Error, Feature, Unsupported}; +use crate::error::{Capability, Error, Feature, Unsupported}; use crate::pipeline::sym::Stage; use crate::vk; -/// A device the core translates for: its profile, the Metal properties the consumer reports to -/// the guest, and the policy it was created with. Cheap to clone; `Send + Sync`. +/// A device the core translates for: its profile and the Metal properties the consumer reports to +/// the guest. Cheap to clone; `Send + Sync`. #[derive(Clone, Debug)] pub struct Device(Arc); @@ -38,7 +37,6 @@ struct DeviceInner { /// `profile`'s fingerprint, computed once: every key and artifact check takes it. fingerprint: crate::cache::Hash256, metal: MetalDeviceProperties, - policy: DevicePolicy, /// The description's `generated_commands`, which only the device replay reads. No translation /// reads it, so it is not a profile field: two devices that differ only in it share every /// artifact. @@ -49,8 +47,9 @@ struct DeviceInner { } impl Device { - /// The device its Vulkan queries decide, under `policy`: the profile is a function of what - /// the description states the device supports and the consumer enabled, and of the policy. + /// The device its Vulkan queries decide: the profile is a function of what the description + /// states the device supports and the consumer enabled. A pointer is the device address it + /// holds and a texture's or sampler's handle is its `gpuResourceID` (the identity domains). /// The description need not come from a device: one read from a Khronos profiles JSON document /// ([`DeviceDescription::from_khronos_json`]) or built field by field /// ([`DeviceDescription::new`]) makes a device with no `VkDevice` behind it. @@ -62,10 +61,8 @@ impl Device { /// a feature neither its version nor its listed extensions expose, a feature without the /// feature Vulkan requires enabled with it, or `shaderQuadControl` without /// `shaderMaximalReconvergence`, which every device with the one supports (`InvalidDescriptor`, - /// the invariants `device::enables` states), a policy that turns containment off while guest isolation - /// is on (`InvalidDescriptor`), a policy that takes one identity domain without the other - /// (`InvalidDescriptor`), and the identity domains on a device without `bufferDeviceAddress` - /// and `shaderInt64` (`Unsupported{IdentityDomains}`). + /// the invariants `device::enables` states), and a device without `bufferDeviceAddress` and + /// `shaderInt64`, which the identity domains need (`Unsupported{IdentityDomains}`). /// /// No identity decides anything: the description's `driver_id`, `driver_version`, /// `vendor_id`, `device_id` and `device_name` are not read. The rasterizer splits clipped @@ -74,7 +71,7 @@ impl Device { /// `PrecisionNote::TessellationTriangleOrder`), `InterpolateAtOffset` reads from the pixel's center as GLSL.std.450 states, and a thread's /// Function storage is the 16 KiB floor. Every stage output is 32-bit: a `half` color output /// reaches the device widened to `float`, whatever `storageInputOutput16` says. - pub fn from_queries(desc: DeviceDescription, policy: DevicePolicy) -> Result { + pub fn from_queries(desc: DeviceDescription) -> Result { if desc.api_version < ApiVersion::V1_2 { return Err(Unsupported::needs( Feature::VulkanVersion, @@ -95,14 +92,13 @@ impl Device { .into()); } crate::device::enables::check_invariants(&desc)?; - identity_domains(&desc, &policy)?; - let profile = DeviceProfile::of(derive_fields(&desc, &policy)); + identity_domains(&desc)?; + let profile = DeviceProfile::of(derive_fields(&desc)); let metal = MetalDeviceProperties::derive(&profile, &desc.allocation); Ok(Device(Arc::new(DeviceInner { fingerprint: profile.fingerprint(), profile, metal, - policy, generated_commands: desc.generated_commands, allocation: desc.allocation, }))) @@ -125,11 +121,6 @@ impl Device { &self.0.metal } - /// The policy the device was created with. - pub fn policy(&self) -> &DevicePolicy { - &self.0.policy - } - /// `VK_EXT_device_generated_commands` as the description states the consumer enabled it: the /// limits and stages the device replay's generated-commands layout is held to. It is not part /// of [`Device::profile`], so it changes no artifact. @@ -145,27 +136,18 @@ impl Device { } } -/// The identity domains come as a pair, and need device addresses and 64-bit integers: a -/// pointer is a 64-bit device address. -fn identity_domains(desc: &DeviceDescription, policy: &DevicePolicy) -> Result<(), Error> { - let pointers = policy.pointer_domain == PointerDomain::Identity; - let handles = policy.handle_domain == HandleDomain::Identity; - if pointers != handles { - return Err(Error::InvalidDescriptor( - DescriptorError::DeviceDescription { - detail: "the identity pointer and handle domains are taken together".into(), - }, - )); - } +/// The identity domains need device addresses and 64-bit integers: a pointer is a 64-bit device +/// address. +fn identity_domains(desc: &DeviceDescription) -> Result<(), Error> { let needs = [VkFeature::BufferDeviceAddress, VkFeature::ShaderInt64]; - if pointers && !needs.iter().all(|&f| desc.has(f)) { + if !needs.iter().all(|&f| desc.has(f)) { let all = needs.iter().map(|&f| Capability::Feature(f)).collect(); return Err(Unsupported::needs_any_of(Feature::IdentityDomains, vec![all]).into()); } Ok(()) } -fn derive_fields(desc: &DeviceDescription, policy: &DevicePolicy) -> ProfileFields { +fn derive_fields(desc: &DeviceDescription) -> ProfileFields { let has = |f: VkFeature| desc.has(f); let ext = |e: VkExtension| desc.extensions.contains(&e); let api = desc.api_version; @@ -258,8 +240,6 @@ fn derive_fields(desc: &DeviceDescription, policy: &DevicePolicy) -> ProfileFiel let (vertex_formats, storage_formats, image_formats) = format_tables(desc); ProfileFields { buffer_access, - pointer_domain: policy.pointer_domain, - handle_domain: policy.handle_domain, leaf, subgroup: subgroup_model(desc), images, diff --git a/crates/metal2vulkan/src/device/description.rs b/crates/metal2vulkan/src/device/description.rs index 77a586193..57c647e0b 100644 --- a/crates/metal2vulkan/src/device/description.rs +++ b/crates/metal2vulkan/src/device/description.rs @@ -16,9 +16,8 @@ use crate::vk; /// One Vulkan physical device as the consumer will create it. /// -/// With feature `serde` it (and [`DevicePolicy`](crate::device::DevicePolicy)) serializes, so a -/// consumer that compiles in a child process can hand the child the pair from which it rebuilds -/// the same `Device` (`docs/HOWTO.md` section 5). +/// With feature `serde` it serializes, so a consumer that compiles in a child process can hand the +/// child the description from which it rebuilds the same `Device` (`docs/HOWTO.md` section 5). #[non_exhaustive] #[derive(Clone, Debug, PartialEq, Eq)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] diff --git a/crates/metal2vulkan/src/device/khronos.rs b/crates/metal2vulkan/src/device/khronos.rs index d83fdb349..4463a5c29 100644 --- a/crates/metal2vulkan/src/device/khronos.rs +++ b/crates/metal2vulkan/src/device/khronos.rs @@ -743,15 +743,12 @@ fn limits(p: &Props<'_>, api: ApiVersion, extensions: &BTreeSet) -> Resu max_per_stage_descriptor_storage_buffers: p.u32("maxPerStageDescriptorStorageBuffers")?, max_per_stage_descriptor_sampled_images: p.u32("maxPerStageDescriptorSampledImages")?, max_per_stage_descriptor_storage_images: p.u32("maxPerStageDescriptorStorageImages")?, - max_per_stage_descriptor_input_attachments: p - .u32("maxPerStageDescriptorInputAttachments")?, max_per_stage_resources: p.u32("maxPerStageResources")?, max_descriptor_set_samplers: p.u32("maxDescriptorSetSamplers")?, max_descriptor_set_uniform_buffers: p.u32("maxDescriptorSetUniformBuffers")?, max_descriptor_set_storage_buffers: p.u32("maxDescriptorSetStorageBuffers")?, max_descriptor_set_sampled_images: p.u32("maxDescriptorSetSampledImages")?, max_descriptor_set_storage_images: p.u32("maxDescriptorSetStorageImages")?, - max_descriptor_set_input_attachments: p.u32("maxDescriptorSetInputAttachments")?, max_descriptor_set_update_after_bind_samplers: p .u32("maxDescriptorSetUpdateAfterBindSamplers")?, max_descriptor_set_update_after_bind_sampled_images: p @@ -966,14 +963,12 @@ fn required_limits(version: ApiVersion) -> Vec<(&'static str, Value)> { ("maxPerStageDescriptorStorageBuffers", n(4)), ("maxPerStageDescriptorSampledImages", n(16)), ("maxPerStageDescriptorStorageImages", n(4)), - ("maxPerStageDescriptorInputAttachments", n(4)), ("maxPerStageResources", n(128)), ("maxDescriptorSetSamplers", n(96)), ("maxDescriptorSetUniformBuffers", n(72)), ("maxDescriptorSetStorageBuffers", n(24)), ("maxDescriptorSetSampledImages", n(96)), ("maxDescriptorSetStorageImages", n(24)), - ("maxDescriptorSetInputAttachments", n(4)), ("maxVertexInputAttributes", n(16)), ("maxVertexInputBindings", n(16)), ("maxVertexInputAttributeOffset", n(2047)), diff --git a/crates/metal2vulkan/src/device/mechanism.rs b/crates/metal2vulkan/src/device/mechanism.rs index 335ef53a3..812476f42 100644 --- a/crates/metal2vulkan/src/device/mechanism.rs +++ b/crates/metal2vulkan/src/device/mechanism.rs @@ -22,12 +22,7 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::ResourcePresence { .. } => Mechanism::Specialization, RuntimeFact::SampleCount => Mechanism::Specialization, // Keyed by a per-slot StorageImageChoice, a separate per-function compile. - RuntimeFact::StorageTextureFormat { .. } - | RuntimeFact::StorageTextureNumericType { .. } => Mechanism::Variant, - // Keyed by the slots bound to an sRGB format's UNORM twin, whose codes the function decodes. - RuntimeFact::SrgbTexture { .. } => Mechanism::Variant, - RuntimeFact::SamplerCoordinates { .. } => Mechanism::Specialization, - RuntimeFact::SamplerReduction { .. } => Mechanism::PlanTimeCheck, + RuntimeFact::StorageTextureNumericType { .. } => Mechanism::Variant, RuntimeFact::ImageViewShape { .. } => Mechanism::BinderView, RuntimeFact::VertexFetch { .. } => Mechanism::KeyProjection, RuntimeFact::VertexBufferStride { .. } => { @@ -45,24 +40,7 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { } } RuntimeFact::DeviceAddresses { .. } => Mechanism::PlanTimeCheck, - // F: DescriptorRangeExceeded at plan time; A: a variant that makes the slot PSB. - RuntimeFact::BufferRangeLimit { .. } => match f.buffer_access { - BufferAccess::Addressed => Mechanism::Variant, - BufferAccess::Floor => Mechanism::PlanTimeCheck, - }, - RuntimeFact::TexelBufferRange { .. } => Mechanism::PlanTimeCheck, RuntimeFact::FramebufferFetch { .. } => Mechanism::RenderPassContract, - // A function that writes the status buffer reaches it at the device address the binder - // writes into its push field (`PushField::ExecutionStatusAddress`), or, on a device that - // does not address buffers, through the stage's binding of it - // (`SyntheticBinding::ExecutionStatus`). - RuntimeFact::ExecutionStatus => match f.buffer_access { - BufferAccess::Addressed => Mechanism::PushConstant, - BufferAccess::Floor => Mechanism::SyntheticBinding, - }, - // The binder writes each heap element from the texture's facts and reports a texture - // the class cannot hold. - RuntimeFact::HeapNumericType { .. } => Mechanism::BinderView, // The scratch's length is a specialization of the local size; the planner checks each // region's total against the limit. RuntimeFact::SimdgroupEmulation { .. } => Mechanism::PlanTimeCheck, @@ -86,13 +64,8 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { // The binder specializes the alpha from the bound texture's pixel format. RuntimeFact::OutOfBoundsAlpha { .. } => Mechanism::Specialization, RuntimeFact::BorderTexels { .. } => Mechanism::Specialization, - // The bound format's treatment is specialized; the planner refuses an unmeasured - // format. - RuntimeFact::BicubicTexels { .. } => Mechanism::Specialization, // The binder writes the bound texture's level count per draw or dispatch. RuntimeFact::StorageTextureLevels { .. } => Mechanism::PushConstant, - // The binder writes the bound texture's integer channel widths. - RuntimeFact::StorageTextureIntegerChannels { .. } => Mechanism::PushConstant, // The binder views each level of the bound texture at its element. RuntimeFact::StorageTextureLevelViews { .. } => Mechanism::BinderView, // The bound texture's sparseness selects the sparse form or the tile map where the module @@ -128,10 +101,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { // A pipeline compiled under the flat-grid variant; its plans state it. RuntimeFact::FlatGrid => Mechanism::Variant, RuntimeFact::CallThreadgroups => Mechanism::Variant, - // A sparse texture's writes are dropped under the slot's `SparseTexture` specialization; - // at a slot updated atomically the planner refuses one. - RuntimeFact::SparseTextureWrites { atomic: false, .. } => Mechanism::Specialization, - RuntimeFact::SparseTextureWrites { atomic: true, .. } => Mechanism::PlanTimeCheck, // The offsets and the tile memory are specialized; the pass binds its tile memory. RuntimeFact::TileThreadgroupMemory { .. } => Mechanism::Specialization, // The binder checks the object function's arena with the encoder's lengths, which it @@ -166,8 +135,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { RuntimeFact::StencilBitDraws => Mechanism::PushConstant, // The pipeline's robustness, which the consumer states as it makes it. RuntimeFact::RobustStorageBuffers => Mechanism::PipelineState, - // Keyed by the slots bound to a texture buffer of more texels than one view holds. - RuntimeFact::TexelBufferParts { .. } => Mechanism::Variant, // The runtime refuses a dispatch whose slot address is not a multiple of the alignment. RuntimeFact::AddressAlignment { .. } => Mechanism::PlanTimeCheck, // A separate compile of the pipeline, which a pass with colors the pipeline lacks asks @@ -180,8 +147,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { // A separate link of the mesh pipeline's synthesized vertex stage. // The binder's region flags a draw whose last object threadgroup along an axis is partial. RuntimeFact::PartialObjectThreadgroups => Mechanism::RegionSelected, - // The binder specializes the lanes from the bound texture's pixel format and swizzle. - RuntimeFact::ConstantLanes { .. } => Mechanism::Specialization, // A separate compile that reads the tables' words through their device addresses, which // a shape whose tables may pass `maxStorageBufferRange` asks for; without device // addresses the binder refuses such a table where it binds it. @@ -192,29 +157,5 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism { // The binder's regions carry the tile as Metal's threadgroup; the tile pipeline checks its // descriptor's flag. RuntimeFact::TileThreadgroup { .. } => Mechanism::RegionSelected, - // Keyed by the slots a constexpr sampler samples whose bound texture's address-mode map - // is not the identity. - RuntimeFact::ConstexprSampled { .. } => Mechanism::Variant, - // Keyed by the slots bound to a cubic sampler, with its state. - RuntimeFact::CubicSampler { .. } => Mechanism::Variant, - // The planner admits a listed cubic sampler beside the stage's sampler table; the - // function marks the `ExecutionStatus` buffer where it reaches one. - RuntimeFact::CubicArgumentSampler { .. } => Mechanism::PlanTimeCheck, - // The planner refuses a texture a heap holds by its raw texels alone that a plan names - // beside the stage; a consumer's own heap announces one. - RuntimeFact::HeapRawSamples { .. } => Mechanism::PlanTimeCheck, - // Keyed by the slots bound in a format of another numeric class than the declared one, - // whose texels the function reads in that class. - RuntimeFact::CrossClassReads { .. } => Mechanism::Variant, - // The planner reports a member of another numeric class the stage reaches in the class. - RuntimeFact::HeapCrossClassNeutral { .. } => Mechanism::PlanTimeCheck, - // The planner refuses a sparse texture the stage's handle tables reach. - RuntimeFact::HeapResidency { .. } => Mechanism::PlanTimeCheck, - // The planner refuses a texture of a dropped or shadowed write the stage reaches in a - // storage class it reads. - RuntimeFact::HeapStorageReads { .. } => Mechanism::PlanTimeCheck, - // Keyed by the slots bound to a sampler whose word states anisotropy, where the - // function's samples take Metal's anisotropic filter, emulated. - RuntimeFact::AnisotropicSampler { .. } => Mechanism::Variant, } } diff --git a/crates/metal2vulkan/src/device/mod.rs b/crates/metal2vulkan/src/device/mod.rs index e3315b958..3573e3688 100644 --- a/crates/metal2vulkan/src/device/mod.rs +++ b/crates/metal2vulkan/src/device/mod.rs @@ -1,4 +1,4 @@ -//! The device a pipeline is compiled for: what the consumer enabled, and its policy. +//! The device a pipeline is compiled for: what the consumer enabled. //! //! A [`DeviceDescription`] states one Vulkan physical device as the consumer creates it: its API //! version, the features and extensions it enables, its limits, subgroup and float-controls @@ -12,18 +12,18 @@ //! what is enabled. Translation uses only what the description enables. //! //! [`Device::from_queries`] derives an opaque [`DeviceProfile`] from the description's Vulkan -//! queries and a [`DevicePolicy`], the consumer's product choices (the pointer and handle -//! domains; the default is the runtime's, the identity domains); no -//! driver or GPU identity decides anything, and no `VkDevice` is needed. It refuses a device below Vulkan -//! 1.2 and an inconsistent description or policy. A [`Device`] is cheap to clone, and every -//! compile and plan takes one: +//! queries; no driver or GPU identity decides anything, and no `VkDevice` is needed. A pointer is +//! the device address it holds and a texture's or sampler's handle is its `gpuResourceID` (the +//! identity domains), so it refuses a device without `bufferDeviceAddress` and `shaderInt64`, +//! as it refuses a device below Vulkan 1.2 and an inconsistent description. A [`Device`] is cheap +//! to clone, and every compile and plan takes one: //! //! - [`Device::compile_function`], [`Device::compile_compute_pipeline`], //! [`Device::compile_render_pipeline`], and their keys (see [`pipeline`](crate::pipeline)); //! - [`Device::required_enables`]: everything an artifact compiled for the device can need //! enabled; //! - [`Device::metal_properties`]: the Metal device properties to report to the guest; -//! - [`DeviceProfile::fingerprint`]: a hash over every profile field, policy included, which +//! - [`DeviceProfile::fingerprint`]: a hash over every profile field, which //! every cache key includes, so an artifact never serves another device. //! //! A consumer that creates its own `VkDevice` sets each feature of an [`EnableSet`] in the @@ -47,7 +47,6 @@ pub(crate) mod function_storage; pub(crate) mod khronos; pub(crate) mod mechanism; pub(crate) mod metal; -pub(crate) mod policy; pub(crate) mod profile; pub(crate) mod requirements; pub(crate) mod subgroup; @@ -61,14 +60,13 @@ pub use enables::{EnableSet, Exposure}; // The mechanism derivation: internal; a pipeline states each mechanism in its `dependencies`. pub(crate) use mechanism::mechanism; pub use metal::{MetalDeviceProperties, SimdSupport, StageSimd}; -pub use policy::DevicePolicy; pub(crate) use profile::whole_point_size; pub use profile::{DeviceProfile, SpirvValidation, IDENTITY_BUFFER_BYTES, KERNEL_BUFFER_BINDINGS}; -// The vocabulary the device surface reaches: description and policy inputs, and the requirement +// The vocabulary the device surface reaches: description inputs, and the requirement // vocabulary of `Requirements`, `Capability`, and `DeviceDescription`. pub use profile::{ - EnabledCaps, FloatControls, FloatWidthControls, FragmentCaps, HandleDomain, ImageCaps, - Independence, Limits, MeshLimits, PointerDomain, + EnabledCaps, FloatControls, FloatWidthControls, FragmentCaps, ImageCaps, Independence, Limits, + MeshLimits, }; // The profile's facts a consumer or a validation tool reads: its descriptor capabilities, its // subgroup model and simdgroup tiers, and the Function storage a thread holds. diff --git a/crates/metal2vulkan/src/device/policy.rs b/crates/metal2vulkan/src/device/policy.rs deleted file mode 100644 index a6d19835b..000000000 --- a/crates/metal2vulkan/src/device/policy.rs +++ /dev/null @@ -1,45 +0,0 @@ -//! `DevicePolicy`: the consumer's product choices that, together with a `DeviceDescription`, -//! decide a `DeviceProfile`. - -use crate::device::profile::{HandleDomain, PointerDomain}; - -/// Policy inputs of `Device::from_queries`. Every field can change emitted code, so the profile -/// carries it and its fingerprint covers it. -/// -/// [`DevicePolicy::default`] is the one constructor: the runtime compiles under it, and the -/// command line, the compile worker, the validation executor and every validation tool take -/// their policy from it, so a tool compiles what the runtime does. Nothing in the tree builds -/// [`DevicePolicy::RESIDENT_TABLES`] outside tests. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct DevicePolicy { - /// How pointer values resolve to resources: `Identity` with `handle_domain` `Identity` (the - /// default), or `ResidentTable` with `Table` (`RESIDENT_TABLES`, which only tests build). - pub pointer_domain: PointerDomain, - /// How resource handles resolve: `Identity` with `pointer_domain` `Identity` (the default), or - /// `Table` with `ResidentTable` (`RESIDENT_TABLES`, which only tests build). - pub handle_domain: HandleDomain, -} - -impl DevicePolicy { - /// A resident table of pointers and a handle table. Nothing in the tree builds it outside - /// tests: the runtime, the tools and the validation executor take the default. - pub const RESIDENT_TABLES: DevicePolicy = DevicePolicy { - pointer_domain: PointerDomain::ResidentTable, - handle_domain: HandleDomain::Table, - }; -} - -impl Default for DevicePolicy { - /// The identity domains, the runtime's: a pointer is the device address it holds and a - /// texture's or sampler's handle is its `gpuResourceID` ([`PointerDomain::Identity`], - /// [`HandleDomain::Identity`]). `Device::from_queries` refuses them on a device without - /// `bufferDeviceAddress` and `shaderInt64` (`Feature::IdentityDomains`). - fn default() -> DevicePolicy { - DevicePolicy { - pointer_domain: PointerDomain::Identity, - handle_domain: HandleDomain::Identity, - } - } -} diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 85b947607..7b56bc173 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -1,8 +1,8 @@ //! `DeviceProfile` and its translation-relevant fields. //! -//! `Device::from_queries(desc, policy)` is the only producer of a [`DeviceProfile`]. The profile is the -//! normalized projection of a device description plus the policy; lowering selects representations -//! from it and nothing else. Derivation lives in `device::derive`, the fingerprint in +//! `Device::from_queries(desc)` is the only producer of a [`DeviceProfile`]. The profile is the +//! normalized projection of a device description; lowering selects representations from it and +//! nothing else. Derivation lives in `device::derive`, the fingerprint in //! [`DeviceProfile::fingerprint`]. use std::collections::{BTreeMap, BTreeSet}; @@ -144,8 +144,7 @@ impl DeviceProfile { l.max_descriptor_set_update_after_bind_storage_buffers, l.max_per_stage_resources, ]; - f.pointer_domain == PointerDomain::Identity - && f.enabled.features.contains(&VkFeature::PipelineRobustness) + f.enabled.features.contains(&VkFeature::PipelineRobustness) && l.robust_buffer_access2 && l.robust_buffer_access_update_after_bind && buffers.iter().all(|&limit| limit >= KERNEL_BUFFER_BINDINGS) @@ -315,7 +314,7 @@ impl DeviceProfile { } } - /// A SHA-256 over **every** field, policy included. + /// A SHA-256 over **every** field. /// /// The encoding is the derived `Debug` rendering of the profile's fields under a versioned /// domain tag: it is total by construction (a new field is hashed without further code) and @@ -383,13 +382,11 @@ pub const KERNEL_BUFFER_BINDINGS: u32 = 31; /// whose accesses add 32-bit offsets read as signed to its address (`docs/API.md` section 1). pub const IDENTITY_BUFFER_BYTES: u64 = 1 << 31; -/// Every field of a profile, policy included. The fingerprint hashes all of them. +/// Every field of a profile. The fingerprint hashes all of them. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProfileFields { /// Memory's A/F split. pub buffer_access: BufferAccess, - pub pointer_domain: PointerDomain, - pub handle_domain: HandleDomain, pub leaf: LeafCaps, pub subgroup: SubgroupModel, pub images: ImageCaps, @@ -483,45 +480,6 @@ pub enum BufferAccess { Floor, } -/// How pointer values are resolved to resources. A device takes `Identity` only with -/// [`HandleDomain::Identity`], and the other two together. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum PointerDomain { - /// The sorted resident set of bound arguments and used resources. Nothing in the tree - /// builds it outside tests - /// ([`DevicePolicy::RESIDENT_TABLES`](crate::device::DevicePolicy::RESIDENT_TABLES)): the - /// runtime, the tools and the validation executor take `Identity`. - ResidentTable, - /// Pointers are device addresses used directly: a `device` or `constant` pointer is the - /// 64-bit Vulkan device address of the byte it names, as Metal's `gpuAddress` is, and a - /// buffer slot is reached at its own address, pushed, and a pointer loaded from - /// memory or made from an integer is the address it holds, used directly. Needs - /// `bufferDeviceAddress` and `shaderInt64`. So far it lowers a kernel that reaches memory - /// only through its buffer slots and such addresses, and, on `Device::from_queries`' profile, - /// a vertex or fragment function that does; any other function is refused as - /// [`Feature::IdentityDomains`](crate::error::Feature::IdentityDomains). - Identity, -} - -/// How resource handles are resolved. A device takes `Identity` only with -/// [`PointerDomain::Identity`], and the other two together. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum HandleDomain { - /// The handle table plus the set-1 heap. Nothing in the tree builds it outside tests - /// ([`DevicePolicy::RESIDENT_TABLES`](crate::device::DevicePolicy::RESIDENT_TABLES)): the - /// runtime, the tools and the validation executor take `Identity`. - Table, - /// A texture's or sampler's handle is its `gpuResourceID`: the low 32 bits index the - /// pipeline's descriptor arrays and the high 32 bits are the word of its Metal descriptor - /// (`docs/RESOURCE-ID.md`). A texture or sampler use with no form under it is refused as - /// [`Feature::IdentityDomains`](crate::error::Feature::IdentityDomains). - Identity, -} - /// Leaf arithmetic, storage, and atomic capabilities. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] pub struct LeafCaps { @@ -679,14 +637,12 @@ pub struct Limits { pub max_per_stage_descriptor_storage_buffers: u32, pub max_per_stage_descriptor_sampled_images: u32, pub max_per_stage_descriptor_storage_images: u32, - pub max_per_stage_descriptor_input_attachments: u32, pub max_per_stage_resources: u32, pub max_descriptor_set_samplers: u32, pub max_descriptor_set_uniform_buffers: u32, pub max_descriptor_set_storage_buffers: u32, pub max_descriptor_set_sampled_images: u32, pub max_descriptor_set_storage_images: u32, - pub max_descriptor_set_input_attachments: u32, pub max_descriptor_set_update_after_bind_samplers: u32, pub max_descriptor_set_update_after_bind_sampled_images: u32, pub max_descriptor_set_update_after_bind_storage_images: u32, diff --git a/crates/metal2vulkan/src/device/requirements.rs b/crates/metal2vulkan/src/device/requirements.rs index 31c4788c4..23c80d781 100644 --- a/crates/metal2vulkan/src/device/requirements.rs +++ b/crates/metal2vulkan/src/device/requirements.rs @@ -686,14 +686,12 @@ pub enum VkLimit { MaxPerStageDescriptorStorageBuffers, MaxPerStageDescriptorSampledImages, MaxPerStageDescriptorStorageImages, - MaxPerStageDescriptorInputAttachments, MaxPerStageResources, MaxDescriptorSetSamplers, MaxDescriptorSetUniformBuffers, MaxDescriptorSetStorageBuffers, MaxDescriptorSetSampledImages, MaxDescriptorSetStorageImages, - MaxDescriptorSetInputAttachments, MaxDescriptorSetUpdateAfterBindSamplers, MaxDescriptorSetUpdateAfterBindSampledImages, MaxDescriptorSetUpdateAfterBindStorageImages, diff --git a/crates/metal2vulkan/src/device/tests/description.rs b/crates/metal2vulkan/src/device/tests/description.rs index 52656dff1..78e2c9797 100644 --- a/crates/metal2vulkan/src/device/tests/description.rs +++ b/crates/metal2vulkan/src/device/tests/description.rs @@ -184,7 +184,7 @@ fn divisor_first_instance_support_follows_exposure() { } /// `rgba4OpaqueBlackSwizzled` is read where `VK_KHR_maintenance10` is exposed and is an enabled -/// property when true; MoltenVK's capture has no maintenance10, so it is false there. +/// property when true (lavapipe's); MoltenVK's capture has no maintenance10, so it is false there. #[test] fn rgba4_opaque_black_swizzled_follows_exposure() { use crate::device::requirements::VkProperty; @@ -199,8 +199,7 @@ fn rgba4_opaque_black_swizzled_follows_exposure() { ); let d = DeviceDescription::from_khronos_json(&with, None).unwrap(); assert!(d.rgba4_opaque_black_swizzled); - let dev = crate::device::Device::from_queries(d, crate::device::DevicePolicy::RESIDENT_TABLES) - .unwrap(); + let dev = crate::device::Device::from_queries(profile("lavapipe")).unwrap(); assert!(dev .profile() .fields() @@ -743,45 +742,35 @@ fn required_features_are_cumulative() { assert!(v13.contains(&VkFeature::SubgroupSizeControl)); } -/// With feature `serde`, every committed description and both policies survive a JSON round trip -/// unchanged, and the `Device` rebuilt from the decoded pair has the original's profile -/// fingerprint, or, where the description cannot take the policy (the identity domains without -/// `bufferDeviceAddress` and `shaderInt64`), the same refusal: what an out-of-process compile -/// worker needs to compile for the consumer's device (worker recipe step 1). +/// With feature `serde`, every committed description survives a JSON round trip unchanged, and the +/// `Device` rebuilt from the decoded description has the original's profile fingerprint, or, where +/// the description cannot take the identity domains (without `bufferDeviceAddress` and +/// `shaderInt64`), the same refusal: what an out-of-process compile worker needs to compile for the +/// consumer's device (worker recipe step 1). #[cfg(feature = "serde")] #[test] -fn descriptions_and_policies_round_trip_through_serde() { - let identity = DevicePolicy { - pointer_domain: crate::device::PointerDomain::Identity, - handle_domain: crate::device::HandleDomain::Identity, - }; - let policies = [DevicePolicy::RESIDENT_TABLES, identity]; +fn descriptions_round_trip_through_serde() { for (stem, text) in committed_profiles() { let description = DeviceDescription::from_khronos_json(&text, None).unwrap(); let json = serde_json::to_string(&description).unwrap(); let decoded: DeviceDescription = serde_json::from_str(&json).unwrap(); assert_eq!(decoded, description, "{stem}"); - for policy in policies { - let policy_json = serde_json::to_string(&policy).unwrap(); - let decoded_policy: DevicePolicy = serde_json::from_str(&policy_json).unwrap(); - assert_eq!(decoded_policy, policy, "{stem}"); - let original = Device::from_queries(description.clone(), policy); - let rebuilt = Device::from_queries(decoded.clone(), decoded_policy); - match (original, rebuilt) { - (Ok(original), Ok(rebuilt)) => assert_eq!( - rebuilt.profile().fingerprint(), - original.profile().fingerprint(), - "{stem}" - ), - (Err(original), Err(rebuilt)) => { - assert_eq!(rebuilt.to_string(), original.to_string(), "{stem}") - } - (original, rebuilt) => panic!( - "{stem}: the original derives {}, the decoded pair {}", - original.is_ok(), - rebuilt.is_ok() - ), + let original = Device::from_queries(description.clone()); + let rebuilt = Device::from_queries(decoded.clone()); + match (original, rebuilt) { + (Ok(original), Ok(rebuilt)) => assert_eq!( + rebuilt.profile().fingerprint(), + original.profile().fingerprint(), + "{stem}" + ), + (Err(original), Err(rebuilt)) => { + assert_eq!(rebuilt.to_string(), original.to_string(), "{stem}") } + (original, rebuilt) => panic!( + "{stem}: the original derives {}, the decoded description {}", + original.is_ok(), + rebuilt.is_ok() + ), } } } diff --git a/crates/metal2vulkan/src/device/tests/enables.rs b/crates/metal2vulkan/src/device/tests/enables.rs index 9f8898425..a099cd317 100644 --- a/crates/metal2vulkan/src/device/tests/enables.rs +++ b/crates/metal2vulkan/src/device/tests/enables.rs @@ -97,10 +97,9 @@ fn recommendations_are_closed_fixed_points_on_every_committed_profile() { .clone() .with_enabled(&rec) .unwrap_or_else(|e| panic!("{stem}: {e}")); - let dev = Device::from_queries(restricted, DevicePolicy::RESIDENT_TABLES) - .unwrap_or_else(|e| panic!("{stem}: {e}")); + let dev = Device::from_queries(restricted).unwrap_or_else(|e| panic!("{stem}: {e}")); assert_eq!(dev.required_enables(), rec, "{stem}"); - let full = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap(); + let full = Device::from_queries(desc.clone()).unwrap(); assert_eq!(full.required_enables(), rec, "{stem}"); assert_eq!( rec.extensions.contains(&VkExtension::KhrPortabilitySubset), @@ -191,11 +190,7 @@ fn extended_dynamic_state2_is_enabled_below_1_3_and_implied_from_it() { assert!(rec.extensions.contains(&extension), "{extension:?}"); assert!(rec.features.contains(&feature), "{feature:?}"); } - let dev = Device::from_queries( - d.clone().with_enabled(&rec).unwrap(), - DevicePolicy::RESIDENT_TABLES, - ) - .unwrap(); + let dev = Device::from_queries(d.clone().with_enabled(&rec).unwrap()).unwrap(); let enabled = &dev.profile().fields().enabled; assert!(enabled.features.contains(&VkFeature::ExtendedDynamicState2)); assert!(enabled @@ -328,13 +323,13 @@ fn device_new_refuses_a_feature_without_its_companion() { } let mut d = floor_with(&[], &[f]); d.features.remove(&needs); - let e = match Device::from_queries(d.clone(), DevicePolicy::RESIDENT_TABLES) { + let e = match Device::from_queries(d.clone()) { Err(Error::InvalidDescriptor(DescriptorError::DeviceDescription { detail })) => detail, other => panic!("{other:?}"), }; assert!(e.contains(vuid), "{e}"); d.features.insert(needs); - Device::from_queries(d, DevicePolicy::RESIDENT_TABLES).unwrap(); + Device::from_queries(d).unwrap(); } } @@ -359,7 +354,7 @@ fn device_new_refuses_quad_control_without_maximal_reconvergence() { ], &[VkFeature::ShaderQuadControl], ); - let e = match Device::from_queries(d.clone(), DevicePolicy::RESIDENT_TABLES) { + let e = match Device::from_queries(d.clone()) { Err(Error::InvalidDescriptor(DescriptorError::DeviceDescription { detail })) => detail, other => panic!("{other:?}"), }; @@ -368,7 +363,7 @@ fn device_new_refuses_quad_control_without_maximal_reconvergence() { "{e}" ); d.features.insert(VkFeature::ShaderMaximalReconvergence); - let device = Device::from_queries(d, DevicePolicy::RESIDENT_TABLES).unwrap(); + let device = Device::from_queries(d).unwrap(); let model = &device.profile().fields().subgroup; assert!(model.quad_control && model.maximal_reconvergence); } @@ -597,7 +592,7 @@ fn required_enables_follow_version_dependencies_formats_and_flags() { fn device_new_refuses_unexposed_features() { let mut d = profile("runtime-floor"); d.features.insert(VkFeature::Maintenance8); - let e = match Device::from_queries(d.clone(), DevicePolicy::RESIDENT_TABLES) { + let e = match Device::from_queries(d.clone()) { Err(Error::InvalidDescriptor(DescriptorError::DeviceDescription { detail })) => detail, other => panic!("{other:?}"), }; @@ -606,7 +601,7 @@ fn device_new_refuses_unexposed_features() { "{e}" ); d.extensions.insert(VkExtension::KhrMaintenance8); - Device::from_queries(d, DevicePolicy::RESIDENT_TABLES).unwrap(); + Device::from_queries(d).unwrap(); } /// The profile's format tables hold only formats the description exposes: a queried description @@ -647,7 +642,7 @@ fn profile_format_tables_hold_only_exposed_formats() { let entry = d.formats.formats[&vk::Format::R8_UNORM]; d.formats.formats.insert(vk::Format::A8_UNORM, entry); let a8 = |d: &DeviceDescription| { - Device::from_queries(d.clone(), DevicePolicy::RESIDENT_TABLES) + Device::from_queries(d.clone()) .unwrap() .profile() .supports_format(vk::Format::A8_UNORM, FormatUsage::SampledImage) @@ -676,13 +671,12 @@ fn a_storage_read_without_a_format_is_enabled_by_the_feature_the_version_or_the_ reads.spirv_capabilities.insert(SpirvCapability::of( crate::spv::Capability::StorageImageReadWithoutFormat, )); - let policy = DevicePolicy::RESIDENT_TABLES; let open = |desc: &DeviceDescription| { let enabled = desc.recommended_enables(); let opened = desc.clone().with_enabled(&enabled).unwrap(); ( enabled, - Device::from_queries(opened.clone(), policy).unwrap(), + Device::from_queries(opened.clone()).unwrap(), opened, ) }; diff --git a/crates/metal2vulkan/src/device/tests/from_queries.rs b/crates/metal2vulkan/src/device/tests/from_queries.rs index 51b76c599..d17c803fb 100644 --- a/crates/metal2vulkan/src/device/tests/from_queries.rs +++ b/crates/metal2vulkan/src/device/tests/from_queries.rs @@ -82,7 +82,7 @@ fn from_queries_derives_one_profile_whatever_the_identity() { other.device_type = Some(id.kind); other.device_name = id.name.to_owned(); other.driver_version = id.version; - Device::from_queries(other, DevicePolicy::RESIDENT_TABLES) + Device::from_queries(other) .ok() .map(|d| d.profile().clone()) }) @@ -165,26 +165,22 @@ entry: "#; /// The push window is the device's `maxPushConstantsSize` up to 256 bytes -/// (`DeviceProfile::push_window`), and at least 128, Vulkan's least: the Vulkan 1.2 minimum -/// (`validation/profiles/below-floor/vk12-floor`, this test's input alone) derives at its 128, -/// with a window of 128, and the same description at 64, which no Vulkan device reports, is -/// refused: `Unsupported{PushWindow}`, needing `MaxPushConstantsSize` 128. Every committed -/// profile derives, its window its limit up to 256: `runtime-floor` at Vulkan 1.3's least, 128, -/// and every profile of a device at 256 (`moltenvk-m3`'s 4,096 included). +/// (`DeviceProfile::push_window`), and at least 128, Vulkan's least: `runtime-floor`, at Vulkan +/// 1.3's least, 128, derives with a window of 128, and the same description at 64, which no Vulkan +/// device reports, is refused: `Unsupported{PushWindow}`, needing `MaxPushConstantsSize` 128. +/// Every committed profile derives, its window its limit up to 256: every profile of a device at +/// 256 (`moltenvk-m3`'s 4,096 included). #[test] fn the_push_window_is_the_device_s_limit_up_to_256_bytes() { - let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) - .join("../metal2vulkan-validation/profiles/below-floor/vk12-floor.json"); - let text = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("{}: {e}", path.display())); - let least = DeviceDescription::from_khronos_json(&text, None).expect("parses"); + let least = profile("runtime-floor"); assert_eq!(least.limits.max_push_constants_size, 128); let mut below = least.clone(); below.limits.max_push_constants_size = 64; - match Device::from_queries(least, DevicePolicy::RESIDENT_TABLES) { + match Device::from_queries(least) { Ok(device) => assert_eq!(device.profile().push_window(), 128), - Err(e) => panic!("vk12-floor: {e}"), + Err(e) => panic!("runtime-floor: {e}"), } - match Device::from_queries(below, DevicePolicy::RESIDENT_TABLES) { + match Device::from_queries(below) { Err(Error::Unsupported(u)) => { assert_eq!(u.feature, Feature::PushWindow); let limit = Capability::Limit { @@ -199,7 +195,7 @@ fn the_push_window_is_the_device_s_limit_up_to_256_bytes() { for (stem, _) in committed_profiles() { let description = profile(&stem); let limit = description.limits.max_push_constants_size; - let device = Device::from_queries(description, DevicePolicy::RESIDENT_TABLES) + let device = Device::from_queries(description) .unwrap_or_else(|e| panic!("{stem} is committed but refused: {e}")); let window = device.profile().push_window(); assert_eq!(window, limit.min(256), "{stem}"); @@ -228,7 +224,7 @@ fn from_queries_records_the_device_denormals_of_a_float_product() { }; let mut compiled = 0; for (stem, _) in committed_profiles() { - let Ok(device) = Device::from_queries(profile(&stem), DevicePolicy::RESIDENT_TABLES) else { + let Ok(device) = Device::from_queries(profile(&stem)) else { continue; }; let a = compile(&bc, "mixed_products", device.profile()) @@ -288,7 +284,7 @@ fn from_queries_clears_a_narrow_value_by_an_and_on_ga10x() { .count(); (ands, extracts) }; - let queried = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap(); + let queried = Device::from_queries(desc).unwrap(); let (ands, extracts) = counts(queried.profile()); assert!(ands > 0, "from_queries: no AND"); assert_eq!(extracts, 0, "from_queries: an extract"); diff --git a/crates/metal2vulkan/src/device/tests/mechanism.rs b/crates/metal2vulkan/src/device/tests/mechanism.rs index 5d03b3957..4da2dc3d2 100644 --- a/crates/metal2vulkan/src/device/tests/mechanism.rs +++ b/crates/metal2vulkan/src/device/tests/mechanism.rs @@ -3,10 +3,7 @@ use super::profile::device; use crate::device::mechanism::mechanism; use crate::pipeline::facts::{Mechanism, RuntimeFact}; -use crate::pipeline::sym::{ - ImageAccess, ImageDim, ImageHandleClass, SampledType, SlotClass, SlotRef, Stage, - StorageFormatClass, -}; +use crate::pipeline::sym::{SlotClass, SlotRef, Stage}; /// One value of every `RuntimeFact` variant. fn every_fact() -> Vec { @@ -24,29 +21,12 @@ fn every_fact() -> Vec { RuntimeFact::IndirectGroupCount, RuntimeFact::ResourcePresence { slot }, RuntimeFact::SampleCount, - RuntimeFact::StorageTextureFormat { slot }, - RuntimeFact::SamplerCoordinates { slot }, - RuntimeFact::SamplerReduction { slot }, RuntimeFact::ImageViewShape { slot }, RuntimeFact::VertexFetch { attr: 1 }, RuntimeFact::VertexBufferStride { layout: 0 }, RuntimeFact::BaseVertexInstance, RuntimeFact::DeviceAddresses { slot }, - RuntimeFact::BufferRangeLimit { slot }, - RuntimeFact::TexelBufferRange { slot }, RuntimeFact::FramebufferFetch { color: 0 }, - RuntimeFact::ExecutionStatus, - RuntimeFact::HeapNumericType { - class: ImageHandleClass { - dim: ImageDim::D2, - arrayed: false, - multisampled: false, - sampled_type: SampledType::Float, - depth_compare: false, - access: ImageAccess::Sampled, - format: StorageFormatClass::NotStorage, - }, - }, RuntimeFact::SimdgroupEmulation { bytes_per_simdgroup: 128, arena: None, @@ -69,7 +49,6 @@ fn every_fact() -> Vec { }, RuntimeFact::StorageTextureNumericType { slot }, RuntimeFact::OutOfBoundsAlpha { slot }, - RuntimeFact::BicubicTexels { slot }, RuntimeFact::BorderTexels { slot }, RuntimeFact::StorageTextureLevels { slot }, RuntimeFact::StorageTextureLevelViews { slot }, @@ -90,22 +69,15 @@ fn every_fact() -> Vec { }, RuntimeFact::AccelerationStructureInstanceCount { slot }, RuntimeFact::PredicationVote, - RuntimeFact::SrgbTexture { slot }, RuntimeFact::ViewportCount, RuntimeFact::AliasedImageblock { data_size: 24 }, RuntimeFact::CallStackDepth { depth: 8 }, RuntimeFact::OpenClMode, RuntimeFact::OpenClLineTexture { slot }, RuntimeFact::RowLockstep, - RuntimeFact::TexelBufferParts { slot }, RuntimeFact::AddressAlignment { slot, align: 16 }, RuntimeFact::FlatGrid, RuntimeFact::CallThreadgroups, - RuntimeFact::SparseTextureWrites { - slot, - atomic: false, - }, - RuntimeFact::SparseTextureWrites { slot, atomic: true }, RuntimeFact::TileThreadgroupMemory { index: 1 }, RuntimeFact::TextureSwizzle { slot }, RuntimeFact::TileImageblock { @@ -132,58 +104,8 @@ fn every_fact() -> Vec { }, RuntimeFact::DroppedColor { color: 1 }, RuntimeFact::DepthClampRange, - RuntimeFact::ConstantLanes { slot }, RuntimeFact::FunctionTableRange { addressed: false }, RuntimeFact::TileThreadgroup { tile_sized: true }, - RuntimeFact::ConstexprSampled { - slot, - modes: [crate::metal::SamplerAddressMode::Repeat; 3], - }, - RuntimeFact::CubicSampler { slot }, - RuntimeFact::CubicArgumentSampler { - stage: Stage::Kernel, - }, - RuntimeFact::StorageTextureIntegerChannels { slot }, - RuntimeFact::HeapRawSamples { - stage: Stage::Fragment, - sampler: Some(1), - }, - RuntimeFact::CrossClassReads { slot }, - RuntimeFact::HeapCrossClassNeutral { - stage: Stage::Kernel, - class: crate::pipeline::sym::ImageHandleClass { - dim: crate::pipeline::sym::ImageDim::D2, - arrayed: false, - multisampled: false, - sampled_type: crate::pipeline::sym::SampledType::Float, - depth_compare: false, - access: crate::pipeline::sym::ImageAccess::Sampled, - format: crate::pipeline::sym::StorageFormatClass::NotStorage, - }, - every_member: true, - }, - RuntimeFact::HeapResidency { - stage: Stage::Fragment, - }, - RuntimeFact::HeapStorageReads { - stage: Stage::Kernel, - class: crate::pipeline::sym::ImageHandleClass { - dim: crate::pipeline::sym::ImageDim::D2, - arrayed: false, - multisampled: false, - sampled_type: crate::pipeline::sym::SampledType::Float, - depth_compare: false, - access: crate::pipeline::sym::ImageAccess::Storage, - format: crate::pipeline::sym::StorageFormatClass::Unknown, - }, - }, - RuntimeFact::AnisotropicSampler { - slot: SlotRef { - stage: Stage::Fragment, - class: SlotClass::Sampler, - index: 0, - }, - }, RuntimeFact::ObjectThreadgroupArena { static_bytes: 16, payload: Some(64), @@ -210,83 +132,61 @@ fn variant(f: &RuntimeFact) -> usize { RuntimeFact::IndirectGroupCount => 5, RuntimeFact::ResourcePresence { .. } => 6, RuntimeFact::SampleCount => 7, - RuntimeFact::StorageTextureFormat { .. } => 8, - RuntimeFact::SamplerCoordinates { .. } => 9, - RuntimeFact::SamplerReduction { .. } => 10, - RuntimeFact::ImageViewShape { .. } => 11, - RuntimeFact::VertexFetch { .. } => 12, - RuntimeFact::VertexBufferStride { .. } => 13, - RuntimeFact::BaseVertexInstance => 14, - RuntimeFact::DeviceAddresses { .. } => 15, - RuntimeFact::BufferRangeLimit { .. } => 16, - RuntimeFact::TexelBufferRange { .. } => 17, - RuntimeFact::FramebufferFetch { .. } => 18, - RuntimeFact::ExecutionStatus => 19, - RuntimeFact::HeapNumericType { .. } => 20, - RuntimeFact::SimdgroupEmulation { .. } => 21, - RuntimeFact::AmplificationCount => 22, - RuntimeFact::EmulatedSimdgroups => 23, - RuntimeFact::ImageblockSize { .. } => 24, - RuntimeFact::RenderTargetArrayLength { .. } => 25, - RuntimeFact::StageInRegion => 26, - RuntimeFact::StageInStride { .. } => 27, - RuntimeFact::RegionViewports => 28, - RuntimeFact::TileFunction => 29, - RuntimeFact::TileAttachmentFormat { .. } => 30, - RuntimeFact::StorageTextureNumericType { .. } => 31, - RuntimeFact::OutOfBoundsAlpha { .. } => 32, - RuntimeFact::BicubicTexels { .. } => 33, - RuntimeFact::StorageTextureLevels { .. } => 34, - RuntimeFact::StorageTextureLevelViews { .. } => 35, - RuntimeFact::SparseTexture { .. } => 36, - RuntimeFact::AccelerationStructureInstanceCount { .. } => 37, - RuntimeFact::PredicationVote => 38, - RuntimeFact::HeapStorageReads { .. } => 39, - RuntimeFact::SrgbTexture { .. } => 40, - RuntimeFact::ViewportCount => 41, - RuntimeFact::AliasedImageblock { .. } => 42, - RuntimeFact::CallStackDepth { .. } => 43, - RuntimeFact::FlatGrid => 44, - RuntimeFact::SparseTextureWrites { .. } => 45, - RuntimeFact::TileThreadgroupMemory { .. } => 46, - RuntimeFact::TextureSwizzle { .. } => 47, - RuntimeFact::TileImageblock { .. } => 48, - RuntimeFact::AmplificationDraws { .. } => 49, - RuntimeFact::FoldedGroups => 51, - RuntimeFact::ZeroedColor { .. } => 53, - RuntimeFact::DroppedColor { .. } => 54, - RuntimeFact::DepthClampRange => 55, - RuntimeFact::ConstantLanes { .. } => 56, - RuntimeFact::FunctionTableRange { .. } => 57, - RuntimeFact::TileThreadgroup { .. } => 59, - RuntimeFact::ConstexprSampled { .. } => 60, - RuntimeFact::CubicSampler { .. } => 61, - RuntimeFact::CubicArgumentSampler { .. } => 62, - RuntimeFact::HeapRawSamples { .. } => 66, - RuntimeFact::CrossClassReads { .. } => 69, - RuntimeFact::HeapCrossClassNeutral { .. } => 72, - RuntimeFact::AnisotropicSampler { .. } => 73, - RuntimeFact::StorageTextureIntegerChannels { .. } => 74, - RuntimeFact::ObjectThreadgroupArena { .. } => 77, - RuntimeFact::ReplayBindings => 80, - RuntimeFact::MergedDraws => 65, - RuntimeFact::QuadPrimitiveIds => 52, - RuntimeFact::RotatedWeights => 75, - RuntimeFact::PrivateList => 78, - RuntimeFact::PartialObjectThreadgroups => 81, - RuntimeFact::OpenClMode => 83, - RuntimeFact::RowLockstep => 84, - RuntimeFact::BorderTexels { .. } => 58, - RuntimeFact::HeapResidency { .. } => 76, - RuntimeFact::CallThreadgroups => 82, - RuntimeFact::PartialThreadgroups => 79, - RuntimeFact::TexelBufferParts { .. } => 63, - RuntimeFact::OpenClLineTexture { .. } => 67, - RuntimeFact::AddressAlignment { .. } => 64, - RuntimeFact::GridTiles => 50, - RuntimeFact::PrivateArena { .. } => 68, - RuntimeFact::StencilBitDraws => 70, - RuntimeFact::RobustStorageBuffers => 71, + RuntimeFact::ImageViewShape { .. } => 8, + RuntimeFact::VertexFetch { .. } => 9, + RuntimeFact::VertexBufferStride { .. } => 10, + RuntimeFact::BaseVertexInstance => 11, + RuntimeFact::DeviceAddresses { .. } => 12, + RuntimeFact::FramebufferFetch { .. } => 13, + RuntimeFact::SimdgroupEmulation { .. } => 14, + RuntimeFact::AmplificationCount => 15, + RuntimeFact::EmulatedSimdgroups => 16, + RuntimeFact::ImageblockSize { .. } => 17, + RuntimeFact::RenderTargetArrayLength { .. } => 18, + RuntimeFact::StageInRegion => 19, + RuntimeFact::StageInStride { .. } => 20, + RuntimeFact::RegionViewports => 21, + RuntimeFact::TileFunction => 22, + RuntimeFact::TileAttachmentFormat { .. } => 23, + RuntimeFact::StorageTextureNumericType { .. } => 24, + RuntimeFact::OutOfBoundsAlpha { .. } => 25, + RuntimeFact::StorageTextureLevels { .. } => 26, + RuntimeFact::StorageTextureLevelViews { .. } => 27, + RuntimeFact::SparseTexture { .. } => 28, + RuntimeFact::AccelerationStructureInstanceCount { .. } => 29, + RuntimeFact::PredicationVote => 30, + RuntimeFact::ViewportCount => 31, + RuntimeFact::AliasedImageblock { .. } => 32, + RuntimeFact::CallStackDepth { .. } => 33, + RuntimeFact::FlatGrid => 34, + RuntimeFact::TileThreadgroupMemory { .. } => 35, + RuntimeFact::TextureSwizzle { .. } => 36, + RuntimeFact::TileImageblock { .. } => 37, + RuntimeFact::AmplificationDraws { .. } => 38, + RuntimeFact::FoldedGroups => 40, + RuntimeFact::ZeroedColor { .. } => 42, + RuntimeFact::DroppedColor { .. } => 43, + RuntimeFact::DepthClampRange => 44, + RuntimeFact::FunctionTableRange { .. } => 45, + RuntimeFact::TileThreadgroup { .. } => 47, + RuntimeFact::ObjectThreadgroupArena { .. } => 55, + RuntimeFact::ReplayBindings => 58, + RuntimeFact::MergedDraws => 49, + RuntimeFact::QuadPrimitiveIds => 41, + RuntimeFact::RotatedWeights => 54, + RuntimeFact::PrivateList => 56, + RuntimeFact::PartialObjectThreadgroups => 59, + RuntimeFact::OpenClMode => 61, + RuntimeFact::RowLockstep => 62, + RuntimeFact::BorderTexels { .. } => 46, + RuntimeFact::CallThreadgroups => 60, + RuntimeFact::PartialThreadgroups => 57, + RuntimeFact::OpenClLineTexture { .. } => 50, + RuntimeFact::AddressAlignment { .. } => 48, + RuntimeFact::GridTiles => 39, + RuntimeFact::PrivateArena { .. } => 51, + RuntimeFact::StencilBitDraws => 52, + RuntimeFact::RobustStorageBuffers => 53, } } @@ -294,7 +194,7 @@ fn variant(f: &RuntimeFact) -> usize { fn mechanism_is_total_over_every_fact_and_profile() { let facts = every_fact(); let covered: std::collections::BTreeSet = facts.iter().map(variant).collect(); - assert_eq!(covered, (0..85).collect(), "every_fact misses a variant"); + assert_eq!(covered, (0..63).collect(), "every_fact misses a variant"); for (stem, _) in super::committed_profiles() { let dev = device(&stem); let p = dev.profile(); @@ -308,26 +208,20 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::ThreadgroupMemoryLength { .. } | RuntimeFact::ResourcePresence { .. } | RuntimeFact::SampleCount - | RuntimeFact::SamplerCoordinates { .. } | RuntimeFact::AmplificationCount | RuntimeFact::ImageblockSize { .. } | RuntimeFact::TileFunction | RuntimeFact::OutOfBoundsAlpha { .. } - | RuntimeFact::BicubicTexels { .. } | RuntimeFact::BorderTexels { .. } | RuntimeFact::SparseTexture { sparse_arm: true, .. } | RuntimeFact::SparseTexture { tile_map: true, .. } - | RuntimeFact::SparseTextureWrites { atomic: false, .. } | RuntimeFact::TileThreadgroupMemory { .. } - | RuntimeFact::TextureSwizzle { .. } - | RuntimeFact::ConstantLanes { .. } => Mechanism::Specialization, + | RuntimeFact::TextureSwizzle { .. } => Mechanism::Specialization, RuntimeFact::LocalSizeConstraint { .. } | RuntimeFact::LocalSizeLimits - | RuntimeFact::SamplerReduction { .. } | RuntimeFact::DeviceAddresses { .. } - | RuntimeFact::TexelBufferRange { .. } | RuntimeFact::SimdgroupEmulation { .. } | RuntimeFact::PredicationVote | RuntimeFact::SparseTexture { @@ -335,12 +229,6 @@ fn mechanism_is_total_over_every_fact_and_profile() { tile_map: false, .. } - | RuntimeFact::SparseTextureWrites { atomic: true, .. } - | RuntimeFact::CubicArgumentSampler { .. } - | RuntimeFact::HeapRawSamples { .. } - | RuntimeFact::HeapCrossClassNeutral { .. } - | RuntimeFact::HeapResidency { .. } - | RuntimeFact::HeapStorageReads { .. } | RuntimeFact::ObjectThreadgroupArena { .. } | RuntimeFact::AddressAlignment { .. } | RuntimeFact::RowLockstep => Mechanism::PlanTimeCheck, @@ -349,12 +237,9 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::PartialObjectThreadgroups | RuntimeFact::GridTiles => Mechanism::RegionSelected, RuntimeFact::IndirectGroupCount => Mechanism::None, - RuntimeFact::StorageTextureFormat { .. } - | RuntimeFact::StorageTextureNumericType { .. } + RuntimeFact::StorageTextureNumericType { .. } | RuntimeFact::EmulatedSimdgroups | RuntimeFact::RenderTargetArrayLength { .. } - | RuntimeFact::SrgbTexture { .. } - | RuntimeFact::CrossClassReads { .. } | RuntimeFact::FlatGrid | RuntimeFact::CallThreadgroups | RuntimeFact::PartialThreadgroups @@ -365,15 +250,11 @@ fn mechanism_is_total_over_every_fact_and_profile() { | RuntimeFact::QuadPrimitiveIds | RuntimeFact::PrivateList | RuntimeFact::RegionViewports - | RuntimeFact::TexelBufferParts { .. } | RuntimeFact::OpenClLineTexture { .. } | RuntimeFact::ZeroedColor { .. } | RuntimeFact::DroppedColor { .. } | RuntimeFact::DepthClampRange - | RuntimeFact::RotatedWeights - | RuntimeFact::ConstexprSampled { .. } - | RuntimeFact::CubicSampler { .. } - | RuntimeFact::AnisotropicSampler { .. } => Mechanism::Variant, + | RuntimeFact::RotatedWeights => Mechanism::Variant, RuntimeFact::ImageViewShape { .. } | RuntimeFact::StorageTextureLevelViews { .. } => Mechanism::BinderView, RuntimeFact::VertexFetch { .. } | RuntimeFact::TileAttachmentFormat { .. } => { @@ -393,24 +274,16 @@ fn mechanism_is_total_over_every_fact_and_profile() { Mechanism::PushConstant } } - RuntimeFact::BufferRangeLimit { .. } | RuntimeFact::FunctionTableRange { .. } => { - match f.buffer_access { - crate::device::profile::BufferAccess::Addressed => Mechanism::Variant, - _ => Mechanism::PlanTimeCheck, - } - } + RuntimeFact::FunctionTableRange { .. } => match f.buffer_access { + crate::device::profile::BufferAccess::Addressed => Mechanism::Variant, + _ => Mechanism::PlanTimeCheck, + }, RuntimeFact::FramebufferFetch { .. } | RuntimeFact::TileImageblock { .. } => { Mechanism::RenderPassContract } - RuntimeFact::ExecutionStatus => match f.buffer_access { - crate::device::profile::BufferAccess::Addressed => Mechanism::PushConstant, - _ => Mechanism::SyntheticBinding, - }, - RuntimeFact::HeapNumericType { .. } => Mechanism::BinderView, RuntimeFact::StageInRegion | RuntimeFact::StageInStride { .. } | RuntimeFact::StorageTextureLevels { .. } - | RuntimeFact::StorageTextureIntegerChannels { .. } | RuntimeFact::AccelerationStructureInstanceCount { .. } | RuntimeFact::ViewportCount | RuntimeFact::PrivateArena { .. } @@ -423,49 +296,3 @@ fn mechanism_is_total_over_every_fact_and_profile() { } } } - -#[test] -fn profile_dependent_rows_differ_where_the_design_says() { - let range = RuntimeFact::BufferRangeLimit { - slot: SlotRef { - stage: Stage::Kernel, - class: SlotClass::Buffer, - index: 0, - }, - }; - // Below the runtime's floor: `runtime-floor` as a Vulkan 1.2 context reads it, without device - // addresses, 64-bit integers or shader draw parameters. - use crate::device::requirements::VkFeature; - let mut below = crate::pipeline::testing::description_at_1_2("runtime-floor", false).unwrap(); - for f in [ - VkFeature::BufferDeviceAddress, - VkFeature::ShaderInt64, - VkFeature::ShaderDrawParameters, - ] { - below.features.remove(&f); - } - let floor = - crate::device::Device::from_queries(below, crate::device::DevicePolicy::RESIDENT_TABLES) - .unwrap(); - let addressed = device("nvidia-rtx50-linux"); - assert_eq!(mechanism(&range, floor.profile()), Mechanism::PlanTimeCheck); - assert_eq!(mechanism(&range, addressed.profile()), Mechanism::Variant); - let stride = RuntimeFact::VertexBufferStride { layout: 0 }; - assert_eq!( - mechanism(&stride, floor.profile()), - Mechanism::PipelineStateOrPushConstant - ); - assert_eq!( - mechanism(&stride, addressed.profile()), - Mechanism::DynamicStateOrPushConstant - ); - // The device reads GPU-written group counts where Metal wrote them. - assert_eq!( - mechanism(&RuntimeFact::IndirectGroupCount, floor.profile()), - Mechanism::None - ); - assert_eq!( - mechanism(&RuntimeFact::BaseVertexInstance, floor.profile()), - Mechanism::PushConstant - ); -} diff --git a/crates/metal2vulkan/src/device/tests/profile.rs b/crates/metal2vulkan/src/device/tests/profile.rs index ae7bd774e..02245b396 100644 --- a/crates/metal2vulkan/src/device/tests/profile.rs +++ b/crates/metal2vulkan/src/device/tests/profile.rs @@ -1,25 +1,23 @@ //! `Device::from_queries`, profile derivation, the fingerprint, and `requirements ⊆ profile`. use super::*; -use crate::device::profile::{BufferAccess, HandleDomain, Independence, PointerDomain}; +use crate::device::profile::{BufferAccess, Independence}; use crate::device::requirements::{Requirements, StageCreateFlag, VkLimit, VkProperty}; use crate::error::{Capability, Feature, Needs}; pub(crate) fn device(stem: &str) -> Device { - Device::from_queries(profile(stem), DevicePolicy::RESIDENT_TABLES) - .expect("committed profile derives") + Device::from_queries(profile(stem)).expect("committed profile derives") } #[test] fn every_committed_profile_derives() { for (stem, text) in committed_profiles() { let desc = DeviceDescription::from_khronos_json(&text, None).unwrap(); - let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES) - .unwrap_or_else(|e| panic!("{stem}: {e}")); + let dev = Device::from_queries(desc.clone()).unwrap_or_else(|e| panic!("{stem}: {e}")); let f = dev.profile().fields(); assert_eq!(f.api_version, desc.api_version, "{stem}"); // Deterministic. - let again = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap(); + let again = Device::from_queries(desc).unwrap(); assert_eq!(dev.profile(), again.profile(), "{stem}"); assert_eq!(dev.profile().fingerprint(), again.profile().fingerprint()); // A profile satisfies the requirements of everything it enabled. @@ -56,7 +54,7 @@ fn occlusion_query_precise_follows_each_source() { stated, "{stem}" ); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap(); + let dev = Device::from_queries(desc).unwrap(); let enabled = &dev.profile().fields().enabled.features; assert_eq!( enabled.contains(&VkFeature::OcclusionQueryPrecise), @@ -89,7 +87,7 @@ fn depth_bias_control_follows_each_source() { let desc = DeviceDescription::from_khronos_json(&text, None).unwrap(); let has_extension = desc.extensions.contains(&VkExtension::ExtDepthBiasControl); assert_eq!(has_extension, stated.is_some(), "{stem}"); - let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap(); + let dev = Device::from_queries(desc.clone()).unwrap(); let enabled = &dev.profile().fields().enabled; for (member, feature) in features { let want = stated @@ -139,21 +137,9 @@ fn find_structure(v: &serde_json::Value, name: &str, out: &mut Option { assert_eq!(u.feature, Feature::VulkanVersion); assert_eq!( @@ -287,91 +254,40 @@ fn below_1_2_is_refused() { } } -/// The identity domains come as a pair (`InvalidDescriptor` for one alone) and need -/// `bufferDeviceAddress` and `shaderInt64` (`Unsupported{IdentityDomains}` naming both, on a -/// device without `shaderInt64`). What they lower is `tests::engine_identity`'s. +/// The identity domains need `bufferDeviceAddress` and `shaderInt64`: a device without either, +/// below the runtime's floor, which requires both, is refused at `Device::from_queries`: +/// `Unsupported{IdentityDomains}` naming both. What they lower is `tests::engine_identity`'s. #[test] -fn the_identity_domains_come_as_a_pair_on_a_device_with_addresses() { - let identity = DevicePolicy { - pointer_domain: PointerDomain::Identity, - handle_domain: HandleDomain::Identity, - ..DevicePolicy::RESIDENT_TABLES - }; - for half in [ - DevicePolicy { - pointer_domain: PointerDomain::Identity, - ..DevicePolicy::RESIDENT_TABLES - }, - DevicePolicy { - handle_domain: HandleDomain::Identity, - ..DevicePolicy::RESIDENT_TABLES - }, +fn the_identity_domains_need_addresses_and_64_bit_integers() { + let both = [VkFeature::BufferDeviceAddress, VkFeature::ShaderInt64]; + let both = both.map(Capability::Feature).to_vec(); + for without in [ + &[VkFeature::BufferDeviceAddress, VkFeature::ShaderInt64][..], + &[VkFeature::BufferDeviceAddress], + &[VkFeature::ShaderInt64], ] { - assert!( - matches!( - Device::from_queries(profile("lavapipe"), half), - Err(Error::InvalidDescriptor( - DescriptorError::DeviceDescription { .. } - )) - ), - "{half:?}" - ); - } - // `runtime-floor` without `shaderInt64`: device addresses, no 64-bit integers. - match Device::from_queries(floor_without(&[VkFeature::ShaderInt64]), identity) { - Err(Error::Unsupported(u)) => { - assert_eq!(u.feature, Feature::IdentityDomains); - let both = [VkFeature::BufferDeviceAddress, VkFeature::ShaderInt64]; - let both = both.map(Capability::Feature).to_vec(); - assert_eq!(u.needs, Needs::AnyOf(vec![both])); + match Device::from_queries(floor_without(without)) { + Err(Error::Unsupported(u)) => { + assert_eq!(u.feature, Feature::IdentityDomains, "{without:?}"); + assert_eq!(u.needs, Needs::AnyOf(vec![both.clone()]), "{without:?}"); + } + other => panic!("{without:?}: {:?}", other.map(|_| ())), } - other => panic!("{other:?}"), } } +/// The fingerprint covers the description's fields: a feature or a limit changes it. #[test] -fn fingerprint_covers_every_policy_field() { +fn fingerprint_covers_the_description() { let desc = profile("lavapipe"); - let base = DevicePolicy::RESIDENT_TABLES; - let fp = |p: DevicePolicy| { - Device::from_queries(desc.clone(), p) - .unwrap() - .profile() - .fingerprint() - }; - let reference = fp(base); - let mut variants = Vec::new(); - let identity = DevicePolicy { - pointer_domain: PointerDomain::Identity, - handle_domain: HandleDomain::Identity, - ..base - }; - variants.push(("domains", identity)); - let mut seen = vec![reference]; - for (name, p) in variants { - let h = fp(p); - assert!(!seen.contains(&h), "{name} did not change the fingerprint"); - seen.push(h); - } - // Description-derived fields are covered too. + let fp = |d: DeviceDescription| Device::from_queries(d).unwrap().profile().fingerprint(); + let reference = fp(desc.clone()); let mut fewer = desc.clone(); fewer.features.remove(&VkFeature::ShaderInt8); - assert_ne!( - Device::from_queries(fewer, base) - .unwrap() - .profile() - .fingerprint(), - reference - ); + assert_ne!(fp(fewer), reference); let mut limits = desc; limits.limits.max_texel_offset += 1; - assert_ne!( - Device::from_queries(limits, base) - .unwrap() - .profile() - .fingerprint(), - reference - ); + assert_ne!(fp(limits), reference); } /// The fingerprint streams the `Debug` rendering into the hash; it must equal the hash of the @@ -449,7 +365,7 @@ fn allocation_sizes_are_no_profile_field() { ] { let mut other = desc.clone(); other.allocation = AllocationLimits::new(memory, buffer); - let dev = Device::from_queries(other, DevicePolicy::RESIDENT_TABLES).unwrap(); + let dev = Device::from_queries(other).unwrap(); assert_eq!(dev.profile(), base.profile(), "{stem}"); assert_eq!( dev.profile().fingerprint(), @@ -555,11 +471,7 @@ fn check_reports_the_first_missing_capability() { ); // Stage flags need their enabling features, which the floor requires: the floor without // `computeFullSubgroups`, a device below it, names it. - let without = Device::from_queries( - floor_without(&[VkFeature::ComputeFullSubgroups]), - DevicePolicy::RESIDENT_TABLES, - ) - .unwrap(); + let without = Device::from_queries(floor_without(&[VkFeature::ComputeFullSubgroups])).unwrap(); assert_eq!( without.profile().check(&Requirements { stage_flags: [StageCreateFlag::RequireFullSubgroups].into(), @@ -592,7 +504,6 @@ fn device_is_send_sync_and_cheap_to_clone() { fn send_sync() {} send_sync::(); send_sync::(); - send_sync::(); } /// The storage-without-format usages: per format and per image or buffer from @@ -641,14 +552,14 @@ fn storage_without_format_follows_each_format() { U::StorageTexelBufferReadWithoutFormat, U::StorageTexelBufferWriteWithoutFormat, ]; - let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap(); + let dev = Device::from_queries(desc.clone()).unwrap(); assert_eq!(usages(&dev, vk::Format::R32_UINT), all); assert_eq!(usages(&dev, vk::Format::B8G8R8A8_UNORM), []); let mut write_only = desc.clone(); write_only .features .remove(&VkFeature::ShaderStorageImageReadWithoutFormat); - let dev = Device::from_queries(write_only, DevicePolicy::RESIDENT_TABLES).unwrap(); + let dev = Device::from_queries(write_only).unwrap(); assert_eq!( usages(&dev, vk::Format::R32_UINT), [ @@ -661,7 +572,7 @@ fn storage_without_format_follows_each_format() { // extension at 1.2 reports them as Vulkan 1.3 does. desc.khr_format_feature_flags2 = true; assert!(desc.has_format_feature_flags2()); - let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap(); + let dev = Device::from_queries(desc.clone()).unwrap(); assert_eq!( usages(&dev, vk::Format::R32_UINT), [ @@ -677,7 +588,7 @@ fn storage_without_format_follows_each_format() { F::STORAGE_READ_WITHOUT_FORMAT, ), ); - let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap(); + let dev = Device::from_queries(desc.clone()).unwrap(); assert_eq!( usages(&dev, vk::Format::B8G8R8A8_UNORM), [ @@ -688,7 +599,7 @@ fn storage_without_format_follows_each_format() { // The implication needs the feature. desc.features .remove(&VkFeature::ShaderStorageImageReadWithoutFormat); - let dev = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap(); + let dev = Device::from_queries(desc).unwrap(); assert_eq!( usages(&dev, vk::Format::R32_UINT), [U::StorageImageWriteWithoutFormat] @@ -744,7 +655,7 @@ fn from_queries_half_rounding_follows_the_queries_alone() { let mut controlled = Vec::new(); for (stem, text) in committed_profiles() { let desc = DeviceDescription::from_khronos_json(&text, None).unwrap(); - let device = Device::from_queries(desc, DevicePolicy::RESIDENT_TABLES).unwrap(); + let device = Device::from_queries(desc).unwrap(); let p = device.profile(); if half_controls(p) { assert_eq!(quantize_form(p), QuantizeForm::Controlled, "{stem}"); diff --git a/crates/metal2vulkan/src/device/tests/render_vocabulary.rs b/crates/metal2vulkan/src/device/tests/render_vocabulary.rs index 7a78e1526..bec7a8fb6 100644 --- a/crates/metal2vulkan/src/device/tests/render_vocabulary.rs +++ b/crates/metal2vulkan/src/device/tests/render_vocabulary.rs @@ -145,7 +145,7 @@ fn render_features_follow_each_source() { for (stem, text) in committed_profiles() { let json: Value = serde_json::from_str(&text).unwrap(); let desc = DeviceDescription::from_khronos_json(&text, None).unwrap(); - let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap(); + let dev = Device::from_queries(desc.clone()).unwrap(); let enabled = &dev.profile().fields().enabled; for (structure, member, feature, extension) in FEATURES { let exposed = extension.is_none_or(|e| desc.extensions.contains(&e)); @@ -215,7 +215,7 @@ fn render_properties_and_limits_follow_each_source() { for (stem, text) in committed_profiles() { let json: Value = serde_json::from_str(&text).unwrap(); let desc = DeviceDescription::from_khronos_json(&text, None).unwrap(); - let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap(); + let dev = Device::from_queries(desc.clone()).unwrap(); let properties = &dev.profile().fields().enabled.properties; let depth = stated_flags(&json, "supportedDepthResolveModes"); let stencil = stated_flags(&json, "supportedStencilResolveModes"); @@ -278,7 +278,7 @@ fn each_stated_color_attachment_sample_count_derives_its_property() { for (stem, text) in committed_profiles() { let json: Value = serde_json::from_str(&text).unwrap(); let desc = DeviceDescription::from_khronos_json(&text, None).unwrap(); - let dev = Device::from_queries(desc.clone(), DevicePolicy::RESIDENT_TABLES).unwrap(); + let dev = Device::from_queries(desc.clone()).unwrap(); let derived: BTreeSet<(vk::Format, u32)> = dev .profile() .fields() diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 7c075dc42..e662c23cc 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -796,8 +796,9 @@ pub enum Feature { /// push window a stage is lowered for: a compute stage's dispatch region and buffer addresses, /// a render pipeline's two stages together. PushWindow, - /// The identity pointer and handle domains (`PointerDomain::Identity`, - /// `HandleDomain::Identity`): on a device without `bufferDeviceAddress` and `shaderInt64` + /// The identity pointer and handle domains, where a pointer is the device address it holds and + /// a texture's or sampler's handle is its `gpuResourceID`: on a device without + /// `bufferDeviceAddress` and `shaderInt64` /// (needing them, with no cause), and, on any device, a compile of a function holding a form /// they do not lower yet ([`Needs::NotImplemented`], the form named by [`IdentityCause`]). IdentityDomains, @@ -970,11 +971,6 @@ pub enum Feature { /// ([`GenericPointer`]). Vulkan's logical addressing has no pointer that may point into either /// of two storage classes. GenericPointer(GenericPointer), - /// A sequentially consistent fence (`seq_cst` `atomic_thread_fence`, an LLVM `fence seq_cst`, - /// or a `seq_cst` barrier ordering device memory), whose total order with the command - /// buffer's other such fences the translation keeps through an atomic of the command buffer's - /// `ExecutionStatus` word: in a vertex or fragment stage without its stores and atomics. - SeqCstFence, /// The coverage after the depth and stencil tests (`[[sample_mask, post_depth_coverage]]`). /// Vulkan's one form reads `SampleMask` under `VK_EXT_post_depth_coverage`, which no runtime /// enables; no form is built. @@ -1106,8 +1102,9 @@ pub enum IdentityCause { /// minimum level or emulated filter the function specializes, a bicubic filter of a 1D /// texture, or an anisotropic sampler slot whose filter the function emulates. SamplerState, - /// A sequentially consistent fence, which orders through the command buffer's execution status - /// word the identity domains do not reach. + /// A sequentially consistent fence, which Vulkan has no order for: its memory model reads + /// `SequentiallyConsistent` as acquire-release, whose fence allows the store buffering Metal's + /// fence forbids. SeqCstFence, /// A storage texture access the device takes only with a declared format, whose bound format /// no input names under the identity domains. diff --git a/crates/metal2vulkan/src/library/compiled.rs b/crates/metal2vulkan/src/library/compiled.rs index ff4ce3cdf..2b06ec69e 100644 --- a/crates/metal2vulkan/src/library/compiled.rs +++ b/crates/metal2vulkan/src/library/compiled.rs @@ -280,17 +280,6 @@ impl CompiledFunction { pub fn writes_memory(&self) -> bool { self.0.interface.writes_memory } - - /// Whether the function reads the resident root table: it has a device-address slot or a - /// dynamic root, so the binder builds the table with an entry for each such slot. - pub fn reads_resident_roots(&self) -> bool { - self.0.interface.needs_pointer_translation - } - - /// Whether the function looks texture or sampler handles up in the handle table. - pub fn resolves_handles(&self) -> bool { - self.0.interface.needs_handle_translation - } } /// What one per-function compile retains, with its provenance: the profile it was compiled for and @@ -313,8 +302,6 @@ pub struct FunctionArtifact { /// What the finalize verifier counted of the module: what its linked stage states as /// `StageModule::stats`. pub stats: ModuleStats, - /// Constant data the function reads through `WriteSource::ConstantBlob`. - pub blob: Option>, pub requirements: Requirements, /// Specialization and variant bits the function can take. pub variant_bits: u32, @@ -336,9 +323,6 @@ pub struct FunctionArtifact { /// take it away, and a per-slot gap is one undetermined answer among the others /// (`SlotWritability::Unknown`). pub(crate) slot_writes: Vec, - /// The notes of `precision` that hold only under some specializations, with their - /// conditions: what its linked stage states as `StageModule::specialized_notes`. - pub specialized: Vec, } /// What a kernel's `ComputePipelineMetalInfo`, and an object or mesh function's checks against its diff --git a/crates/metal2vulkan/src/lower/access/absent.rs b/crates/metal2vulkan/src/lower/access/absent.rs index e9c1883b6..e07fb0f90 100644 --- a/crates/metal2vulkan/src/lower/access/absent.rs +++ b/crates/metal2vulkan/src/lower/access/absent.rs @@ -7,39 +7,22 @@ //! beside a removed texture table, dropped a kernel's whole body, so no one translation is Metal's. //! The read writes no status: it takes the zero of its result's type (a read's zeros and a //! query's size of 0, which the nil texture, set 1's element 0, answers too) and fetches nothing, -//! a write of a removed texture is dropped, and the stage takes no `ExecutionStatus` buffer, push -//! field or fact for it. +//! and a write of a removed texture is dropped. //! //! A load or atomic of threadgroup memory the constants removed is the same read //! ([`FunctionConstant::AbsentMemory`]), and so is a texture operation on a removed texture or //! sampler that lowering reaches through memory, an aggregate, a table, or a merge //! (`texture::AbsentArgument`). -//! -//! The module also holds how a stage writes the command buffer's `ExecutionStatus` words, for a -//! sequentially consistent fence (`sync::barrier`) and an argument buffer's cubic sampler's mark -//! (`sampler::emit`): the stage states [`RuntimeFact::ExecutionStatus`] and reaches the buffer by -//! its device address ([`PushField::ExecutionStatusAddress`]) where the device addresses buffers -//! (`bufferDeviceAddress` and `shaderInt64`), and through a storage-buffer binding of its own -//! (`SyntheticBinding::ExecutionStatus`, [`StatusBinding`]) where it does not, one more storage -//! descriptor of the stage. use crate::air::intrinsics::{AirIntrinsic, FunctionConstant}; use crate::air::ir::{Callee, Inst, InstId, InstKind, Type, Value, ValueId}; -use crate::bind::status::{StatusBits, StatusWord}; -use crate::device::profile::BufferAccess; -use crate::device::requirements::VkFeature; use crate::error::Error; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; -use crate::memory::leaf::k32; -use crate::memory::roots::k64; -use crate::memory::views::{self, View}; -use crate::pipeline::facts::RuntimeFact; -use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, Stage, SyntheticBinding}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; +use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; use crate::spirv::ids::DemoteTy; -use crate::spirv::ir::{AtomicOp, BinOp, Constant, Scope, Semantics, Type as SType}; +use crate::spirv::ir::Constant; /// An absent read ([`FunctionConstant::AbsentRead`]): zero. #[derive(Clone, Debug, PartialEq, Eq)] @@ -83,105 +66,6 @@ pub fn select(cx: &mut SelectCx<'_>, at: InstId, inst: &Inst) -> Result) -> Option { - let enabled = &cx.profile.fields().enabled.features; - super::dynamic::stage_stores(cx.stage) - .find(|f| !enabled.contains(f)) - .map(StatusShort::Stores) -} - -/// Why a stage of a device that does not address buffers binds the command buffer's -/// `ExecutionStatus` buffer (`SyntheticBinding::ExecutionStatus`), one more storage descriptor of -/// the stage, which counts against its per-stage limits. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] -pub enum StatusBinding { - /// Only an argument buffer's sampler's cubic test marks the buffer - /// (`sampler::select::cubic_reach`): where the stage's descriptors pass a per-stage limit with - /// it, [`finish`] gives it back, and the stage marks nothing, as a fragment stage does (the - /// planner refuses a listed cubic sampler beside the stage). - CubicMark, - /// A sequentially consistent fence writes the buffer: a stage past a per-stage limit with it - /// is refused as `DescriptorCount`. - Required, -} - -/// State how the stage reaches the `ExecutionStatus` buffer, which [`status_short`] found it can -/// write, for `need`: its device address where the device addresses buffers, else its binding -/// ([`StatusBinding`]), counted once in the stage's descriptors. -pub fn state_status(cx: &mut SelectCx<'_>, need: StatusBinding) { - cx.facts.insert(RuntimeFact::ExecutionStatus); - if cx.profile.fields().buffer_access == BufferAccess::Addressed { - cx.push.insert(PushField::ExecutionStatusAddress); - return; - } - let access = &mut cx.families.access; - if access.status_binding.is_none() { - cx.descriptors.storage_buffers = cx.descriptors.storage_buffers.saturating_add(1); - } - access.status_binding = access.status_binding.max(Some(need)); -} - -/// Give back a binding of the `ExecutionStatus` buffer that only the cubic mark holds -/// ([`StatusBinding::CubicMark`]) where the stage's descriptors pass a per-stage limit with it: -/// the stage then marks nothing, and states no cubic reach, so the planner refuses a listed cubic -/// sampler beside it (`SamplerBicubicFilter`), as before the binding. Called once the slots' -/// forms are final, before the limits are checked (`lower::select`). -/// -/// The mark is one the stage may need, not one it does: only a cubic sampler that a command -/// later lists in the argument buffer needs it, and that sampler then meets the planner's typed -/// refusal, so giving the binding back hides nothing. Refusing the stage instead would refuse -/// every stage near its limit that samples through an argument buffer, cubic sampler or not. -pub fn finish(cx: &mut SelectCx<'_>) { - if cx.families.access.status_binding != Some(StatusBinding::CubicMark) { - return; - } - if cx - .descriptors - .exceeded(&cx.profile.fields().limits) - .is_none() - { - return; - } - cx.families.access.status_binding = None; - cx.descriptors.storage_buffers = cx.descriptors.storage_buffers.saturating_sub(1); - cx.families.sampler.cubic_reach = false; - cx.facts.remove(&RuntimeFact::ExecutionStatus); - cx.facts - .remove(&RuntimeFact::CubicArgumentSampler { stage: cx.stage }); -} - -/// The binding symbol of `stage`'s `ExecutionStatus` buffer. -pub fn symbol(stage: Stage) -> ResourceSlot { - ResourceSlot { - stage, - kind: ResourceKind::Synthetic(SyntheticBinding::ExecutionStatus), - index: 0, - } -} - -/// Declare the stage's `ExecutionStatus` view, a storage word view at its binding symbol, where -/// it binds the buffer ([`StatusBinding`]). -pub fn declare( - mb: &mut ModuleBuilder, - stage: Stage, - plan: &super::AccessPlan, -) -> BResult> { - match plan.status_binding { - Some(_) => Ok(Some(views::declare_at(mb, symbol(stage))?)), - None => Ok(None), - } -} - /// Emit absent read `s`, whose result is `vid`: define the result as zero. pub fn emit( cx: &mut EmitCx<'_>, @@ -200,54 +84,3 @@ pub fn emit( cx.define(vid, zero); Ok(()) } - -/// Whether the stage can write the command buffer's `ExecutionStatus` word for the cubic mark (the -/// stage's stores and atomics), stating how it reaches the buffer where it can -/// ([`StatusBinding::CubicMark`]). -pub fn status_writable(cx: &mut SelectCx<'_>) -> bool { - let writable = status_short(cx).is_none(); - if writable { - state_status(cx, StatusBinding::CubicMark); - } - writable -} - -/// Set `bits` in the command buffer's `ExecutionStatus` word, where the open block runs (a -/// relaxed device-scope `OR`); the stage stated how it reaches the buffer ([`status_writable`]). -pub fn mark_bits( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - bits: StatusBits, -) -> BResult<()> { - let word = status_word(cx, fb, StatusWord::Status)?; - let bit = k32(fb, bits.0)?; - fb.atomic(AtomicOp::Or, word, Scope::Device, Semantics::RELAXED, bit)?; - Ok(()) -} - -/// The place of the command buffer's `ExecutionStatus` word `w` (a `u32`): through the stage's -/// binding of the buffer where it has one ([`declare`]), else by the buffer's device address; the -/// stage stated which ([`state_status`]). -pub fn status_word( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - w: StatusWord, -) -> BResult { - if let Some(view) = cx.decl.families.access.status { - let word = k32(fb, w.byte_offset() / 4)?; - return views::word_ptr(fb, view, word); - } - let status = cx.push_field(fb, PushField::ExecutionStatusAddress)?; - let address = match w.byte_offset() { - 0 => status, - at => { - let off = k64(fb, u64::from(at))?; - fb.binary(BinOp::IAdd, status, off)? - } - }; - let u32_ty = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - fb.device_place(address, u32_ty) -} diff --git a/crates/metal2vulkan/src/lower/access/blob.rs b/crates/metal2vulkan/src/lower/access/blob.rs index 996b17e00..571fdba32 100644 --- a/crates/metal2vulkan/src/lower/access/blob.rs +++ b/crates/metal2vulkan/src/lower/access/blob.rs @@ -20,18 +20,17 @@ use crate::air::ir::{CastOp, Const, Inst, InstId, InstKind, Value, ValueId}; use crate::error::{AccessCause, Error}; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; -use crate::memory::blob::{BlobDecl, BlobHome, BlobUse}; +use crate::memory::blob::{BlobUse, ModuleWords}; use crate::memory::contain; -use crate::memory::leaf::{self, k32, Leaf, WordMem, WordOps}; +use crate::memory::leaf::{self, k32, Leaf, WordMem}; use crate::memory::plan::{ConstGlobalForm, MemoryPlan}; use crate::memory::provenance::{Repr, RootSetId}; -use crate::memory::views; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; use crate::spirv::ids::{DemoteTy, Value as SValue}; use crate::spirv::ir::BinOp; -use super::emit::{index_u32, ViewMem}; +use super::emit::index_u32; use super::local::LocalPtr; use super::root_sets::SetFacts; use super::{is_ptr_ty, operand, refuse, GepTerms}; @@ -143,9 +142,8 @@ pub fn lowered_pointer(cx: &SelectCx<'_>, v: Value) -> Result, Ok(Some(DemoteTy::ArenaOffset)) } -/// Record that the function reads the blob, its bytes shared with the memory plan's: under the -/// identity domains the module's words, with no descriptor; otherwise bound, the artifact carrying -/// its bytes and its storage descriptor counting in the per-stage limits. +/// Record that the function reads the blob, its bytes shared with the memory plan's: the module's +/// words, with no descriptor. pub fn use_blob(cx: &mut SelectCx<'_>) -> Result<(), Error> { if cx.families.access.blob.is_some() { return Ok(()); @@ -154,14 +152,7 @@ pub fn use_blob(cx: &mut SelectCx<'_>) -> Result<(), Error> { Some(b) => Arc::clone(&b.bytes), None => return Err(cx.invariant("a blob pointer without a blob")), }; - let home = match super::identity(cx.profile) { - true => BlobHome::Module, - false => BlobHome::Bound, - }; - cx.families.access.blob = Some(BlobUse { bytes, home }); - if home == BlobHome::Bound { - cx.descriptors.storage_buffers = cx.descriptors.storage_buffers.saturating_add(1); - } + cx.families.access.blob = Some(BlobUse { bytes }); Ok(()) } @@ -306,26 +297,16 @@ pub fn load_at( load_decl(fb, decl, leaf, off) } -/// Load `leaf` at byte offset `off` of the declared blob `decl`, contained: a bound blob's view -/// and the module's words alike. +/// Load `leaf` at byte offset `off` of the declared blob `words`, contained. pub fn load_decl( fb: &mut FunctionBuilder<'_>, - decl: BlobDecl, + mut words: ModuleWords, leaf: &Leaf, off: SValue, ) -> BResult { // The blob is read-only: its words are the same on every load, which stay plain. - match decl { - BlobDecl::Bound(view) => { - let mut mem = ViewMem(view, WordOps::default(), views::UnitViews::NONE); - let size = views::storage_bytes(fb, view)?; - contained(fb, &mut mem, leaf, off, size) - } - BlobDecl::Module(mut words) => { - let size = k32(fb, words.words.saturating_mul(4))?; - contained(fb, &mut words, leaf, off, size) - } - } + let size = k32(fb, words.words.saturating_mul(4))?; + contained(fb, &mut words, leaf, off, size) } /// Load `leaf` at byte offset `off` of `mem`, whose bytes number `size`: the leaf, or zero where diff --git a/crates/metal2vulkan/src/lower/access/copy.rs b/crates/metal2vulkan/src/lower/access/copy.rs index cfceaa654..97f0b9ab6 100644 --- a/crates/metal2vulkan/src/lower/access/copy.rs +++ b/crates/metal2vulkan/src/lower/access/copy.rs @@ -773,17 +773,6 @@ pub fn base<'a>( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, e: &'a Endpoint, -) -> BResult> { - base_live(cx, fb, e, None) -} - -/// [`base`] of an intrinsic that accesses memory only when `live` holds (a dynamic length's -/// nonzero one): a wide endpoint through root 0 counts a miss only then. -fn base_live<'a>( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - e: &'a Endpoint, - live: Option, ) -> BResult> { Ok(match e { Endpoint::Buffer(a) => { @@ -805,7 +794,7 @@ fn base_live<'a>( let p = cx.operand(fb, a.ptr)?; Base::Wide { p, - b: dynamic::wide_base(cx, fb, p, a, live)?, + b: dynamic::wide_base(cx, fb, p, a)?, } } }) @@ -1246,7 +1235,7 @@ fn position( (Overlap::Addressed, Base::Buffer { a, fat, .. }) => { dynamic::static_guest_address(cx, fb, &a.targets, fat) } - (Overlap::Addressed, Base::Wide { p, .. }) => dynamic::guest_address(cx, fb, p), + (Overlap::Addressed, Base::Wide { p, .. }) => Ok(p), _ => Err(cx.fail("a directed memmove between endpoints it cannot compare")), } } @@ -1262,37 +1251,9 @@ pub fn emit<'c>( return Ok(()); } let (n, tail) = span(cx, fb, op)?; - // A dynamic length may be 0: a wide endpoint then accesses nothing (and counts no miss). - let wide = matches!(op.dst, Endpoint::Wide(_)) - || matches!( - &op.src, - Source::Copy { - from: Endpoint::Wide(_), - .. - } - ); - let nonzero = |fb: &mut FunctionBuilder<'_>, v: SValue, wide: bool| -> BResult { - let zero = konst(fb, wide, 0)?; - fb.binary(BinOp::INotEqual, v, zero) - }; - let live = match (wide, n, tail) { - (true, Count::Value(n), Count::Const(0)) => Some(nonzero(fb, n, false)?), - (true, Count::Value(n), Count::Value(t)) => { - let bytes = fb.binary(BinOp::IAdd, n, t)?; - Some(nonzero(fb, bytes, false)?) - } - // A `u64` unit count: live when it or the tail is nonzero. - (true, Count::Wide(n), Count::Const(0)) => Some(nonzero(fb, n, true)?), - (true, Count::Wide(n), Count::Value(t)) => { - let units = nonzero(fb, n, true)?; - let bytes = nonzero(fb, t, false)?; - Some(fb.binary(BinOp::LogicalOr, units, bytes)?) - } - _ => None, - }; - let dst = base_live(cx, fb, &op.dst, live)?; + let dst = base(cx, fb, &op.dst)?; let (from, overlap) = match &op.src { - Source::Copy { from, overlap } => (Feed::Base(base_live(cx, fb, from, live)?), *overlap), + Source::Copy { from, overlap } => (Feed::Base(base(cx, fb, from)?), *overlap), Source::Fill { value: Some(v), .. } => (Feed::Fill(cx.operand(fb, *v)?), Overlap::Disjoint), Source::Fill { value: None, konst } => { (Feed::Fill(k32(fb, u32::from(*konst))?), Overlap::Disjoint) diff --git a/crates/metal2vulkan/src/lower/access/dynamic.rs b/crates/metal2vulkan/src/lower/access/dynamic.rs index 311b970d9..ddb8da87d 100644 --- a/crates/metal2vulkan/src/lower/access/dynamic.rs +++ b/crates/metal2vulkan/src/lower/access/dynamic.rs @@ -37,13 +37,9 @@ //! **Accesses** through a wide pointer compute from the fields it carries (no switch: every //! candidate, static or resident, is one code path): the leaf's words at `host + (at & ~3)`, and //! the sink's address, read once in the function's first block. Every such access is bounded -//! (robustness does not cover device addresses): the normative check `size ≥ n ∧ at ≤ size − n` in `u64`, the access at `select(inb, -//! address, sink)`, and a load's value `select(inb, v, 0)`; an out-of-bounds store lands in the -//! write-only sink. An access through root 0 (a null pointer or a resident-set miss) is -//! counted: word 4 of the `ExecutionStatus` buffer -//! (`StatusWord::ResidentMisses`) is incremented and `StatusBits::RESIDENT_MISS` set, both relaxed -//! `Device` atomics, the buffer reached by `PushField::ExecutionStatusAddress` (a function with -//! device-address slots carries the status by address). Every static slot a wide access may reach +//! (robustness does not cover device addresses): the normative check `size ≥ n ∧ at ≤ size − n` in +//! `u64`, the access at `select(inb, address, sink)`, and a load's value `select(inb, v, 0)`; an +//! out-of-bounds store lands in the write-only sink. Every static slot a wide access may reach //! becomes `BufferForm::Psb` (`access::finish_slots`), so the binder writes its root entry. //! //! **Under the identity domains** there is no root table: a pointer is the device address of the @@ -51,18 +47,19 @@ //! A wide pointer there is its address `a` alone, a `u64` (`DemoteTy::Address`): the `at` of a //! miss's fields `(0, a, 0, 0)`, whose Metal address is `at` and whose accesses are at `host + at`, //! with no field but `at` held, extracted or rebuilt (a GEP is the address's own arithmetic). A -//! wide buffer parameter is its slot's address (`SlotGuestBase`, the bias added back). No access through a wide pointer is contained -//! or counted: a stored address is used as it is, unchecked, and no resident set exists to miss. -//! No root table is read and no `RootTableAddress` pushed. An escaping slot root stays static -//! there (`memory::plan`), so a converted or stored slot pointer is `access::pointer`'s. +//! wide buffer parameter is its slot's address (`SlotGuestBase`, the bias added back). No access +//! through a wide pointer is contained or counted: a stored address is used as it is, unchecked, +//! and no resident set exists to miss. No root table is read and no `RootTableAddress` pushed. An +//! escaping slot root stays static there (`memory::plan`), so a converted or stored slot pointer is +//! `access::pointer`'s. //! //! **Compares.** `icmp` of wide pointers, or of a wide pointer and the null constant, compares //! their Metal addresses: `guest + at` of each pointer's root entry, the null root's fields being //! 0 (so a miss `(0, i, 0, 0)` is address `i`, and null is 0). A compare of a wide //! pointer with a static one is `access::pointer`'s. //! -//! **Null constants** (`null`, `undef`, `poison`) are the null root: `(0, 0, 0, 0)` as a `select` side -//! or a phi's incoming value. +//! **Null constants** (`null`, `undef`, `poison`) are the null root: `(0, 0, 0, 0)` as a `select` +//! side or a phi's incoming value. //! //! **Coherent accesses** (`air.{load,store}.{device,system}_coherent`) through a wide pointer are //! the wide leaf access with `NonPrivatePointer` and `MakePointerVisible` (a load) or @@ -96,7 +93,6 @@ use crate::air::ir::{ AddrSpace, Align, Call, Callee, CastOp, Inst, InstId, InstKind, IntPredicate, Type, Value, ValueId, }; -use crate::bind::status::{StatusBits, StatusWord}; use crate::budget::Meter; use crate::device::profile::BufferAccess; use crate::device::requirements::VkFeature; @@ -107,20 +103,18 @@ use crate::lower::select::SelectCx; use crate::memory::contain; use crate::memory::leaf::{self, k32, Coherence, Leaf, Path, Units, WordOps}; use crate::memory::provenance::{Repr, RootSetId}; -use crate::memory::roots::{self, k64}; -use crate::pipeline::facts::RuntimeFact; +use crate::memory::roots::k64; use crate::pipeline::sym::{PushField, SlotClass, SlotRef, Stage}; -use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; use crate::spirv::ids::{DemoteTy, TypeId, Value as SValue}; -use crate::spirv::ir::{AtomicOp, BinOp, ConvOp, Scope, Semantics, Type as SType}; +use crate::spirv::ir::{BinOp, ConvOp, Type as SType}; use super::local::{self, Home, LocalAccess}; use super::psb::PsbMem; use super::{ - is_ptr_ty, not_lowered, operand, refuse, slot_root, static_roots, Access, AccessPlan, - BufferReach, IndexForm, SideReach, Target, WideGepTerms, + is_ptr_ty, not_lowered, operand, refuse, static_roots, Access, AccessPlan, BufferReach, + IndexForm, SideReach, Target, WideGepTerms, }; /// The access family's dynamic-root plan. @@ -131,13 +125,6 @@ pub struct DynamicPlan { pub slots: BTreeSet, /// Buffer parameters whose value is a wide pointer. pub params: BTreeSet, - /// The function reads the root table for a wide pointer (a search or a wide access). - pub used: bool, - /// The resident-set searches of the function (a loaded pointer or `inttoptr` each): the - /// module defines the search once when there are several ([`roots::define_resolve`]). - pub resolves: u32, - /// Accesses through root 0 are counted in the `ExecutionStatus` buffer. - pub misses: bool, } /// A leaf access through a wide pointer. @@ -245,13 +232,6 @@ pub enum Side { Null, } -/// SPIR-V words of the module's resident-set search ([`roots::define_resolve`], once per module): -/// the table's and the set's conversions, the hit test, and a function's frame (216); its two loops, -/// each with its two variables' stores and loads and the loop's and its exit's blocks (96 each); -/// three steps (the halving, the entry's access chain and load, a compare, and a select, about 40 -/// words each: one in the 64-bit narrowing, two in the 32-bit loop); and the window between them, -/// its two conversions and the root's second addition (48). -pub const SEARCH_WORDS: u32 = 3 * 44 + 216 + 2 * 96 + 48; /// SPIR-V words of one use of the search: the root table's address and the call. const CALL_WORDS: u32 = 24; /// SPIR-V words of one wide access before its leaf: the pointer's fields, the check, the sink @@ -376,33 +356,12 @@ fn wide_operand(cx: &SelectCx<'_>, v: Value) -> Result { operand(cx, v) } -/// The function reads the root table for a wide pointer; under the identity domains, which have -/// none, nothing is read. -fn use_table(cx: &mut SelectCx<'_>) { - if super::identity(cx.profile) { - return; - } - cx.families.access.dynamic.used = true; - cx.push.insert(PushField::RootTableAddress); -} - -/// Plan one resident-set search of a guest address (a loaded pointer, an `inttoptr` operand, an -/// encoder's record address): the function reads the root table and searches it once more. Under -/// the identity domains the address is the pointer, with no search. -fn plan_resolve(cx: &mut SelectCx<'_>) { - if super::identity(cx.profile) { - return; - } - use_table(cx); - cx.families.access.dynamic.resolves += 1; -} - /// Plan a read of wide pointer `v`'s root entry: its static slots go through the root table, so /// the binder writes their entries. The slots are its root set's (`root_sets::SetFacts`), each /// with a window; a root that is neither null, dynamic, nor an accessed buffer slot (the constant /// blob, an arena, a slot the function never accesses and therefore has no root entry for) is /// refused. A set's slots join the plan's once, at its first such read. Under the identity domains -/// the pointer carries its address, and no entry is read ([`use_table`]). +/// the pointer carries its address, and no entry is read. pub(super) fn plan_entry(cx: &mut SelectCx<'_>, v: Value) -> Result { require_addresses(cx)?; let roots = wide(cx, v).ok_or_else(|| refuse(AccessCause::PointerForm))?; @@ -421,41 +380,18 @@ pub(super) fn plan_entry(cx: &mut SelectCx<'_>, v: Value) -> Result, v: Value) -> Result { plan_entry(cx, v)?; - plan_misses(cx)?; operand(cx, v) } -/// Plan the counting of an access through root 0, which needs the stage's store -/// feature for the counter's atomics. The identity domains have no resident set to miss: every -/// wide pointer there is root 0, and nothing is counted. -fn plan_misses(cx: &mut SelectCx<'_>) -> Result<(), Error> { - if !super::identity(cx.profile) { - let enabled = &cx.profile.fields().enabled.features; - if let Some(f) = stage_stores(cx.stage).find(|f| !enabled.contains(f)) { - return Err(Unsupported::needs( - Feature::DereferenceLoadedPointer, - Capability::Feature(f), - ) - .into()); - } - cx.families.access.dynamic.misses = true; - cx.push.insert(PushField::ExecutionStatusAddress); - cx.facts.insert(RuntimeFact::ExecutionStatus); - } - Ok(()) -} - -/// The feature the `ExecutionStatus` counter's atomics, and any other store of the product's -/// (a vertex function's capture records), need in `stage` besides what any module needs: stage -/// stores and atomics outside compute. +/// The feature the product's own stores (a vertex function's capture records) need in `stage` +/// besides what any module needs: stage stores and atomics outside compute. pub(crate) fn stage_stores(stage: Stage) -> impl Iterator { match stage { Stage::Vertex => Some(VkFeature::VertexPipelineStoresAndAtomics), @@ -477,20 +413,7 @@ pub fn lowered_pointer(cx: &SelectCx<'_>, v: Value) -> Result, if super::phis::incoming(cx, v)?.is_some_and(|i| i.not_wide) { return Err(refuse(AccessCause::PointerJoin)); } - Ok(Some(match super::identity(cx.profile) { - true => DemoteTy::Address, - false => DemoteTy::FatPtr { wide: true }, - })) -} - -/// The SPIR-V type of a wide pointer off the identity domains: `u64vec4(root, at, host, size)`. -/// Under them a wide pointer is its device address, a `u64` ([`DemoteTy::Address`]). -pub fn wide_type(mb: &mut crate::spirv::builder::ModuleBuilder) -> BResult { - let u = mb.ty(SType::Int { - width: 64, - signed: false, - })?; - mb.ty(SType::Vector { elem: u, len: 4 }) + Ok(Some(DemoteTy::Address)) } /// Whether buffer parameter `b`'s value is a wide pointer. @@ -498,14 +421,12 @@ pub fn is_wide_param(cx: &SelectCx<'_>, b: &ParamBinding) -> bool { wide(cx, Value::Arg(crate::air::ir::ArgIdx::new(b.param))).is_some() } -/// Plan a buffer parameter whose value is a wide pointer: under the identity domains its slot's -/// address is read from its `SlotGuestBase`. +/// Plan a buffer parameter whose value is a wide pointer: its slot's address is read from its +/// `SlotGuestBase`. pub fn select_param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> { require_addresses(cx)?; - if super::identity(cx.profile) { - let slot = param_slot(cx.entry, b).ok_or_else(|| refuse(AccessCause::Parameter))?; - cx.push.insert(PushField::SlotGuestBase(slot)); - } + let slot = param_slot(cx.entry, b).ok_or_else(|| refuse(AccessCause::Parameter))?; + cx.push.insert(PushField::SlotGuestBase(slot)); cx.families.access.dynamic.params.insert(b.param); Ok(()) } @@ -541,51 +462,7 @@ pub fn param_value( let Some(slot) = param_slot(cx.entry, b) else { return Err(cx.fail(format!("parameter {} is no buffer slot", b.param))); }; - if cx.plan.families.access.identity { - return super::pointer::slot_address(cx, fb, slot).map(Some); - } - let root = k64(fb, u64::from(slot_root(slot.index)))?; - let table = cx.push_field(fb, PushField::RootTableAddress)?; - let at = roots::entry_field(fb, table, root, roots::BIND_OFFSET)?; - let host = roots::entry_field(fb, table, root, roots::HOST)?; - let size = roots::entry_field(fb, table, root, roots::SIZE)?; - Ok(Some(fat(fb, [root, at, host, size])?)) -} - -/// The work before the body (the entry hook): at entry, in a block that dominates every block of -/// the body (the function's first, or the merge of a merged vertex's search, which -/// `stage_io::emit_draw_entry` emits before it, as the slot table it reads is its command's), read -/// the sink's address and each wide buffer parameter's root entry once, so no access reads the -/// root table again. The table is read-only to the dispatch: the binder writes -/// it before submission and no lowering stores to it. -pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<()> { - let dynamic = &cx.plan.families.access.dynamic; - if !dynamic.used { - return Ok(()); - } - let params: Vec = dynamic.params.iter().copied().collect(); - if cx.plan.families.access.psb_contained { - cx.sink_host(fb)?; - } - for p in params { - let Some(v) = cx - .plan - .values - .id(crate::air::ir::Value::Arg(crate::air::ir::ArgIdx::new(p))) - else { - continue; - }; - let x = cx.operand(fb, v)?; - cx.hold(v, x); - } - Ok(()) -} - -/// The sink's address (`host` of the sink's root entry), read in the open block. -pub(crate) fn read_sink_host(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult { - let table = cx.push_field(fb, PushField::RootTableAddress)?; - let sink = k64(fb, roots::SINK_ROOT)?; - roots::entry_field(fb, table, sink, roots::HOST) + super::pointer::slot_address(cx, fb, slot).map(Some) } /// The 8-byte leaf of a stored pointer (its guest address, a `u64`). @@ -740,7 +617,6 @@ pub fn select( ) { return Err(refuse(AccessCause::PointerInteger)); } - plan_resolve(cx); DynStrategy::FromInt { of: operand(cx, *v)?, } @@ -754,7 +630,6 @@ pub fn select( } if result_wide => { require_addresses(cx)?; let leaf = pointer_leaf(cx, inst.ty, *align)?; - plan_resolve(cx); let source = match cx.memory.repr(*ptr) { Some(Repr::BufPtr { wide: false, .. }) => { Source::Static(static_access(cx, *ptr, leaf, false, m)?) @@ -1066,34 +941,17 @@ fn index_u64(fb: &mut FunctionBuilder<'_>, x: SValue, form: IndexForm) -> BResul } } -/// The wide pointer `[root, at, host, size]`. -fn fat(fb: &mut FunctionBuilder<'_>, parts: [SValue; 4]) -> BResult { - let ty = wide_type(fb.module())?; - fb.composite_construct(ty, &parts) +/// The wide pointer of fields `parts` (`[root, at, host, size]`): a pointer has no root entry +/// (every field but `at` is 0), so it is the address `at` alone. +fn wide_of(parts: [SValue; 4]) -> SValue { + parts[1] } -/// The wide pointer of fields `parts` (`[root, at, host, size]`): under the identity domains, whose -/// pointers have no root entry (every field but `at` is 0), the address `at` alone. -fn wide_of(cx: &EmitCx<'_>, fb: &mut FunctionBuilder<'_>, parts: [SValue; 4]) -> BResult { - match cx.plan.families.access.identity { - true => Ok(parts[1]), - false => fat(fb, parts), - } -} - -/// The fields of wide pointer value `p`: `[root, at, host, size]`; under the identity domains -/// `[0, p, 0, 0]`, the constant zeros folding where they are used ([`add64`]). -fn fields(cx: &EmitCx<'_>, fb: &mut FunctionBuilder<'_>, p: SValue) -> BResult<[SValue; 4]> { - if cx.plan.families.access.identity { - let zero = k64(fb, 0)?; - return Ok([zero, p, zero, zero]); - } - Ok([ - fb.composite_extract(p, &[0])?, - fb.composite_extract(p, &[1])?, - fb.composite_extract(p, &[2])?, - fb.composite_extract(p, &[3])?, - ]) +/// The fields of wide pointer value `p`, the address it holds: `[0, p, 0, 0]`, the constant zeros +/// folding where they are used ([`add64`]). +fn fields(fb: &mut FunctionBuilder<'_>, p: SValue) -> BResult<[SValue; 4]> { + let zero = k64(fb, 0)?; + Ok([zero, p, zero, zero]) } /// `a + b` in `u64`: the other operand where one is the constant 0 (the `host` of an identity @@ -1108,49 +966,6 @@ fn add64(fb: &mut FunctionBuilder<'_>, a: SValue, b: SValue) -> BResult fb.binary(BinOp::IAdd, a, b) } -/// Count an access through root 0 when `live` holds (always without it): `ResidentMisses += 1`, -/// `RESIDENT_MISS` set. -fn count_miss( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - root: SValue, - live: Option, -) -> BResult<()> { - let status = cx.push_field(fb, PushField::ExecutionStatusAddress)?; - let null = k64(fb, roots::NULL_ROOT)?; - let miss = fb.binary(BinOp::IEqual, root, null)?; - let miss = match live { - Some(l) => fb.binary(BinOp::LogicalAnd, miss, l)?, - None => miss, - }; - let then: ArmFn<'_, ()> = Box::new(move |fb, _| { - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - let word = |fb: &mut FunctionBuilder<'_>, w: StatusWord| -> BResult { - let off = k64(fb, u64::from(w.byte_offset()))?; - let a = fb.binary(BinOp::IAdd, status, off)?; - fb.device_place(a, u32_) - }; - let count = word(fb, StatusWord::ResidentMisses)?; - let one = k32(fb, 1)?; - fb.atomic( - AtomicOp::IAdd, - count, - Scope::Device, - Semantics::RELAXED, - one, - )?; - let bits = word(fb, StatusWord::Status)?; - let bit = k32(fb, StatusBits::RESIDENT_MISS.0)?; - fb.atomic(AtomicOp::Or, bits, Scope::Device, Semantics::RELAXED, bit)?; - Ok(ArmEnd::FallThrough(Vec::new())) - }); - fb.if_(&mut (), miss, then, None)?; - Ok(()) -} - /// The access `a` through its wide pointer: the loaded value, or the stored value's store. pub(super) fn wide_access( cx: &mut EmitCx<'_>, @@ -1159,7 +974,7 @@ pub(super) fn wide_access( stored: Option, ) -> BResult> { let p = cx.operand(fb, a.ptr)?; - let b = wide_base(cx, fb, p, a, None)?; + let b = wide_base(cx, fb, p, a)?; wide_at(fb, b, None, &a.leaf, stored) } @@ -1179,17 +994,15 @@ pub struct WideBase { units: Units, } -/// Resolve wide pointer value `p` (a `u64vec4`, or an identity `u64`) for the accesses of `a`: with its coherence (a -/// `*_coherent` access's, or the function's own) and volatility. Under isolation an access -/// through root 0 is counted here, once, when `live` holds (always without it). +/// Resolve wide pointer value `p` (a `u64vec4`, or an identity `u64`) for the accesses of `a`: with +/// its coherence (a `*_coherent` access's, or the function's own) and volatility. pub(super) fn wide_base( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, p: SValue, a: &WideAccess, - live: Option, ) -> BResult { - base_with(cx, fb, p, (a.coherence, a.volatile), live) + base_with(cx, fb, p, (a.coherence, a.volatile)) } /// [`wide_base`] with the coherence (`None`: the function's own) and volatility `ops`. @@ -1198,21 +1011,12 @@ fn base_with( fb: &mut FunctionBuilder<'_>, p: SValue, ops: (Option, bool), - live: Option, ) -> BResult { - let [root, at, host, size] = fields(cx, fb, p)?; - if cx.plan.families.access.dynamic.misses { - count_miss(cx, fb, root, live)?; - } - let bounds = if cx.plan.families.access.psb_contained { - Some((size, cx.sink_host(fb)?)) - } else { - None - }; + let [_, at, host, _] = fields(fb, p)?; Ok(WideBase { host, at, - bounds, + bounds: None, units: cx.plan.families.access.psb_units, ops: WordOps { coherence: ops @@ -1291,10 +1095,7 @@ pub(super) fn atomic_address( n: u32, ) -> BResult { let p = cx.operand(fb, ptr)?; - let [root, at, host, size] = fields(cx, fb, p)?; - if cx.plan.families.access.dynamic.misses { - count_miss(cx, fb, root, None)?; - } + let [_, at, host, _] = fields(fb, p)?; let word = u64::from(n.max(4)); let mask = k64(fb, !(word - 1))?; let aligned = fb.binary(BinOp::BitwiseAnd, at, mask)?; @@ -1310,20 +1111,10 @@ pub(super) fn atomic_address( } else { None }; - if !cx.plan.families.access.psb_contained { - return Ok(AtomicAddress { - addr, - byte, - inb: None, - }); - } - let inb = contain::in_bounds(fb, at, size, u64::from(n))?; - let sink = cx.sink_host(fb)?; - let addr = fb.select(inb, addr, sink)?; Ok(AtomicAddress { addr, byte, - inb: Some(inb), + inb: None, }) } @@ -1364,36 +1155,19 @@ fn wide_side(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, side: Side) -> B Side::Ptr(p) => cx.operand(fb, p), Side::Null => { let zero = k64(fb, 0)?; - wide_of(cx, fb, [zero; 4]) + Ok(wide_of([zero; 4])) } } } -/// The Metal address of wide pointer `side` ([`guest_address`]; 0 for the null constant). +/// The Metal address of wide pointer `side`, the address it holds (0 for the null constant). fn metal_address(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, side: Side) -> BResult { let p = match side { Side::Null => return k64(fb, 0), Side::Ptr(p) => cx.operand(fb, p)?, }; - guest_address(cx, fb, p) -} - -/// The Metal (guest) address of wide pointer value `p` (a `u64vec4`): `guest + at` of its root -/// entry (the null root's fields are 0, so a miss `[0, i, 0, 0]` is `i`). Under the identity -/// domains, which have no root table, it is the pointer itself. -pub(super) fn guest_address( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - p: SValue, -) -> BResult { - if cx.plan.families.access.identity { - return Ok(p); - } - let root = fb.composite_extract(p, &[0])?; - let at = fb.composite_extract(p, &[1])?; - let table = cx.push_field(fb, PushField::RootTableAddress)?; - let guest = roots::entry_field(fb, table, root, roots::GUEST)?; - fb.binary(BinOp::IAdd, guest, at) + // A wide pointer is the address it holds. + Ok(p) } /// The Metal (guest) address of static-root fat pointer `fat` whose candidates are `targets`: for @@ -1455,40 +1229,6 @@ pub(super) fn plan_static_guest( Ok(()) } -/// The wide pointer of guest address `guest` (a `u64`): a call of the module's resident-set -/// search ([`roots::define_resolve`]), or the search in place when it is the module's only one. -/// Under the identity domains the address is the pointer, with no search. -fn resolve(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, guest: SValue) -> BResult { - if cx.plan.families.access.identity { - return Ok(guest); - } - let table = cx.push_field(fb, PushField::RootTableAddress)?; - match cx.decl.families.access.resolve { - Some(search) => fb - .call(search, &[table, guest])? - .ok_or_else(|| cx.fail("a resident-set search without a result")), - None => { - let r = roots::resolve_wide(fb, table, guest)?; - fat(fb, r) - } - } -} - -/// Whether the module defines the resident-set search as a function: a function with more than -/// one search calls it, one with a single search emits it in place (a function's frame and call -/// would only add words). -pub fn defines_search(plan: &DynamicPlan) -> bool { - plan.resolves > 1 -} - -/// The module's routines the dynamic strategies use, charged once to the census: the resident-set -/// search, `access.dynamic.resolve`, whether called or in place. -pub fn routine_words(plan: &DynamicPlan) -> impl Iterator { - (plan.resolves > 0) - .then_some(("access.dynamic.resolve", u64::from(SEARCH_WORDS))) - .into_iter() -} - /// Emit dynamic strategy `s`, defining value `vid`. pub fn emit( cx: &mut EmitCx<'_>, @@ -1499,7 +1239,7 @@ pub fn emit( let r = match s { DynStrategy::Gep { base, konst, terms } => { let p = cx.operand(fb, *base)?; - let [root, mut off, host, size] = fields(cx, fb, p)?; + let [root, mut off, host, size] = fields(fb, p)?; if *konst != 0 { let c = k64(fb, *konst)?; off = fb.binary(BinOp::IAdd, off, c)?; @@ -1513,7 +1253,7 @@ pub fn emit( } off = fb.binary(BinOp::IAdd, off, x)?; } - wide_of(cx, fb, [root, off, host, size])? + wide_of([root, off, host, size]) } DynStrategy::Copy { of } => cx.operand(fb, *of)?, DynStrategy::Select { c, t, f } => { @@ -1523,8 +1263,8 @@ pub fn emit( fb.select(c, t, f)? } DynStrategy::FromInt { of } => { - let x = cx.operand(fb, *of)?; - resolve(cx, fb, x)? + // The address is the pointer, with no search. + cx.operand(fb, *of)? } DynStrategy::LoadPointer(Source::Static(a)) => { let p = cx.operand(fb, a.ptr)?; @@ -1532,19 +1272,19 @@ pub fn emit( let Some(guest) = super::emit::access_at(cx, fb, a, p, m, None)? else { return Err(cx.fail("a pointer load without a value")); }; - resolve(cx, fb, guest)? + guest } DynStrategy::LoadPointer(Source::Wide(a)) => { let Some(guest) = wide_access(cx, fb, a, None)? else { return Err(cx.fail("a pointer load without a value")); }; - resolve(cx, fb, guest)? + guest } DynStrategy::LoadPointer(Source::Arena(a)) => { let Some(guest) = local::emit_access(cx, fb, a, None)? else { return Err(cx.fail("a pointer load without a value")); }; - resolve(cx, fb, guest)? + guest } DynStrategy::StorePointer { to, value } => { let guest = metal_address(cx, fb, *value)?; diff --git a/crates/metal2vulkan/src/lower/access/emit.rs b/crates/metal2vulkan/src/lower/access/emit.rs index b096690b0..502dd3477 100644 --- a/crates/metal2vulkan/src/lower/access/emit.rs +++ b/crates/metal2vulkan/src/lower/access/emit.rs @@ -374,27 +374,20 @@ fn prepare_access( }; let lowering = cx.plan.families.access.slots.get(t.slot).copied().flatten(); let ops = WordOps::of(crate::lower::sync::memory_model::coherence(cx.plan)); - if let Some(SlotLowering::Psb { start }) = lowering { - // Under the identity domains a slot whose address the binder holds to an alignment is - // reached from that address as it is (its biased word), a leaf at an offset proven a - // multiple of 8 or 16 accessed at that alignment up to the address's; any other from the - // word below each access. + if let Some(SlotLowering::Psb { .. }) = lowering { + // A slot whose address the binder holds to an alignment is reached from that address as + // it is (its biased word), a leaf at an offset proven a multiple of 8 or 16 accessed at + // that alignment up to the address's; any other from the word below each access. let aligned = cx.plan.families.access.aligned.get(&t.slot).copied(); - let a = if cx.plan.families.access.identity { - match aligned { - Some(held) => { - let base = super::pointer::direct_base(cx, fb, choice.slot)?; - psb::prepare_direct(base, m, held) - } - None => { - let address = super::pointer::slot_address(cx, fb, choice.slot)?; - psb::prepare_at(fb, address, m)? - } + let a = match aligned { + Some(held) => { + let base = super::pointer::direct_base(cx, fb, choice.slot)?; + psb::prepare_direct(base, m, held) + } + None => { + let address = super::pointer::slot_address(cx, fb, choice.slot)?; + psb::prepare_at(fb, address, m)? } - } else { - let table = cx.push_field(fb, PushField::RootTableAddress)?; - let contained = cx.plan.families.access.psb_contained; - psb::prepare(fb, table, t.root, m, start, n, contained)? }; let units = cx.plan.families.access.psb_units; let read_only = cx.plan.families.access.unwritten.contains(&t.slot); diff --git a/crates/metal2vulkan/src/lower/access/handle.rs b/crates/metal2vulkan/src/lower/access/handle.rs index 863f501c7..0487dd476 100644 --- a/crates/metal2vulkan/src/lower/access/handle.rs +++ b/crates/metal2vulkan/src/lower/access/handle.rs @@ -79,16 +79,15 @@ use std::collections::BTreeMap; use crate::air::ir::{AddrSpace, CastOp, Inst, InstId, InstKind, Type, Value, ValueId}; use crate::budget::{tree_bytes, Meter}; use crate::error::{AccessCause, Error, Feature, LowerFamily, Unsupported}; -use crate::lower::arith::{legal, Form, Held}; +use crate::lower::arith::{Form, Held}; use crate::lower::emit::EmitCx; -use crate::lower::select::{DescriptorCounts, Plan, SelectCx}; +use crate::lower::select::SelectCx; use crate::memory::handles::{self, Candidate, Domain, DomainKind, NULL_HANDLE}; use crate::memory::leaf::{k32, Leaf, Path}; use crate::memory::provenance::{HandleClass, OffsetRange, Repr}; -use crate::pipeline::sym::{ResourceKind, ResourceSlot, SyntheticBinding}; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::BResult; -use crate::spirv::ids::{DemoteTy, FuncId, Value as SValue}; +use crate::spirv::ids::{DemoteTy, Value as SValue}; use crate::spirv::ir::BinOp; use super::dynamic::WideAccess; @@ -156,24 +155,24 @@ fn id_type(mb: &mut ModuleBuilder) -> BResult { mb.ty(SType::Vector { elem: u, len: 2 }) } -/// The representation of an argument buffer's sampler handle under the identity domains: its -/// resource ID, a `uvec2` ([`emit_identity_sampler`]). +/// The representation of an argument buffer's sampler handle: its resource ID, a `uvec2` +/// ([`emit_identity_sampler`]). const IDENTITY_SAMPLER_ID: DemoteTy = DemoteTy::Vector { elem: crate::spirv::ids::ScalarTy::Int { bits: 32 }, len: 2, }; -/// Whether handle value `v` is an argument buffer's sampler under the identity domains, held as -/// its resource ID ([`IDENTITY_SAMPLER_ID`]). +/// Whether handle value `v` is an argument buffer's sampler, held as its resource ID +/// ([`IDENTITY_SAMPLER_ID`]). fn identity_sampler(cx: &SelectCx<'_>, v: Value) -> bool { - super::identity(cx.profile) && handles::heap_handle(cx.memory, v) == Some(HandleClass::Sampler) + handles::heap_handle(cx.memory, v) == Some(HandleClass::Sampler) } /// The representation of handle word `v` ([`is_word`]): an argument buffer's sampler's resource -/// ID under the identity domains ([`IDENTITY_SAMPLER_ID`]), every other word's handle index. +/// ID ([`IDENTITY_SAMPLER_ID`]), every other word's handle index. pub fn word_repr(cx: &SelectCx<'_>, v: Value) -> DemoteTy { match member_word(&cx.families.access, v) { - Some(HandleClass::Sampler) if super::identity(cx.profile) => IDENTITY_SAMPLER_ID, + Some(HandleClass::Sampler) => IDENTITY_SAMPLER_ID, _ => DemoteTy::HandleIndex, } } @@ -303,8 +302,7 @@ impl HandleStrategy { HandleStrategy::Select { .. } => 6, HandleStrategy::Load(Element::Handle(_)) => 4, HandleStrategy::Load(Element::Dynamic { .. }) => 40, - // The id's load, its two words, and the call; the search is the module's routine, - // counted once ([`routine_words`]). + // The id's load, its two words, and their handle's arithmetic. HandleStrategy::Lookup(a) | HandleStrategy::SamplerLookup(a) => { LOOKUP_CALL_WORDS.saturating_add(a.words()) } @@ -1097,8 +1095,10 @@ enum Table { } /// The resource-id load of a heap texture or sampler handle through buffer pointer `ptr` (the -/// argument buffer's member): two words, contained like any leaf access of the slot. The function -/// then reads the handle table or the sampler table (`table`), one more storage descriptor. +/// argument buffer's member, a texture's or a sampler's by `table`): two words, contained like any +/// leaf access of the slot. A texture's or a sampler's resource ID is its handle: its index is the +/// element of the set-1 arrays (`emit_identity_handle`, `emit_identity_sampler`), and no table is +/// searched. fn lookup( cx: &mut SelectCx<'_>, ptr: Value, @@ -1147,110 +1147,21 @@ fn lookup( )?) } }; - // Under the identity domains a texture's or a sampler's resource ID is its handle: its index - // is the element of the set-1 arrays (`emit_identity_handle`, `emit_identity_sampler`), and no - // table is searched. - if super::identity(cx.profile) { - return Ok(access); - } - let ids = if legal::holds_wide(cx.profile) { - HandleIds::Words - } else { - HandleIds::U64 - }; - let planned = match table { - Table::Handles => &mut cx.families.access.handle_table, - Table::Samplers => &mut cx.families.access.sampler_table, - }; - if planned.is_none() { - *planned = Some(ids); - cx.descriptors = cx.descriptors.plus(&DescriptorCounts { - storage_buffers: 1, - ..DescriptorCounts::default() - }); - } Ok(access) } -/// The words of a heap handle load besides its id's access: the id's two words and the search's -/// call (`OpCompositeExtract` of 5 words each, `OpFunctionCall` of 6). +/// The words of a heap handle load besides its id's access: the id's two words and their +/// handle's arithmetic (`OpCompositeExtract` of 5 words each, and the rest's). const LOOKUP_CALL_WORDS: u32 = 24; -/// The words of the handle-table and sampler-table searches a function's heap handle loads call, -/// with the census name of the strategy that calls each: counted once per module, not per load. -pub fn routine_words(plan: &AccessPlan) -> impl Iterator { - let form = plan.lookup(); - let handles = plan.handle_table.map(move |ids| { - let words = handles::lookup_routine_words(ids == HandleIds::U64, form); - ("access.handle.lookup", u64::from(words)) - }); - let samplers = plan.sampler_table.map(|ids| { - let words = handles::lookup_routine_words(ids == HandleIds::U64, handles::Lookup::Entry); - ("access.handle.sampler_lookup", u64::from(words)) - }); - handles.into_iter().chain(samplers) -} - -/// How the handle-table search reads an entry's resource id: as one `u64` on a profile with -/// `shaderInt64` (the table declared as an entry array), else as two words. +/// How a function-table directory search reads an entry's resource id: as one `u64` on a profile +/// with `shaderInt64`, else as two words. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum HandleIds { U64, Words, } -/// The stage's handle table and the module's search of it. -#[derive(Clone, Copy, Debug)] -pub struct HandleTable { - /// `fn(lo: u32, hi: u32) -> u32`, the heap handle of a resource id - /// ([`handles::define_lookup`]): its element, with the entry's flags the plan's search carries; - /// for the sampler table, the index of its entry. - pub lookup: FuncId, - /// The table, whose entries a sampler handle's uses read ([`handles::entry_field`]). - pub table: handles::Table, -} - -/// The binding symbol of the handle table of `stage`. -pub fn table_symbol(stage: crate::pipeline::sym::Stage) -> ResourceSlot { - ResourceSlot { - stage, - kind: ResourceKind::Synthetic(SyntheticBinding::HandleTable), - index: 0, - } -} - -/// The binding symbol of the sampler table of `stage`. -pub fn sampler_table_symbol(stage: crate::pipeline::sym::Stage) -> ResourceSlot { - ResourceSlot { - stage, - kind: ResourceKind::Synthetic(SyntheticBinding::SamplerTable), - index: 0, - } -} - -/// Declare the stage's handle table (an entry array, or a word view on a profile without -/// `shaderInt64`) and the module's search of it, when the plan reads it. -pub fn declare_table(mb: &mut ModuleBuilder, plan: &Plan) -> BResult> { - let Some(ids) = plan.families.access.handle_table else { - return Ok(None); - }; - let table = handles::declare_table(mb, table_symbol(plan.stage), ids == HandleIds::U64)?; - let lookup = handles::define_lookup(mb, table, plan.families.access.lookup())?; - Ok(Some(HandleTable { lookup, table })) -} - -/// Declare the stage's sampler table and the module's search of it in its entry form, when the -/// plan reads it. -pub fn declare_sampler_table(mb: &mut ModuleBuilder, plan: &Plan) -> BResult> { - let Some(ids) = plan.families.access.sampler_table else { - return Ok(None); - }; - let sym = sampler_table_symbol(plan.stage); - let table = handles::declare_table(mb, sym, ids == HandleIds::U64)?; - let lookup = handles::define_lookup(mb, table, handles::Lookup::Entry)?; - Ok(Some(HandleTable { lookup, table })) -} - /// Emit handle strategy `s`, defining value `vid`. pub fn emit( cx: &mut EmitCx<'_>, @@ -1305,7 +1216,6 @@ pub fn emit( fb.binary(BinOp::IAdd, base, delta)? } HandleStrategy::Lookup(a) | HandleStrategy::SamplerLookup(a) => { - let identity = cx.plan.families.access.identity; let id = match a.as_ref() { IdLoad::Static(a) => { let p = cx.operand(fb, a.ptr)?; @@ -1317,33 +1227,17 @@ pub fn emit( let Some(id) = id else { return Err(cx.fail("a resource-id load without a value")); }; - match s { - HandleStrategy::SamplerLookup(_) if identity => { - return emit_identity_sampler(cx, fb, vid, id); - } - _ if identity => return emit_identity_handle(cx, fb, vid, id), - _ => {} - } - let table = match s { - HandleStrategy::SamplerLookup(_) => cx.decl.families.access.sampler_table, - _ => cx.decl.families.access.handle_table, + return match s { + HandleStrategy::SamplerLookup(_) => emit_identity_sampler(cx, fb, vid, id), + _ => emit_identity_handle(cx, fb, vid, id), }; - let Some(table) = table else { - return Err(cx.fail("a handle lookup without its table")); - }; - let lo = fb.composite_extract(id, &[0])?; - let hi = fb.composite_extract(id, &[1])?; - match fb.call(table.lookup, &[lo, hi])? { - Some(element) => element, - None => return Err(cx.fail("a handle lookup without a result")), - } } }; cx.define(vid, r); Ok(()) } -/// Under the identity domains, the handle of a texture whose resource ID `id` (`uvec2`, low word +/// The handle of a texture whose resource ID `id` (`uvec2`, low word /// first) an argument buffer holds (`docs/RESOURCE-ID.md`), defining `vid`: the id's index masked /// below the set-1 image arrays' length (`pipeline::link::IDENTITY_TEXTURES`, a power of two), the /// element of those arrays (0, nil, the null descriptor), with the word's missing-alpha bit @@ -1402,7 +1296,7 @@ fn emit_identity_handle( Ok(()) } -/// Under the identity domains, the handle of a sampler whose resource ID `id` (`uvec2`, low word +/// The handle of a sampler whose resource ID `id` (`uvec2`, low word /// first) an argument buffer holds (`docs/RESOURCE-ID.md`), defining `vid`: the ID itself, its index /// replaced by 0 (the default sampler) where it is not below the set-1 sampler arrays' length /// (`pipeline::link::IDENTITY_SAMPLERS`), and its word as the program wrote it. The program writes diff --git a/crates/metal2vulkan/src/lower/access/icb.rs b/crates/metal2vulkan/src/lower/access/icb.rs index 19f9b3fcf..47d785ad0 100644 --- a/crates/metal2vulkan/src/lower/access/icb.rs +++ b/crates/metal2vulkan/src/lower/access/icb.rs @@ -237,12 +237,9 @@ fn needs(cx: &SelectCx<'_>) -> Result<(), Error> { Ok(()) } -/// Select the strategy of `inst` under the identity domains: an indirect-command operation's -/// writes, or its refusal; `None` for any other instruction, or on another profile. +/// Select the strategy of `inst`: an indirect-command operation's writes, or its refusal; `None` +/// for any other instruction. pub fn select(cx: &mut SelectCx<'_>, inst: &Inst, m: &mut Meter) -> Result, Error> { - if !super::identity(cx.profile) { - return Ok(None); - } let InstKind::Call(call) = &inst.kind else { return Ok(None); }; @@ -393,8 +390,8 @@ fn emit_address(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, a: &Address) match a { Address::Null => k64(fb, 0), Address::Wide(p) => { - let p = cx.operand(fb, *p)?; - dynamic::guest_address(cx, fb, p) + // A wide pointer is the address it holds. + cx.operand(fb, *p) } Address::Static { ptr, targets } => { let fat = cx.operand(fb, *ptr)?; diff --git a/crates/metal2vulkan/src/lower/access/mod.rs b/crates/metal2vulkan/src/lower/access/mod.rs index d5f11e718..145c99995 100644 --- a/crates/metal2vulkan/src/lower/access/mod.rs +++ b/crates/metal2vulkan/src/lower/access/mod.rs @@ -22,14 +22,13 @@ //! ([`quad`]): one 16-byte store where each invocation finds their address a multiple of 16 and the //! 16 bytes inside the slot, else the four. //! -//! **Slots** ([`finish_slots`]). An accessed slot is a storage view. A storage slot whose range is -//! not provably within `maxStorageBufferRange` declares `RuntimeFact::BufferRangeLimit`. On -//! Profile A a `BufferRangeLimit` variant (`LowerInputs.psb_slots`) and the per-stage -//! descriptor-limit fallback move storage slots to their device addresses (`BufferForm::Psb`, the PSB leaf of `psb`, reached through the root -//! table), which declare `RuntimeFact::DeviceAddresses`. The pulled vertex fetch's source buffers -//! are slots under the same rules ([`pulled`]): one sharing a read-only buffer argument's Metal -//! index is that argument's slot, widened to a `Whole` storage slot; any other is a read-only -//! `Whole` storage slot of its own. +//! **Slots** ([`finish_slots`]). A kernel's slot that its device binds +//! (`DeviceProfile::binds_kernel_buffers`) and that only its own typed accesses reach is a storage +//! view of set 0 at its pushed bind offset; every other slot is read at its device address +//! (`BufferForm::Psb`, the PSB leaf of `psb`), and declares `RuntimeFact::DeviceAddresses`. The +//! pulled vertex fetch's source buffers are slots under the same rules ([`pulled`]): one sharing a +//! read-only buffer argument's Metal index is that argument's slot, widened to a `Whole` storage +//! slot; any other is a read-only `Whole` storage slot of its own. //! //! **Census names**. A slot's form is decided after its accesses are selected, so a strategy's //! census name reads the finished plan ([`AccessPlan::check`], [`BufferReach`]): an access that @@ -122,12 +121,9 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::air::abi::{AbiInt, ParamBinding, ParamRole}; use crate::air::ir::{AddrSpace, CastOp, Const, Inst, InstId, InstKind, Type, Value, ValueId}; use crate::budget::Meter; -use crate::device::profile::{BufferAccess, Limits}; -use crate::device::requirements::VkLimit; +use crate::device::profile::BufferAccess; use crate::device::DeviceProfile; -use crate::error::{ - AccessCause, Capability, Error, Feature, ImageblockCause, LowerFamily, Unsupported, -}; +use crate::error::{AccessCause, Error, Feature, ImageblockCause, LowerFamily, Unsupported}; use crate::lower::emit::EmitCx; use crate::lower::select::{DescriptorCounts, FamilyPlans, Plan, SelectCx, SlotChoice}; use crate::lower::strategy::FamilyStrategy; @@ -472,12 +468,13 @@ impl AccessPlan { ) } - /// The containment check target `t` takes as emitted (`emit::prepare`): the in-shader check, - /// unless it is a device-address slot and containment is off (`psb_contained`). + /// The containment check target `t` takes as emitted (`emit::prepare`): none for a + /// device-address slot, whose accesses are checked against its pushed length where they may + /// reach another offset ([`AccessPlan::variable`]), else the in-shader check. pub fn check(&self, t: &Target) -> Check { - match (self.by_address(t), self.psb_contained) { - (true, false) => Check::None, - _ => Check::InShader, + match self.by_address(t) { + true => Check::None, + false => Check::InShader, } } @@ -656,15 +653,13 @@ pub fn lowered_pointer(cx: &SelectCx<'_>, v: Value) -> Result { if let Some(e) = phis::incoming(cx, v)?.and_then(|i| phis::fat_refusal(cx, i)) { return Err(e); } - Ok(DemoteTy::FatPtr { wide: false }) + Ok(DemoteTy::FatPtr) } -/// The SPIR-V type of a pointer representation `ty`: `uvec2` for a narrow fat pointer, `u32` -/// for an arena offset or a handle index, `u64vec4` for a wide fat pointer, `u64` for a device -/// address, `None` for the others. +/// The SPIR-V type of a pointer representation `ty`: `uvec2` for a fat pointer, `u32` for an arena +/// offset or a handle index, `u64` for a device address, `None` for the others. pub fn spirv_type(mb: &mut ModuleBuilder, ty: &DemoteTy) -> BResult> { match ty { - DemoteTy::FatPtr { wide: true } => Ok(Some(dynamic::wide_type(mb)?)), DemoteTy::Address => Ok(Some(mb.ty(SType::Int { width: 64, signed: false, @@ -673,7 +668,7 @@ pub fn spirv_type(mb: &mut ModuleBuilder, ty: &DemoteTy) -> BResult { + DemoteTy::FatPtr => { let u = mb.ty(SType::Int { width: 32, signed: false, @@ -700,16 +695,9 @@ pub enum SlotLowering { #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct AccessPlan { pub slots: Vec>, - /// Device-address accesses are bounds-checked (robust buffer access does not cover them): - /// every profile's but the identity domains', whose slots are checked against their pushed - /// lengths instead. - pub psb_contained: bool, /// The narrow units device-address accesses load and store directly (`psb::narrow_units` of /// the profile): a sub-word store there is one narrow store instead of two word atomics. pub psb_units: Units, - /// The function compiles under the identity domains: a device-address slot's address is its - /// own field ([`address_field`]). - pub identity: bool, /// Under the identity domains with containment on ([`identity_contained`]), the buffer slots /// an access may reach at a byte offset that is not a translation-time constant /// ([`note_variable`]): each reads its `PushField::SlotBounds`, and each of those accesses @@ -768,14 +756,6 @@ pub struct AccessPlan { pub typed_slots: BTreeSet, /// The pulled vertex fetch's source buffers, by Metal index ([`pulled`]). pub pulled: Vec, - /// Some texture handle is loaded from an argument buffer: the function reads the stage's - /// handle table ([`handle`]), one more storage descriptor, and its search reads the ids as - /// this. - pub handle_table: Option, - /// Some sampler handle is loaded from an argument buffer: the function reads the stage's - /// sampler table ([`handle`]), one more storage descriptor, and its search reads the ids as - /// this. - pub sampler_table: Option, /// Memory-plan slots whose Metal address (`SlotGuestBase`) a pointer compare reads /// ([`mod@pointer`]): a slot no access bounds gets the window `Whole`, so the binder plans it /// and writes the field. @@ -856,10 +836,6 @@ pub struct AccessPlan { /// The relaxed atomic loads an exit of a loop holding them depends on ([`atomic::spin`]): each /// acquires its memory. Planned before any instruction is selected. pub spins: BTreeSet, - /// The stage binds the command buffer's `ExecutionStatus` buffer - /// (`SyntheticBinding::ExecutionStatus`), one more storage descriptor, on a device that does - /// not address buffers, and why ([`absent::StatusBinding`]). - pub status_binding: Option, } impl AccessPlan { @@ -900,40 +876,21 @@ pub struct Declared { pub views: Vec>, /// The arenas. pub local: local::LocalDecl, - /// The stage's `ArgumentTable`, when the placement spilled fields there. - pub table: Option, /// The constant blob's words, when the function reads the blob. - pub blob: Option, - /// The storage view of each pulled source buffer with a descriptor slot of its own, by Metal - /// index ([`pulled`]). - pub pulled: Vec<(u32, View)>, - /// The stage's handle table and its search, when a texture handle is loaded from an - /// argument buffer. - pub handle_table: Option, - /// The stage's sampler table and its search, when a sampler handle is loaded from an - /// argument buffer. - pub sampler_table: Option, + pub blob: Option, /// The unit views of each accessed slot, by memory-plan slot index. pub units: Vec, - /// The module's resident-set search, when a function searches it more than once - /// ([`dynamic`]). - pub resolve: Option, /// A tile function's attachment images and render area ([`tile`]). pub tile: tile::TileDecl, /// The stage's function-table directory and search and its snapshot, when a table is read by /// its resource id. pub function_tables: Option, - /// The stage's view of the command buffer's `ExecutionStatus` buffer, where it binds the - /// buffer ([`absent::declare`]). - pub status: Option, } /// The module's routines the access family's strategies call, each charged once to the census: the -/// handle-table and function-table-directory searches and the resident-set search. +/// function-table-directory search. pub fn routine_words(plan: &AccessPlan) -> impl Iterator + '_ { - handle::routine_words(plan) - .chain(function_table::routine_words(plan.function_tables)) - .chain(dynamic::routine_words(&plan.dynamic)) + function_table::routine_words(plan.function_tables) } /// Plan a used resource parameter (buffer, argument buffer, threadgroup, indirect constant). @@ -1019,40 +976,20 @@ pub fn param_value( fb.module().const_value(c) } -/// Whether a storage slot's descriptor range is provably within `maxStorageBufferRange`: a -/// `Bounded` window's range is at most `round_up(len + align - 1, 16)`, with `align` the descriptor -/// base alignment `max(minStorageBufferOffsetAlignment, 16)`. -fn storage_range_fits(window: Window, limits: &Limits) -> bool { - match window { - Window::Bounded { len, .. } => { - let align = views::base_alignment(limits.min_storage_buffer_offset_alignment); - views::descriptor_range(len, align) - .is_some_and(|r| r <= u64::from(limits.max_storage_buffer_range)) - } - _ => false, - } -} - /// Choose the form of every accessed slot and of every pulled vertex source buffer, and add their /// descriptors to `cx.descriptors`. Returns the form of each accessed slot, by memory-plan slot /// index (`None` for slots the function does not access). /// -/// A slot is a storage view unless a `BufferRangeLimit` variant (`LowerInputs.psb_slots`) -/// moves it to its device address, or, on Profile A, the per-stage descriptor limits are exceeded: -/// then the highest-index storage slots move to device addresses, one at a time, until the -/// storage-buffer and resource counts fit (a deterministic per-function choice). Every -/// device-address slot declares `DeviceAddresses` and reads the root table -/// (`PushField::RootTableAddress`) instead of its bind residual. +/// A slot is its device address, read from its own `SlotGuestBase`, and declares +/// `DeviceAddresses`; a kernel's slot on a device that binds its buffer arguments +/// (`DeviceProfile::binds_kernel_buffers`) is its storage view, unless a wide pointer, a typed +/// atomic or the stage-in fetch reaches it or the dispatch binds it below its argument's +/// alignment. /// /// A pulled source buffer ([`pulled`]) shares the accessed slot of its Metal index, widened to a -/// `Whole` storage slot that the fetch reads too (a window outside the first 2³² bytes above the -/// bind offset is refused), or is a read-only `Whole` storage slot of its own; either takes part -/// in the rules above like any storage slot. -/// -/// Each step of the fallback moves one storage view, so the descriptors and push fields of the -/// slots' forms are kept in a census the step updates, and the order of the slots it moves is -/// sorted once: the fallback takes one pass over the slots, metered, where it recounted every slot -/// per slot moved before. The working tables are charged while they run. +/// `Whole` slot that the fetch reads too (a window outside the first 2³² bytes above the bind +/// offset is refused), or is a read-only `Whole` slot of its own, its device address. The working +/// tables are charged while they run. pub fn finish_slots( cx: &mut SelectCx<'_>, m: &mut Meter, @@ -1064,80 +1001,9 @@ pub fn finish_slots( result } -/// The ledger bytes `place_slots` works in per memory-plan slot: its form and window, and its -/// place in the fallback's order. -const SLOT_WORK_BYTES: usize = std::mem::size_of::>() - + std::mem::size_of::>() - + std::mem::size_of::<(u32, Moved)>(); - -/// The descriptors and push fields of the slots' forms while [`finish_slots`] moves them: the -/// storage views, and the push fields with each device-address slot's `SlotBindOffset` replaced by -/// the field its address is read from ([`slot_address_field`]). A move updates it in place. -struct Census { - storage: u32, - fields: BTreeSet, - /// Under the identity domains the spilled fields are a parameter block at a pushed address. - identity: bool, - /// A device-address slot reads its own address ([`slot_address_field`]). - own_addresses: bool, - /// The stage's push base and the device's window bytes, which decide where the fields spill. - push_window: (u32, u32), -} - -impl Census { - /// The census of `forms` over the function's push fields `push`; `dynamic` when a wide - /// pointer reads the root table. - fn new( - push: &BTreeSet, - (dynamic, identity, own_addresses, push_window): (bool, bool, bool, (u32, u32)), - forms: impl Iterator, - m: &mut Meter, - ) -> Result { - let mut c = Census { - storage: 0, - fields: push.clone(), - identity, - own_addresses, - push_window, - }; - if dynamic { - c.fields.insert(PushField::RootTableAddress); - } - for (slot, l) in forms { - m.tick(1)?; - match l { - SlotLowering::View => c.storage = c.storage.saturating_add(1), - SlotLowering::Psb { .. } => { - c.fields.remove(&PushField::SlotBindOffset(slot)); - c.fields.insert(slot_address_field(own_addresses, slot)); - } - } - } - Ok(c) - } - - /// The slots' descriptors in `stage`: their views, and the `ArgumentTable` when the push fields - /// spill. - fn counts(&self, stage: crate::pipeline::sym::Stage) -> DescriptorCounts { - DescriptorCounts { - // Under the identity domains the spilled fields are a parameter block at a pushed - // address, no descriptor. - uniform_buffers: u32::from( - !self.identity && table::spills(stage, self.push_window, &self.fields), - ), - storage_buffers: self.storage, - ..DescriptorCounts::default() - } - } - - /// A storage view of `slot` became its device address. - fn addressed(&mut self, slot: SlotRef) { - self.storage = self.storage.saturating_sub(1); - self.fields.remove(&PushField::SlotBindOffset(slot)); - self.fields - .insert(slot_address_field(self.own_addresses, slot)); - } -} +/// The ledger bytes `place_slots` works in per memory-plan slot: its form and window. +const SLOT_WORK_BYTES: usize = + std::mem::size_of::>() + std::mem::size_of::>(); /// The push field a device-address slot's address is read from: its own ([`address_field`]) where /// `own`, under the identity domains outside a device-replay variant, else the root table, where a @@ -1166,17 +1032,10 @@ fn address_field(slot: SlotRef) -> PushField { /// a 64-bit add of a constant. pub(crate) const SLOT_ADDRESS_BIAS: u64 = 1 << 31; -/// Whether profile `p` takes the identity domains, where a pointer is a device address used -/// directly. -pub(crate) fn identity(p: &DeviceProfile) -> bool { - p.fields().pointer_domain == crate::device::PointerDomain::Identity -} - -/// Whether a function selected in `cx` bounds its slots' device-address accesses under the -/// identity domains: the function is no device-replay variant, whose slots' addresses are its -/// replayed command's. +/// Whether a function selected in `cx` bounds its slots' device-address accesses: the function is +/// no device-replay variant, whose slots' addresses are its replayed command's. pub(crate) fn identity_contained(cx: &SelectCx<'_>) -> bool { - identity(cx.profile) && !cx.inputs.replay_bindings + !cx.inputs.replay_bindings } /// An access of buffer slot `slot`, a read where `read`, whose byte offset is a translation-time @@ -1235,12 +1094,6 @@ pub(crate) fn fixed_offset(cx: &SelectCx<'_>, ptr: Value) -> bool { /// [`finish_slots`]'s placement, in its charged working tables. fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result>, Error> { let p = cx.profile; - let limits = &p.fields().limits; - let addressed = p.fields().buffer_access == BufferAccess::Addressed; - let range_variant = || -> Error { - // Profile F honors `BufferRangeLimit` at plan time; it has no device address. - Unsupported::needs_any_of(Feature::BufferRange, vec![p.addressed_needs()]).into() - }; let memory = cx.memory; let stage = cx.stage; let sources: Vec = cx @@ -1254,11 +1107,11 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result, m: &mut Meter) -> Result = Vec::new(); for &s in &sources { - if shared_slot(s).is_some() { - continue; - } - if replay || identity(p) { + if shared_slot(s).is_none() { own.push((s, psb_lowering(Window::Whole)?)); - continue; - } - cx.facts.insert(RuntimeFact::BufferRangeLimit { slot: s }); - let l = if cx.inputs.psb_slots.contains(&s) { - if !addressed { - return Err(range_variant()); - } - psb_lowering(Window::Whole)? - } else { - SlotLowering::View - }; - own.push((s, l)); - } - // The push fields as they will be once the slot forms are final: a device-address slot reads - // the root table instead of its residual. The `ArgumentTable` is one more uniform buffer when - // they spill (the synthetic bindings count against the limits). - let forms = memory - .slots - .iter() - .zip(&lowering) - .filter_map(|(plan, l)| l.map(|l| (plan.slot, l))) - .chain(own.iter().copied()); - let mut census = Census::new( - &cx.push, - ( - cx.families.access.dynamic.used, - identity(p), - own_addresses, - (crate::lower::push::base(cx), p.push_window()), - ), - forms, - m, - )?; - if addressed { - // The storage views the step may move, the highest Metal index first: the accessed slots - // (by their chosen windows) in memory-plan order, then the source buffers of their own. - // A stable sort read from its end takes the last of equal indices, as the search for the - // greatest index per step once did. - let storage = SlotLowering::View; - let mut order: Vec<(u32, Moved)> = Vec::new(); - for (i, (plan, (l, w))) in memory - .slots - .iter() - .zip(lowering.iter().zip(&windows)) - .enumerate() - { - m.tick(1)?; - if let (Some(l), Some(w)) = (l, w) { - if *l == storage { - order.push((plan.slot.index, Moved::Accessed(i, *w))); - } - } - } - for (k, (s, l)) in own.iter().enumerate() { - m.tick(1)?; - if *l == storage { - order.push((s.index, Moved::Own(k))); - } - } - order.sort_by_key(|(index, _)| *index); - loop { - m.tick(1)?; - let total = cx.descriptors.plus(&census.counts(stage)); - let storage_bound = matches!( - total.exceeded(limits), - Some(( - VkLimit::MaxPerStageDescriptorStorageBuffers | VkLimit::MaxPerStageResources, - _, - _ - )) - ); - if !storage_bound { - break; - } - let Some((_, moved)) = order.pop() else { - break; - }; - match moved { - Moved::Accessed(i, window) => { - let psb = psb_lowering(window)?; - if let (Some(l), Some(plan)) = (lowering.get_mut(i), memory.slots.get(i)) { - *l = Some(psb); - census.addressed(plan.slot); - } - } - Moved::Own(k) => { - let psb = psb_lowering(Window::Whole)?; - if let Some((s, l)) = own.get_mut(k) { - *l = psb; - census.addressed(*s); - } - } - } } } let mut slots = Vec::with_capacity(memory.slots.len()); @@ -1517,14 +1258,22 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result = own @@ -1546,11 +1295,7 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result, m: &mut Meter) -> Result, plan: &SlotPlan) -> Option { - if !identity(cx.profile) || plan.element.is_some() || plan.argument_buffer { + if plan.element.is_some() || plan.argument_buffer { return None; } let twos = cx @@ -1607,7 +1352,6 @@ fn unwritten_slots( .any(|&(key, _)| module.symbols().get(key) == Some(BUFFER_NO_ALIAS)) }) }; - let identity = identity(cx.profile); cx.memory .slots .iter() @@ -1617,9 +1361,7 @@ fn unwritten_slots( let unwritten = !plan.access.write && !plan.wide.write && unaliased(plan.param); let read_only = match l { Some(SlotLowering::View) => unwritten, - Some(SlotLowering::Psb { .. }) if identity => { - unwritten || plan.space == AddrSpace::Constant - } + Some(SlotLowering::Psb { .. }) => unwritten || plan.space == AddrSpace::Constant, _ => false, }; read_only @@ -1773,15 +1515,6 @@ pub fn replay_guest_base( fb.convert(crate::spirv::ir::ConvOp::Bitcast, base, uvec2) } -/// A storage slot the per-stage limit fallback moves to its device address. -#[derive(Clone, Copy)] -enum Moved { - /// Memory-plan slot `.0`, with its chosen window. - Accessed(usize, Window), - /// The `.0`th source buffer of its own. - Own(usize), -} - /// The device-address lowering of a slot with `window`: the window's start fixes how the `u32` /// pointer offset maps back to a 64-bit displacement from the bind offset, which is exact for every /// window of at most 2³² bytes. A `Bounded` window longer than that holds constant offsets the @@ -1794,9 +1527,9 @@ fn psb_lowering(window: Window) -> Result { } } -/// Accept the push placement: every field placed in the `ArgumentTable` is read from the table's -/// uniform buffer ([`table`]), whose descriptor [`finish_slots`] counted from the same field set, -/// and the table fits `maxUniformBufferRange`. +/// Accept the push placement: every field placed in the `ArgumentTable` is read from the parameter +/// block at the pushed `ArgumentTableAddress`, which [`finish_slots`] placed from the same field +/// set. pub fn accept_placement(cx: &SelectCx<'_>, placement: &PushPlacement) -> Result<(), Error> { let spilled = placement .fields @@ -1807,18 +1540,6 @@ pub fn accept_placement(cx: &SelectCx<'_>, placement: &PushPlacement) -> Result< cx.invariant("the push placement disagrees with the counted ArgumentTable descriptor") ); } - let range = cx.profile.fields().limits.max_uniform_buffer_range; - if placement.argument_table_size > range && !cx.families.access.identity { - return Err(Unsupported::needs( - Feature::DescriptorCount, - Capability::Limit { - limit: VkLimit::MaxUniformBufferRange, - required: u64::from(placement.argument_table_size), - available: u64::from(range), - }, - ) - .into()); - } Ok(()) } @@ -1829,25 +1550,19 @@ pub fn table_field( fb: &mut FunctionBuilder<'_>, field: PushField, ) -> BResult { - let read = match &cx.decl.families.access.table { - Some(t) => table::read(fb, t, field)?, - // Under the identity domains the table is the parameter block at the pushed address. - None if cx.plan.families.access.identity => { - let offset = cx.plan.push.fields.iter().find_map(|f| match f.loc { - PushLoc::ArgumentTable { offset } if f.field == field => Some(offset), - _ => None, - }); - match offset { - Some(offset) => { - let block = cx.push_field(fb, PushField::ArgumentTableAddress)?; - let mut lines = Vec::new(); - for line in table::lines(offset, field) { - lines.push((line, cx.block_line(fb, block, line)?)); - } - Some(table::field_of_lines(fb, &lines, offset, field)?) - } - None => None, + // The table is the parameter block at the pushed address. + let offset = cx.plan.push.fields.iter().find_map(|f| match f.loc { + PushLoc::ArgumentTable { offset } if f.field == field => Some(offset), + _ => None, + }); + let read = match offset { + Some(offset) => { + let block = cx.push_field(fb, PushField::ArgumentTableAddress)?; + let mut lines = Vec::new(); + for line in table::lines(offset, field) { + lines.push((line, cx.block_line(fb, block, line)?)); } + Some(table::field_of_lines(fb, &lines, offset, field)?) } None => None, }; @@ -1867,27 +1582,12 @@ pub fn declare( ) -> BResult { let mut d = Declared { local: local::declare(mb, plan)?, - table: match plan.families.access.identity { - true => None, - false => table::declare(mb, &plan.push)?, - }, blob: match &plan.families.access.blob { - Some(b) => Some(crate::memory::blob::declare(mb, plan.stage, b)?), + Some(b) => Some(crate::memory::blob::declare(mb, b)?), None => None, }, - pulled: pulled::declare(mb, &plan.families.access)?, - handle_table: handle::declare_table(mb, plan)?, - sampler_table: handle::declare_sampler_table(mb, plan)?, - resolve: match dynamic::defines_search(&plan.families.access.dynamic) { - true => { - let wide = dynamic::wide_type(mb)?; - Some(crate::memory::roots::define_resolve(mb, wide)?) - } - false => None, - }, tile: tile::declare(mb, &plan.families.access)?, function_tables: function_table::declare(mb, plan)?, - status: absent::declare(mb, plan.stage, &plan.families.access)?, ..Declared::default() }; for (i, s) in plan.slots.iter().enumerate() { diff --git a/crates/metal2vulkan/src/lower/access/pointer.rs b/crates/metal2vulkan/src/lower/access/pointer.rs index 1843c07c1..871c59d15 100644 --- a/crates/metal2vulkan/src/lower/access/pointer.rs +++ b/crates/metal2vulkan/src/lower/access/pointer.rs @@ -573,10 +573,9 @@ pub fn null_value(fb: &mut FunctionBuilder<'_>, ty: &DemoteTy) -> BResult