diff --git a/crates/metal2vulkan-runtime/src/tests/translator_fields.rs b/crates/metal2vulkan-runtime/src/tests/translator_fields.rs index 7ffc598e9..3f5273d02 100644 --- a/crates/metal2vulkan-runtime/src/tests/translator_fields.rs +++ b/crates/metal2vulkan-runtime/src/tests/translator_fields.rs @@ -149,10 +149,6 @@ const STAGE_MODULE: &[(&str, Verdict)] = &[ Fact("the runtime records every note of precision_notes at creation, these among them"), ), ("own_pixel_textures", Applied), - ( - "level_reads", - Fact("the runtime takes a read of a texture as one of its whole bound view"), - ), ( "private_bytes", Fact("the bytes FunctionStorageAssumed's announcement may name"), diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 4c1e1e616..d6dbaeba2 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -43,10 +43,10 @@ use crate::pipeline::graphics::{ LineBandState, TessellationState, }; use crate::pipeline::interface::{ - AccessSet, BufferForm, BufferKind, BufferSlot, CommandWrites, LevelReads, NumberedSampler, - PatchDomain, PipelineInterface, PlacedField, PushLoc, PushPlacement, SampledLevels, - SamplerArray, SamplerSlot, SlotInterface, StageDescriptor, StageInterface, StageSpec, - TessellationStage, TextureAccess, TextureSlot, ThreadgroupArgument, Window, + AccessSet, BufferForm, BufferKind, BufferSlot, CommandWrites, NumberedSampler, PatchDomain, + PipelineInterface, PlacedField, PushLoc, PushPlacement, SamplerArray, SamplerSlot, + SlotInterface, StageDescriptor, StageInterface, StageSpec, TessellationStage, TextureAccess, + TextureSlot, ThreadgroupArgument, Window, }; use crate::pipeline::layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, @@ -1110,12 +1110,10 @@ codec_struct! { stage, slots, threadgroup, push, descriptors, spec, needs_pointer_translation, needs_handle_translation, 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, level_reads, + numbered_samplers, own_pixel_textures, private_bytes, sampler_arrays, } SamplerArray { slot, samplers } - LevelReads { slot, any, named, lowest_read, sampled } - SampledLevels { sampler, highest_lod_bits, lowest_lod_bits, computed } TessellationStage { domain, control_points } TessellationDescriptor { max_tessellation_factor, partition_mode, factor_format, factor_step_function, @@ -1319,7 +1317,7 @@ 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, level_reads, + specialized_notes, own_pixel_textures, private_bytes, stats, } SpecializedNote { note, when } diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 8fdbe17dc..baf53fa95 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 2340; /// 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 = 605; +pub const ARTIFACT_FORMAT_VERSION: u32 = 606; /// 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 diff --git a/crates/metal2vulkan/src/pipeline/api_tests.rs b/crates/metal2vulkan/src/pipeline/api_tests.rs index ca2b684e6..015d09143 100644 --- a/crates/metal2vulkan/src/pipeline/api_tests.rs +++ b/crates/metal2vulkan/src/pipeline/api_tests.rs @@ -45,7 +45,6 @@ fn stage_module_bytes_are_little_endian_words() { constant_blob: None, rounded_colors: Vec::new(), own_pixel_textures: Vec::new(), - level_reads: Vec::new(), private_bytes: 0, specialized_notes: Vec::new(), stats: ModuleStats::default(), @@ -95,7 +94,6 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() { constant_blob: None, rounded_colors: Vec::new(), own_pixel_textures: Vec::new(), - level_reads: Vec::new(), private_bytes: 0, specialized_notes: vec![ SpecializedNote { diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 7cfc629cd..f11fb5a59 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -11,7 +11,7 @@ use crate::cache::{Hash256, PipelineKey, SpecializationKey}; use crate::device::requirements::Requirements; use crate::pipeline::facts::{Mechanism, RuntimeFact}; use crate::pipeline::graphics::GraphicsState; -use crate::pipeline::interface::{LevelReads, PipelineInterface, SampledLevels}; +use crate::pipeline::interface::PipelineInterface; use crate::pipeline::layout::PipelineLayout; use crate::pipeline::sym::SpecKey; use crate::pipeline::vertex::VertexInputState; @@ -96,10 +96,6 @@ fn stage_footprint(stage: &StageModule) -> u64 { + vector_bytes::(stage.specialized_notes.capacity()) + clauses + vector_bytes::(stage.rounded_colors.capacity() + stage.own_pixel_textures.capacity()) - + vector_bytes::(stage.level_reads.capacity()) - + (stage.level_reads.iter()) - .map(|reads| vector_bytes::(reads.sampled.capacity())) - .sum::() } /// A compiled compute pipeline. @@ -179,9 +175,6 @@ pub struct StageModule { /// rectangle bounding its scissors, a pixel wider each way for its helper invocations, on a /// framebuffer below `2^24` pixels a side. Empty for every other stage. pub own_pixel_textures: Vec, - /// The levels of its bound view each texture slot's reads reach, one entry a slot, sorted by - /// slot (`StageInterface::level_reads`). Empty for a kernel and a stage the link makes. - pub level_reads: Vec, /// The private memory a thread of the stage keeps, in bytes /// (`StageInterface::private_bytes`): what `PrecisionNote::FunctionStorageAssumed`'s /// announcement names. 0 for a stage the link makes itself. diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index c0fcb2785..56343635d 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -3101,8 +3101,6 @@ fn lower_bounded( } // A fragment function's texture slots read only at the fragment's own pixel. let own_pixel_textures = crate::spirv::requirements::own_pixel_textures(&module, m)?; - // The levels of its bound view each texture slot's reads reach. - let level_reads = crate::spirv::requirements::level_reads(&module, m)?; // A `half` rounded through `OpQuantizeToF16` (`QuantizeForm::Device`): the module records the // native note on every profile, a result below the smallest normal half the device's. let mut precision = plan.precision.clone(); @@ -3211,7 +3209,7 @@ fn lower_bounded( &function_tables, (reaches_command_buffers, command_writes), (writes_textures, numbered_samplers), - (own_pixel_textures, level_reads), + own_pixel_textures, unbound, ); let mut requirements = module.requirements.clone(); @@ -3386,7 +3384,7 @@ fn stage_interface( function_tables: &std::collections::BTreeSet, (reaches_command_buffers, command_writes): (bool, crate::pipeline::interface::CommandWrites), (writes_textures, numbered_samplers): (bool, Vec), - (own_pixel_textures, level_reads): (Vec, Vec), + own_pixel_textures: Vec, unbound: unbound::Unbound, ) -> StageInterface { use crate::pipeline::interface::{BufferKind, BufferSlot}; @@ -3452,7 +3450,6 @@ fn stage_interface( unbound_storage_textures: unbound.storage_textures, numbered_samplers, own_pixel_textures, - level_reads, private_bytes: plan.private_bytes, sampler_arrays: crate::lower::sampler::sampler_arrays(plan), } diff --git a/crates/metal2vulkan/src/pipeline/compile/api.rs b/crates/metal2vulkan/src/pipeline/compile/api.rs index a3dc6ebaf..fc581d772 100644 --- a/crates/metal2vulkan/src/pipeline/compile/api.rs +++ b/crates/metal2vulkan/src/pipeline/compile/api.rs @@ -1577,7 +1577,6 @@ fn stage_module(c: &CompiledFunction, linked: &Linked, i: usize) -> Result, - /// The levels of its bound view that each texture slot's reads reach, one entry a slot, sorted - /// by slot ([`LevelReads`]): what a runtime needs to tell whether a slot whose texture presents - /// a color attachment of the draw's render pass instance at some level reads that level. - /// Empty for a kernel. - #[cfg_attr(feature = "serde", serde(default))] - pub level_reads: Vec, /// The private memory a thread of the function keeps, in bytes: its `thread` variables and /// arrays a run-time index reaches, its call stacks, and the constants it holds per thread so /// (`ProfileFields::function_storage` holds it). What @@ -429,207 +423,6 @@ pub struct SamplerArray { pub samplers: Vec, } -/// The levels of its bound view that a texture slot's reads reach, each counted from the view's -/// first level (`StageInterface::level_reads`, `StageModule::level_reads`), as the module's -/// instructions decide them (`spirv::requirements::level_reads`, structural). A sample's level is -/// its sampler's to bound, so the fact lists each sampler the slot is sampled through apart. -/// Vulkan's rules decide -/// the levels (Image Level(s) Selection): a sample reads `clamp(λ, 0, q)` past the view's first -/// level, `λ` its level of detail clamped into the sampler's `[minLod, maxLod]`; a gather reads -/// the first level; a fetch and a size query read the level they name. -#[non_exhaustive] -#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct LevelReads { - /// The texture slot. - pub slot: u32, - /// Some use of the slot may reach any level of its view, or answers by the view's level - /// count: a fetch or size query at a level the module computes, a level-count query beyond the - /// containment of a constant level (`UMin(c, levels - 1)` and `c < levels`), a level-of-detail - /// query, a sample with a minimum level of detail operand, a storage access, or any use the - /// walk does not follow (a call, a store, a phi or select of the image). - pub any: bool, - /// The highest level a fetch, a size query or a gather reads, each a constant (a gather reads - /// level 0), or the highest constant a level-count containment compares; `None` where none - /// does. - pub named: Option, - /// The lowest level whose texels a fetch or a gather reads, each a constant (a gather reads - /// level 0); `None` where none does. A size query reads no texel, nor does a level-count - /// containment's comparison: each raises `named` alone. - pub lowest_read: Option, - /// The slot's samples, by the sampler each reads through, sorted by sampler. - pub sampled: Vec, -} - -/// The samples of a texture slot through one sampler ([`LevelReads::sampled`]). -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub struct SampledLevels { - /// The sampler: a runtime sampler's slot, or a constexpr sampler. - pub sampler: crate::pipeline::sym::SamplerRef, - /// The bits of the highest explicit level of detail among its samples that is a constant - /// `f32` (a NaN where one is); `None` where none is. - pub highest_lod_bits: Option, - /// The bits of the lowest explicit level of detail among its samples that is a constant `f32` - /// (a NaN where one is); `None` where none is. - pub lowest_lod_bits: Option, - /// Some sample's level of detail is the module's to compute: implicit, biased, from - /// gradients, or an explicit level that is no constant. The sampler's `maxLod` bounds it. - pub computed: bool, -} - -/// A sampler's level selection as a runtime binds it ([`SampledLevels::level`]): its -/// `minLod`, `maxLod` and `mipLodBias`, whether its mipmap mode is `LINEAR`, and whether every -/// texel of the view is finite ([`SamplerLevels::finite_texels`]), where a linear blend of a level -/// with weight 0 reads that level's texel to no effect. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq)] -pub struct SamplerLevels { - pub min_lod: f32, - pub max_lod: f32, - pub bias: f32, - pub linear: bool, - pub finite_texels: bool, -} - -impl SamplerLevels { - /// The levels of Vulkan sampler `desc` over a view whose texels `finite_texels` says are - /// finite. - pub fn of(desc: &vk::SamplerDesc, finite_texels: bool) -> SamplerLevels { - SamplerLevels { - min_lod: desc.min_lod, - max_lod: desc.max_lod, - bias: desc.mip_lod_bias, - linear: desc.mipmap_mode == vk::SamplerMipmapMode::LINEAR, - finite_texels, - } - } - - /// Whether every texel a view of `format` holds reads as a finite number: an 8-, 10- or - /// 16-bit normalized or sRGB color format, or an integer one. `false` for every other format, - /// a float one among them, whose texels may be infinities or NaNs. - pub fn finite_texels(format: vk::Format) -> bool { - use vk::Format as F; - matches!( - format, - F::R8_UNORM - | F::R8_SNORM - | F::R8G8_UNORM - | F::R8G8_SNORM - | F::R8G8B8A8_UNORM - | F::R8G8B8A8_SNORM - | F::R8G8B8A8_SRGB - | F::B8G8R8A8_UNORM - | F::B8G8R8A8_SRGB - | F::A2B10G10R10_UNORM_PACK32 - | F::A2R10G10B10_UNORM_PACK32 - | F::R16_UNORM - | F::R16_SNORM - | F::R16G16_UNORM - | F::R16G16_SNORM - | F::R16G16B16A16_UNORM - | F::R16G16B16A16_SNORM - | F::R5G6B5_UNORM_PACK16 - | F::B5G6R5_UNORM_PACK16 - | F::R8_UINT - | F::R8_SINT - | F::R8G8_UINT - | F::R8G8_SINT - | F::R8G8B8A8_UINT - | F::R8G8B8A8_SINT - | F::R16_UINT - | F::R16_SINT - | F::R16G16_UINT - | F::R16G16_SINT - | F::R16G16B16A16_UINT - | F::R16G16B16A16_SINT - | F::R32_UINT - | F::R32_SINT - | F::R32G32_UINT - | F::R32G32_SINT - | F::R32G32B32A32_UINT - | F::R32G32B32A32_SINT - ) - } -} - -impl SampledLevels { - /// The highest explicit constant level of detail among the samples. - pub fn highest_lod(&self) -> Option { - self.highest_lod_bits.map(f32::from_bits) - } - - /// The highest level, counted from the view's first, these samples reach through a sampler - /// of levels `s`; `None` where they may reach any. - /// - /// A sample's level of detail is at most `L`: `maxLod`, or for a constant explicit `c` with - /// nothing computed, `c` plus the sampler's bias where it is positive (Vulkan adds the - /// sampler's bias to an explicit level of detail too), clamped into `[minLod, maxLod]`; at - /// least 0. The nearest mipmap mode reads level `floor(L + 0.5)` at most (both of Vulkan's - /// roundings); the linear one reads `floor(L) + 1` with the weight `L - floor(L)`, so where - /// `L` is a whole level and the texels are finite it reads level `L` to effect alone. A - /// sampler whose `minLod` exceeds its `maxLod`, or whose bounds are no finite numbers, - /// reaches any level. - pub fn level(&self, s: SamplerLevels) -> Option { - // A last level past every texture's: Metal's largest has 15 levels. - const PAST: f32 = 64.0; - if !(s.min_lod.is_finite() && s.max_lod.is_finite()) || s.min_lod > s.max_lod { - return None; - } - let computed = self.computed.then_some(s.max_lod); - // A negative bias is not counted on to lower the level. - let explicit = (self.highest_lod()).map(|c| match c.is_nan() { - true => s.max_lod, - false => (c + s.bias.max(0.0)).clamp(s.min_lod, s.max_lod), - }); - let top = (computed.into_iter().chain(explicit)).fold(0.0_f32, |top, l| top.max(l)); - if top >= PAST { - return None; - } - let level = match s.linear { - true if s.finite_texels && top.fract() == 0.0 => top, - true => top.floor() + 1.0, - false => (top + 0.5).floor(), - }; - Some(level as u32) - } - - /// The lowest explicit constant level of detail among the samples. - pub fn lowest_lod(&self) -> Option { - self.lowest_lod_bits.map(f32::from_bits) - } - - /// The lowest level, counted from the view's first, these samples may read through a sampler - /// of levels `s`, over a view of more levels than it (a view whose last level is lower reads - /// that one in its place: the LOD Operation clamps into `[0, q]`). - /// - /// A sample's level of detail is at least `L`: `minLod` where one is computed (the LOD - /// Operation clamps it into `[minLod, maxLod]` after any bias), and for the lowest constant - /// explicit `c`, `c` plus the sampler's bias where it is negative, clamped so; at least 0. - /// Either mipmap mode reads level `floor(L)` or a higher one: the nearest one - /// `ceil(L + 0.5) - 1` or `floor(L + 0.5)`, the linear one `floor(L)` and the next. A NaN - /// constant, a sampler whose `minLod` exceeds its `maxLod` (the level of detail is undefined), - /// or one whose bounds are no finite numbers, reaches the first level. - pub fn lowest(&self, s: SamplerLevels) -> u32 { - if !(s.min_lod.is_finite() && s.max_lod.is_finite()) || s.min_lod > s.max_lod { - return 0; - } - let computed = self.computed.then_some(s.min_lod); - let explicit = match self.lowest_lod() { - Some(c) if c.is_nan() => return 0, - // A positive bias is not counted on to raise the level, and a NaN one is none, as a - // device's sampler takes it (`metal::sampler::device_lod_bias`). - Some(c) => Some((c + s.bias.min(0.0)).clamp(s.min_lod, s.max_lod)), - None => None, - }; - let low = (computed.into_iter().chain(explicit)).reduce(f32::min); - low.map_or(0, |low| low.max(0.0).floor() as u32) - } -} - -impl LevelReads {} - /// What a tessellation evaluation module (a post-tessellation vertex function) needs of the /// pipeline's control stage: its patch domain and Metal's control points per patch. It reads the /// patch index and the instance as `uint` patch inputs at diff --git a/crates/metal2vulkan/src/pipeline/link/band.rs b/crates/metal2vulkan/src/pipeline/link/band.rs index 60ec887c1..54ad6fbac 100644 --- a/crates/metal2vulkan/src/pipeline/link/band.rs +++ b/crates/metal2vulkan/src/pipeline/link/band.rs @@ -384,7 +384,6 @@ impl LineBand { rounded_colors: Vec::new(), specialized_notes: Vec::new(), own_pixel_textures: Vec::new(), - level_reads: Vec::new(), private_bytes: 0, stats, }, diff --git a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs index cc3a16181..0ba84413e 100644 --- a/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs +++ b/crates/metal2vulkan/src/pipeline/link/tessellation/mod.rs @@ -444,7 +444,6 @@ pub fn synthesized_stages( rounded_colors: Vec::new(), specialized_notes: Vec::new(), own_pixel_textures: Vec::new(), - level_reads: Vec::new(), private_bytes: 0, stats, }, diff --git a/crates/metal2vulkan/src/pipeline/link/tests.rs b/crates/metal2vulkan/src/pipeline/link/tests.rs index 73797f0ee..222eeaac9 100644 --- a/crates/metal2vulkan/src/pipeline/link/tests.rs +++ b/crates/metal2vulkan/src/pipeline/link/tests.rs @@ -149,7 +149,6 @@ pub(super) fn iface( unbound_storage_textures: false, numbered_samplers: Vec::new(), own_pixel_textures: Vec::new(), - level_reads: Vec::new(), private_bytes: 0, sampler_arrays: Vec::new(), } diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index 28a940a96..59732cc8b 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -122,10 +122,9 @@ pub use graphics::{ }; pub use indirect_draws::IndirectDrawLayout; pub use interface::{ - AccessSet, AttributeFetch, BufferForm, BufferKind, BufferSlot, CommandWrites, LevelReads, - NumberedSampler, PatchDomain, PipelineInterface, PlacedField, PushLoc, PushPlacement, - SampledLevels, SamplerArray, SamplerLevels, SamplerSlot, SlotInterface, TextureAccess, - TextureSlot, ThreadgroupArgument, Window, + AccessSet, AttributeFetch, BufferForm, BufferKind, BufferSlot, CommandWrites, NumberedSampler, + PatchDomain, PipelineInterface, PlacedField, PushLoc, PushPlacement, SamplerArray, SamplerSlot, + SlotInterface, TextureAccess, TextureSlot, ThreadgroupArgument, Window, }; pub use layout::{ BindingSource, DescriptorBinding, DescriptorSetLayout, PipelineLayout, PushConstantRange, diff --git a/crates/metal2vulkan/src/spirv/requirements/level_reads.rs b/crates/metal2vulkan/src/spirv/requirements/level_reads.rs deleted file mode 100644 index 2b76cdad7..000000000 --- a/crates/metal2vulkan/src/spirv/requirements/level_reads.rs +++ /dev/null @@ -1,468 +0,0 @@ -//! Which levels of its bound view each texture slot of a module reads -//! (`pipeline::LevelReads`). -//! -//! A runtime that serves a draw's read of a texture its own render pass renders at one level -//! (the runtime's `texture/attached_reads.rs`) can bind the texture's own image in place of a copy -//! where the draw reads none of the attached levels. That needs the highest and the lowest level -//! each read reaches, counted from the view's first level, which this decides from the module's -//! instructions alone: -//! -//! - **A sample** (`OpImageSample*`, any of its forms) reads the levels its level of detail -//! selects, which its sampler clamps into `[minLod, maxLod]` (Vulkan's LOD Operation), so the -//! fact holds it by sampler: the slot's binding's own (a combined image sampler's, or a -//! separate image's pairing), and whether its level of detail is a constant `f32` the -//! instruction names (explicit, without gradients) or the module's to compute (implicit, -//! biased, from gradients, or an explicit one that is no constant). A sample with a minimum -//! level of detail operand may select any level ("undefined" where it exceeds `maxLod`). -//! - **A gather** reads the view's first level ("4 texels in the base level of the image view", -//! Texel Gathering). -//! - **A fetch or a size query** reads the level it names: a constant, or the lowering's -//! containment of one, `UMin(c, levels - 1)` of the slot's own level count (`lower::texture`'s -//! `clamp_below`). A level-count query whose every use is that containment, or the in-range -//! test `c < levels` of a constant `c`, answers alike through any view of more than `c` levels. -//! A fetch without a level reads level 0. -//! - **Anything else** reaches any level: a fetch or size query at a level the module computes, -//! a level-count query used otherwise, a level-of-detail query (which answers by the view's -//! level count), a storage access or texel pointer, and any use of the image the walk does not -//! follow (a call, a store, a phi or select of it, the entry's returned value). -//! -//! What carries a slot's image on is followed as `own_pixel` follows it: a load, `OpSampledImage`, -//! `OpImage` or copy whose result is an image, a sampled image or a pointer to one. A slot's -//! binding of each kind is a seed: the texture's own (no sampler: a sample through it reaches any -//! level), a combined image sampler's, or a separate image's, whose sampler is its pairing's. - -use std::collections::{BTreeMap, HashMap}; - -use super::own_pixel::{carried_on, holds_image}; -use crate::budget::Meter; -use crate::error::Error; -use crate::pipeline::interface::{LevelReads, SampledLevels}; -use crate::pipeline::sym::{ResourceKind, SamplerRef}; -use crate::spirv::error::BResult; -use crate::spirv::ids::Value; -use crate::spirv::ir::{ - BinOp, ConstKind, Constant, ExecModel, GlobalKind, GlslOp, ImageQuery, Inst, Terminator, Type, - TypedModule, ValueOrigin, -}; - -/// No seed: a value that holds no slot's image. -const NONE: u32 = u32::MAX; - -#[cfg(test)] -mod tests; - -/// What the walk found of one slot's reads. -#[derive(Default)] -struct Found { - any: bool, - named: Option, - lowest_read: Option, - sampled: BTreeMap, -} - -/// The levels of detail of one sampler's samples of a slot. -#[derive(Default)] -struct Lods { - /// The highest and the lowest constant explicit level of detail, each a NaN where one is. - highest: Option, - lowest: Option, - /// Whether one is computed. - computed: bool, -} - -impl Found { - /// A level-count containment's comparison of `level`, or a size query at it: the view holds - /// more levels than it. - fn name(&mut self, level: u32) { - self.named = Some(self.named.map_or(level, |n| n.max(level))); - } - - /// A read of `level`'s texels. - fn read(&mut self, level: u32) { - self.name(level); - self.lowest_read = Some(self.lowest_read.map_or(level, |l| l.min(level))); - } - - fn sample(&mut self, sampler: SamplerRef, lod: Option) { - let lods = self.sampled.entry(sampler).or_default(); - match lod { - Some(c) => { - lods.highest = Some(lods.highest.map_or(c, |h| kept_nan(h, c, f32::max))); - lods.lowest = Some(lods.lowest.map_or(c, |l| kept_nan(l, c, f32::min))); - } - None => lods.computed = true, - } - } -} - -/// `pick` of `a` and `b`, or a NaN where either is one: `f32::max` and `f32::min` drop a NaN, whose -/// level a sampler decides apart. -fn kept_nan(a: f32, b: f32, pick: fn(f32, f32) -> f32) -> f32 { - match a.is_nan() || b.is_nan() { - true => f32::NAN, - false => pick(a, b), - } -} - -/// The levels each texture slot of module `m` reads (the module docs), one entry a slot, sorted by -/// slot; empty for a kernel. -/// -/// One pass lists the instructions that carry an image on, and a worklist from the slots' -/// variables finds every value that holds one, as `own_pixel_textures` does. Where the module -/// queries a slot's level count, a pass finds the containment's `levels - 1` and its `UMin` of a -/// constant. A last pass judges every use. The table of values and the list are charged to -/// `meter` while held. -pub fn level_reads(m: &TypedModule, meter: &mut Meter) -> Result, Error> { - if m.entry().model == ExecModel::GLCompute { - return Ok(Vec::new()); - } - // The slots' variables, each with its seed: its slot and the sampler it samples through. - let mut seeds: Vec<(u32, Option)> = Vec::new(); - let mut found: BTreeMap = BTreeMap::new(); - let mut work: Vec<(Value, u32)> = Vec::new(); - for g in m.globals() { - let GlobalKind::Resource(slot) = &g.kind else { - continue; - }; - let seed = match slot.kind { - ResourceKind::Texture => Some((slot.index, None)), - ResourceKind::CombinedTextureSampler(cs) => Some((slot.index, Some(cs.sampler))), - ResourceKind::SeparateTexture(_) => slot - .separate_texture_of() - .map(|(texture, cs)| (texture, Some(cs.sampler))), - _ => None, - }; - if let Some((texture, sampler)) = seed { - found.entry(texture).or_default(); - let index = u32::try_from(seeds.len()).unwrap_or(NONE); - seeds.push((texture, sampler)); - work.push((g.value, index)); - } - } - if seeds.is_empty() { - return Ok(Vec::new()); - } - let table = 4 * m.values().len(); - meter.charge(table)?; - let mut carried = vec![NONE; m.values().len()]; - for &(v, seed) in &work { - if let Some(c) = carried.get_mut(v.index()) { - *c = seed; - } - } - let mut carriers: Vec<(Value, Value)> = Vec::new(); - for n in m.blocks().iter().flat_map(|b| &b.insts) { - if let (Some(r), Some(from)) = (n.result, carried_on(&n.inst)) { - if holds_image(m, r)? { - carriers.push((from, r)); - } - } - } - let listed = std::mem::size_of_val(carriers.as_slice()); - meter.charge(listed)?; - carriers.sort_unstable(); - while let Some((v, seed)) = work.pop() { - let start = carriers.partition_point(|&(from, _)| from < v); - let from_v = carriers - .iter() - .skip(start) - .take_while(|&&(from, _)| from == v); - for &(_, r) in from_v { - if let Some(c) = carried.get_mut(r.index()).filter(|c| **c == NONE) { - *c = seed; - work.push((r, seed)); - } - } - } - drop(carriers); - meter.release(listed); - let seed_of = |v: Value| { - let seed = *carried.get(v.index())?; - seeds.get(seed as usize).copied() - }; - let contained = Containment::of(m, &seed_of)?; - for b in m.blocks() { - // A phi or a return of the image reaches what the walk does not follow. - let merged = b - .phis - .iter() - .flat_map(|phi| phi.incoming.iter().map(|(v, _)| *v)); - let returned = match &b.term { - Terminator::ReturnValue(v) => Some(*v), - _ => None, - }; - for (slot, _) in merged.chain(returned).filter_map(seed_of) { - found.entry(slot).or_default().any = true; - } - for n in &b.insts { - let mut uses: Vec = Vec::new(); - n.inst.for_each_value(|v| uses.push(v)); - for v in uses { - if let Some((slot, sampler)) = seed_of(v) { - let f = found.entry(slot).or_default(); - judge(m, &contained, (n.result, &n.inst), (v, slot, sampler), f)?; - } else if let Some(&slot) = contained.levels.get(&v) { - // A level count used but by the containment of a constant level. - let f = found.entry(slot).or_default(); - match level_count_use(m, &n.inst, v)? { - LevelCountUse::Top => {} - LevelCountUse::Compared(c) => f.name(c), - LevelCountUse::Other => f.any = true, - } - } else if let Some(&slot) = contained.tops.get(&v) { - let f = found.entry(slot).or_default(); - match contained.clamps_by_use(m, &n.inst, v)? { - Some(c) => f.name(c), - None => f.any = true, - } - } - } - } - } - meter.release(table); - Ok(found - .into_iter() - .map(|(slot, f)| LevelReads { - slot, - any: f.any, - named: f.named, - lowest_read: f.lowest_read, - sampled: f - .sampled - .into_iter() - .map(|(sampler, lods)| SampledLevels { - sampler, - highest_lod_bits: lods.highest.map(f32::to_bits), - lowest_lod_bits: lods.lowest.map(f32::to_bits), - computed: lods.computed, - }) - .collect(), - }) - .collect()) -} - -/// The lowering's containment of a constant level by a slot's level count (the module docs): -/// each level-count query's result, each `levels - 1` of one, and each `UMin` of a constant and -/// such a `levels - 1`, by value, with the slot and (for the `UMin`) the constant. -struct Containment { - levels: HashMap, - tops: HashMap, - clamps: HashMap, -} - -impl Containment { - fn of( - m: &TypedModule, - seed_of: &impl Fn(Value) -> Option<(u32, Option)>, - ) -> BResult { - let mut c = Containment { - levels: HashMap::new(), - tops: HashMap::new(), - clamps: HashMap::new(), - }; - let insts = || m.blocks().iter().flat_map(|b| &b.insts); - for n in insts() { - if let ( - Some(r), - Inst::ImageQuery { - query: ImageQuery::Levels, - image, - }, - ) = (n.result, &n.inst) - { - if let Some((slot, _)) = seed_of(*image) { - c.levels.insert(r, slot); - } - } - } - if c.levels.is_empty() { - return Ok(c); - } - for n in insts() { - if let ( - Some(r), - Inst::Binary { - op: BinOp::ISub, - a, - b, - .. - }, - ) = (n.result, &n.inst) - { - if let (Some(&slot), Some(1)) = (c.levels.get(a), constant_u32(m, *b)?) { - c.tops.insert(r, slot); - } - } - } - for n in insts() { - let ( - Some(r), - Inst::Glsl { - op: GlslOp::UMin, - args, - .. - }, - ) = (n.result, &n.inst) - else { - continue; - }; - let [x, y] = args[..] else { - continue; - }; - for (top, level) in [(x, y), (y, x)] { - if let (Some(&slot), Some(level)) = (c.tops.get(&top), constant_u32(m, level)?) { - c.clamps.insert(r, (slot, level)); - } - } - } - Ok(c) - } - - /// The constant a use of `top` (a `levels - 1`) clamps: `inst` is a `UMin` of it and a - /// constant. `None` for any other use. - fn clamps_by_use(&self, m: &TypedModule, inst: &Inst, top: Value) -> BResult> { - let Inst::Glsl { - op: GlslOp::UMin, - args, - .. - } = inst - else { - return Ok(None); - }; - let [x, y] = args[..] else { - return Ok(None); - }; - match (x == top, y == top) { - (true, false) => constant_u32(m, y), - (false, true) => constant_u32(m, x), - _ => Ok(None), - } - } - - /// The constant level value `v` is: a constant, or a containment of one ([`Containment`]) of - /// slot `slot`'s level count. - fn level(&self, m: &TypedModule, v: Value, slot: u32) -> BResult> { - if let Some(c) = constant_u32(m, v)? { - return Ok(Some(c)); - } - Ok(self - .clamps - .get(&v) - .filter(|&&(of, _)| of == slot) - .map(|&(_, c)| c)) - } -} - -/// How an instruction uses a level-count query's result ([`level_count_use`]). -enum LevelCountUse { - /// The containment's `levels - 1`, whose uses are judged apart. - Top, - /// The in-range test `c < levels` of the constant `c`. - Compared(u32), - /// Any other use. - Other, -} - -/// How `inst` uses `levels`, a level-count query's result: as the containment's `levels - 1` -/// (`ISub` of the constant 1), as the in-range test `c < levels` of a constant, or otherwise. -fn level_count_use(m: &TypedModule, inst: &Inst, levels: Value) -> BResult { - Ok(match inst { - Inst::Binary { - op: BinOp::ISub, - a, - b, - .. - } if *a == levels && *b != levels && constant_u32(m, *b)? == Some(1) => LevelCountUse::Top, - Inst::Binary { - op: BinOp::ULessThan, - a, - b, - .. - } if *b == levels && *a != levels => match constant_u32(m, *a)? { - Some(c) => LevelCountUse::Compared(c), - None => LevelCountUse::Other, - }, - _ => LevelCountUse::Other, - }) -} - -/// Judge `inst`'s use (its result `result`) of `v`, which holds slot `slot`'s image sampled -/// through `sampler` where it is sampled, into `f`. -fn judge( - m: &TypedModule, - contained: &Containment, - (result, inst): (Option, &Inst), - (v, slot, sampler): (Value, u32, Option), - f: &mut Found, -) -> BResult<()> { - match inst { - // What carries the image on reads nothing. - inst if carried_on(inst) == Some(v) && result.is_some() => {} - Inst::ImageQuery { query, image } if *image == v => match query { - ImageQuery::Size | ImageQuery::Samples => {} - // A size query reads no texel: the view holds the level, which raises the highest - // alone. - ImageQuery::SizeLod(l) => match contained.level(m, *l, slot)? { - Some(c) => f.name(c), - None => f.any = true, - }, - // Its uses are judged as the level count's (`level_reads`). - ImageQuery::Levels if result.is_some_and(|r| contained.levels.contains_key(&r)) => {} - _ => f.any = true, - }, - Inst::ImageFetch { image, ops, .. } if *image == v => match ops.lod { - None => f.read(0), - Some(l) => match contained.level(m, l, slot)? { - Some(c) => f.read(c), - None => f.any = true, - }, - }, - Inst::ImageGather { sampled_image, .. } | Inst::ImageDrefGather { sampled_image, .. } - if *sampled_image == v => - { - f.read(0) - } - Inst::ImageSample { - form, - sampled_image, - ops, - .. - } if *sampled_image == v => match sampler { - Some(sampler) if ops.min_lod.is_none() => { - let lod = match (form.implicit, ops.lod, ops.grad) { - (false, Some(l), None) => constant_f32(m, l)?, - _ => None, - }; - f.sample(sampler, lod); - } - _ => f.any = true, - }, - _ => f.any = true, - } - Ok(()) -} - -/// The value of `v` where it is a plain 32-bit integer constant. -fn constant_u32(m: &TypedModule, v: Value) -> BResult> { - scalar_bits(m, v, |ty| matches!(ty, Type::Int { width: 32, .. })) -} - -/// The value of `v` where it is a plain `f32` constant. -fn constant_f32(m: &TypedModule, v: Value) -> BResult> { - Ok(scalar_bits(m, v, |ty| matches!(ty, Type::Float { width: 32 }))?.map(f32::from_bits)) -} - -/// The bits of `v` where it is a plain scalar constant of a type `of` accepts. -fn scalar_bits(m: &TypedModule, v: Value, of: impl Fn(&Type) -> bool) -> BResult> { - let def = m.value(v)?; - let ValueOrigin::Const(c) = def.origin else { - return Ok(None); - }; - if !of(m.types().get(def.ty)?) { - return Ok(None); - } - Ok(match &m.consts().get(c)?.kind { - ConstKind::Plain(Constant::Scalar { bits, .. }) => u32::try_from(bits.0).ok(), - _ => None, - }) -} diff --git a/crates/metal2vulkan/src/spirv/requirements/level_reads/tests.rs b/crates/metal2vulkan/src/spirv/requirements/level_reads/tests.rs deleted file mode 100644 index c1da84796..000000000 --- a/crates/metal2vulkan/src/spirv/requirements/level_reads/tests.rs +++ /dev/null @@ -1,397 +0,0 @@ -//! [`level_reads`] on hand-built fragment modules, one read of texture slot 0 each. - -use super::level_reads; -use crate::budget::{Budget, Meter}; -use crate::pipeline::interface::{LevelReads, SampledLevels, SamplerLevels}; -use crate::pipeline::sym::{CombinedSampler, ResourceKind, ResourceSlot, SamplerRef, Stage}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::ids::{TypeId, Value}; -use crate::spirv::ir::{ - BinOp, ConstBits, Constant, ConvOp, Dim, ExecModel, GlslOp, ImageOperands, ImageQuery, - ImageType, ImageUsage, MemAccess, StorageClass, TexelMemory, Type, TypedModule, -}; - -/// How a module reads texture slot 0. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Read { - /// An implicit-LOD sample through the combined binding of runtime sampler 0. - Implicit, - /// A sample at the constant level of detail 1.5. - ExplicitConstant, - /// A sample at a level of detail the module computes. - ExplicitComputed, - /// A sample from gradients. - Gradients, - /// A sample with a minimum level of detail. - MinLod, - /// A sample through the pairing of a separate image with constexpr sampler words. - SeparatePair, - /// A gather. - Gather, - /// A fetch at the constant level 2. - FetchConstant, - /// A fetch at the constant level 2, beside `3 < levels`. - FetchCompared, - /// A fetch at the lowering's containment of level 1: `UMin(1, levels - 1)`, beside `1 < - /// levels`. - FetchContained, - /// A fetch at a level the module computes. - FetchComputed, - /// A fetch without a level. - FetchBase, - /// A level count added to itself. - LevelsElsewhere, - /// A level-of-detail query. - QueryLod, - /// A size query at the constant level 3. - SizeConstant, - /// A size query without a level, of a storage image of the slot. - Size, - /// An image write of a storage image of the slot. - Write, -} - -const CONSTEXPR: [u64; 2] = [0x12, 0x34]; - -fn scalar(f: &mut FunctionBuilder<'_>, ty: TypeId, bits: u64) -> Value { - let c = f - .module() - .constant(Constant::Scalar { - ty, - bits: ConstBits(bits), - }) - .expect("constant"); - f.module().const_value(c).expect("value") -} - -fn slot(kind: ResourceKind, index: u32) -> ResourceSlot { - ResourceSlot { - stage: Stage::Fragment, - kind, - index, - } -} - -fn module(read: Read) -> TypedModule { - let mut b = ModuleBuilder::new(); - let u32_ = b - .ty(Type::Int { - width: 32, - signed: false, - }) - .expect("uint"); - let f32_ = b.ty(Type::Float { width: 32 }).expect("float"); - let vec2 = b.ty(Type::Vector { elem: f32_, len: 2 }).expect("vec2"); - let vec4 = b.ty(Type::Vector { elem: f32_, len: 4 }).expect("vec4"); - let uvec2 = b.ty(Type::Vector { elem: u32_, len: 2 }).expect("uvec2"); - let image_of = |b: &mut ModuleBuilder, usage| { - b.ty(Type::Image(ImageType { - sampled_type: f32_, - dim: Dim::D2, - depth: false, - arrayed: false, - multisampled: false, - usage, - format: match usage { - ImageUsage::Storage => crate::spv::ImageFormat::Rgba32f, - _ => crate::spv::ImageFormat::Unknown, - }, - })) - .expect("image") - }; - let image = image_of(&mut b, ImageUsage::Sampled); - let storage = image_of(&mut b, ImageUsage::Storage); - let sampled = b.ty(Type::SampledImage { image }).expect("sampled image"); - let sampler_ty = b.ty(Type::Sampler).expect("sampler"); - let combined = CombinedSampler::new(SamplerRef::Slot(0), false, false); - let pair = CombinedSampler::new(SamplerRef::Constexpr(CONSTEXPR), false, false); - let t = b - .resource( - slot(ResourceKind::Texture, 0), - StorageClass::UniformConstant, - // A size query without a level is a storage image's (or a multisampled one's). - match read { - Read::Write | Read::Size => storage, - _ => image, - }, - ) - .expect("texture"); - let ts = b - .resource( - slot(ResourceKind::CombinedTextureSampler(combined), 0), - StorageClass::UniformConstant, - sampled, - ) - .expect("combined"); - let separate = ResourceSlot::separate_texture(Stage::Fragment, 0, pair).expect("separate"); - let st = b - .resource(separate, StorageClass::UniformConstant, image) - .expect("separate texture"); - let ss = b - .resource( - ResourceSlot::separate_sampler(Stage::Fragment, pair), - StorageClass::UniformConstant, - sampler_ty, - ) - .expect("separate sampler"); - let color = b - .plain_global(StorageClass::Private, vec4, None) - .expect("color"); - let void = b.ty(Type::Void).expect("void"); - let mut f = b.function(void).expect("main"); - let tv = f.module().global_value(t).expect("t"); - let tsv = f.module().global_value(ts).expect("ts"); - let stv = f.module().global_value(st).expect("st"); - let ssv = f.module().global_value(ss).expect("ss"); - let cv = f.module().global_value(color).expect("color"); - let zero = scalar(&mut f, u32_, 0); - let one = scalar(&mut f, u32_, 1); - let half = scalar(&mut f, f32_, 0.5f32.to_bits().into()); - let uv = f.composite_construct(vec2, &[half, half]).expect("uv"); - let texel = f.composite_construct(uvec2, &[zero, zero]).expect("texel"); - let at = |lod: Option| ImageOperands { - lod, - ..ImageOperands::default() - }; - // A level the module computes: the color's first lane, converted. - let computed_float = |f: &mut FunctionBuilder<'_>| { - let c = f.load(cv, MemAccess::default()).expect("color"); - f.composite_extract(c, &[0]).expect("lane") - }; - let value = match read { - Read::Implicit - | Read::ExplicitConstant - | Read::ExplicitComputed - | Read::Gradients - | Read::MinLod - | Read::Gather - | Read::QueryLod => { - let si = f.load(tsv, MemAccess::default()).expect("ts"); - let ops = match read { - Read::ExplicitConstant => { - let lod = scalar(&mut f, f32_, 1.5f32.to_bits().into()); - at(Some(lod)) - } - Read::ExplicitComputed => { - let lod = computed_float(&mut f); - at(Some(lod)) - } - Read::Gradients => ImageOperands { - grad: Some((uv, uv)), - ..ImageOperands::default() - }, - Read::MinLod => ImageOperands { - min_lod: Some(half), - ..ImageOperands::default() - }, - _ => ImageOperands::default(), - }; - match read { - Read::Gather => f.gather(si, uv, 0, &ops).expect("gather"), - Read::QueryLod => { - let lod = f.query_lod(si, uv).expect("query lod"); - let x = f.composite_extract(lod, &[0]).expect("x"); - f.composite_construct(vec4, &[x, x, x, x]).expect("splat") - } - _ => f.sample(si, uv, None, false, &ops).expect("sample"), - } - } - Read::SeparatePair => { - let img = f.load(stv, MemAccess::default()).expect("st"); - let s = f.load(ssv, MemAccess::default()).expect("ss"); - let si = f.sampled_image(img, s).expect("pair"); - f.sample(si, uv, None, false, &ImageOperands::default()) - .expect("sample") - } - Read::FetchConstant - | Read::FetchCompared - | Read::FetchContained - | Read::FetchComputed - | Read::FetchBase => { - let img = f.load(tv, MemAccess::default()).expect("t"); - let lod = match read { - Read::FetchConstant => Some(scalar(&mut f, u32_, 2)), - Read::FetchCompared => { - let levels = f.query(ImageQuery::Levels, img).expect("levels"); - let three = scalar(&mut f, u32_, 3); - let _ = f.binary(BinOp::ULessThan, three, levels).expect("in range"); - Some(scalar(&mut f, u32_, 2)) - } - Read::FetchContained => { - let levels = f.query(ImageQuery::Levels, img).expect("levels"); - let top = f.binary(BinOp::ISub, levels, one).expect("top"); - let _ = f.binary(BinOp::ULessThan, one, levels).expect("in range"); - Some(f.glsl(GlslOp::UMin, &[one, top]).expect("clamped")) - } - Read::FetchComputed => { - let x = computed_float(&mut f); - Some(f.convert(ConvOp::ConvertFToU, x, u32_).expect("level")) - } - _ => None, - }; - f.fetch(img, texel, &at(lod)).expect("fetch") - } - Read::LevelsElsewhere | Read::SizeConstant | Read::Size => { - let img = f.load(tv, MemAccess::default()).expect("t"); - let n = match read { - Read::LevelsElsewhere => { - let levels = f.query(ImageQuery::Levels, img).expect("levels"); - f.binary(BinOp::IAdd, levels, levels).expect("twice") - } - Read::SizeConstant => { - let three = scalar(&mut f, u32_, 3); - let size = f.query(ImageQuery::SizeLod(three), img).expect("size"); - f.composite_extract(size, &[0]).expect("width") - } - _ => { - let size = f.query(ImageQuery::Size, img).expect("size"); - f.composite_extract(size, &[0]).expect("width") - } - }; - let x = f.convert(ConvOp::ConvertUToF, n, f32_).expect("x"); - f.composite_construct(vec4, &[x, x, x, x]).expect("splat") - } - Read::Write => { - let img = f.load(tv, MemAccess::default()).expect("t"); - let c = f.load(cv, MemAccess::default()).expect("color"); - let mem = TexelMemory::Private { volatile: false }; - f.write(img, texel, c, &ImageOperands::default(), mem) - .expect("write"); - c - } - }; - f.store(cv, value, MemAccess::default()).expect("output"); - f.ret(None).expect("ret"); - let main = f.finish().expect("finish"); - b.entry(ExecModel::Fragment, main, Vec::new()) - .expect("entry"); - b.finalize().expect("finalize") -} - -/// Samples through `sampler` at the constant levels of detail `lods` (the lowest and the highest, -/// or none), and computed ones where `computed`. -fn sampled(sampler: SamplerRef, lods: Option<(f32, f32)>, computed: bool) -> SampledLevels { - SampledLevels { - sampler, - highest_lod_bits: lods.map(|(_, highest)| highest.to_bits()), - lowest_lod_bits: lods.map(|(lowest, _)| lowest.to_bits()), - computed, - } -} - -/// Each read states the levels it reaches: a sample by its sampler, a constant level of detail -/// or a computed one; a gather, a fetch and a size query the level they name, the lowering's -/// containment of a constant included, as the highest and (but a size query, which reads no -/// texel) the lowest read (a comparison of the level count raises the highest alone); and a fetch -/// or level at a computed level, a level count used otherwise, a level-of-detail query, a minimum -/// level of detail and a storage write any level. -#[test] -fn each_read_states_the_levels_it_reaches() { - let runtime = SamplerRef::Slot(0); - let constexpr = SamplerRef::Constexpr(CONSTEXPR); - let reads = |any: bool, named: Option, sampled: Vec| LevelReads { - slot: 0, - any, - named, - lowest_read: named, - sampled, - }; - for (read, want) in [ - ( - Read::Implicit, - reads(false, None, vec![sampled(runtime, None, true)]), - ), - ( - Read::ExplicitConstant, - reads(false, None, vec![sampled(runtime, Some((1.5, 1.5)), false)]), - ), - ( - Read::ExplicitComputed, - reads(false, None, vec![sampled(runtime, None, true)]), - ), - ( - Read::Gradients, - reads(false, None, vec![sampled(runtime, None, true)]), - ), - (Read::MinLod, reads(true, None, Vec::new())), - ( - Read::SeparatePair, - reads(false, None, vec![sampled(constexpr, None, true)]), - ), - (Read::Gather, reads(false, Some(0), Vec::new())), - (Read::FetchConstant, reads(false, Some(2), Vec::new())), - ( - Read::FetchCompared, - LevelReads { - named: Some(3), - ..reads(false, Some(2), Vec::new()) - }, - ), - (Read::FetchContained, reads(false, Some(1), Vec::new())), - (Read::FetchComputed, reads(true, None, Vec::new())), - (Read::FetchBase, reads(false, Some(0), Vec::new())), - (Read::LevelsElsewhere, reads(true, None, Vec::new())), - (Read::QueryLod, reads(true, None, Vec::new())), - ( - Read::SizeConstant, - LevelReads { - lowest_read: None, - ..reads(false, Some(3), Vec::new()) - }, - ), - (Read::Size, reads(false, None, Vec::new())), - (Read::Write, reads(true, None, Vec::new())), - ] { - let mut meter = Meter::new(&Budget::default()); - let found = level_reads(&module(read), &mut meter).expect("analysis"); - assert_eq!(meter.ledger(), 0, "{read:?}: every charge released"); - assert_eq!(found, vec![want], "{read:?}"); - } -} - -fn levels(min_lod: f32, max_lod: f32, linear: bool, finite_texels: bool) -> SamplerLevels { - SamplerLevels { - min_lod, - max_lod, - bias: 0.0, - linear, - finite_texels, - } -} - -/// A NaN among a sampler's constant levels of detail stays the highest whatever comes after it, -/// as `SampledLevels::level` reads a NaN at the sampler's `maxLod`: `f32::max` would drop it. -#[test] -fn constant_levels_of_detail_keep_a_nan() { - let mut found = super::Found::default(); - let s = SamplerRef::Slot(0); - for c in [2.0, f32::NAN, 1.0] { - found.sample(s, Some(c)); - } - let lods = &found.sampled[&s]; - assert!(lods.highest.is_some_and(f32::is_nan) && !lods.computed); - let levels = SampledLevels { - sampler: s, - highest_lod_bits: lods.highest.map(f32::to_bits), - lowest_lod_bits: lods.lowest.map(f32::to_bits), - computed: lods.computed, - }; - assert_eq!(levels.level(self::levels(0.0, 3.0, false, true)), Some(3)); -} - -/// Samples at several constant levels of detail keep the lowest apart from the highest, and a NaN -/// among them as the lowest too. -#[test] -fn constant_levels_of_detail_keep_their_lowest_and_a_nan_there() { - let mut found = super::Found::default(); - let s = SamplerRef::Slot(0); - for c in [2.0, 0.5, 3.0] { - found.sample(s, Some(c)); - } - let lods = &found.sampled[&s]; - assert_eq!((lods.lowest, lods.highest), (Some(0.5), Some(3.0))); - found.sample(s, Some(f32::NAN)); - found.sample(s, Some(1.0)); - let lods = &found.sampled[&s]; - assert!(lods.lowest.is_some_and(f32::is_nan) && lods.highest.is_some_and(f32::is_nan)); -} diff --git a/crates/metal2vulkan/src/spirv/requirements/mod.rs b/crates/metal2vulkan/src/spirv/requirements/mod.rs index ff9d30b98..c432a5670 100644 --- a/crates/metal2vulkan/src/spirv/requirements/mod.rs +++ b/crates/metal2vulkan/src/spirv/requirements/mod.rs @@ -88,11 +88,9 @@ fn independence_needed(widths: &BTreeSet) -> Independence { } } -mod level_reads; mod own_pixel; mod writes; -pub use level_reads::level_reads; pub use own_pixel::own_pixel_textures; pub use writes::writes_memory; diff --git a/crates/metal2vulkan/src/spirv/requirements/own_pixel.rs b/crates/metal2vulkan/src/spirv/requirements/own_pixel.rs index 1f269d4b1..13211f2cf 100644 --- a/crates/metal2vulkan/src/spirv/requirements/own_pixel.rs +++ b/crates/metal2vulkan/src/spirv/requirements/own_pixel.rs @@ -250,7 +250,7 @@ fn placed(m: &TypedModule, meter: &mut Meter) -> Result, Error> { } /// How an instruction uses a value that holds a slot's image. -pub(super) enum Use<'n> { +enum Use<'n> { /// It carries the image on, or queries its size, levels or samples: it reads no texel. NoTexel, /// `OpImageFetch` of it at `coord` with `ops`. @@ -264,7 +264,7 @@ pub(super) enum Use<'n> { } /// How `n` uses `v`, which holds a slot's image. -pub(super) fn use_of(n: &InstNode, v: Value) -> Use<'_> { +fn use_of(n: &InstNode, v: Value) -> Use<'_> { match &n.inst { // What carries the image on: its result is the image, or one sampled. inst if carried_on(inst) == Some(v) && n.result.is_some() => Use::NoTexel, @@ -282,7 +282,7 @@ pub(super) fn use_of(n: &InstNode, v: Value) -> Use<'_> { /// The value an instruction that carries an image on takes it from: a load, `OpSampledImage`, /// `OpImage`, or a copy; `None` for any other instruction. -pub(super) fn carried_on(inst: &Inst) -> Option { +fn carried_on(inst: &Inst) -> Option { match inst { Inst::Load { ptr: from, .. } | Inst::SampledImage { image: from, .. } @@ -296,7 +296,7 @@ pub(super) fn carried_on(inst: &Inst) -> Option { } /// Whether `v` is an image, a sampled image, or a pointer to one. -pub(super) fn holds_image(m: &TypedModule, v: Value) -> BResult { +fn holds_image(m: &TypedModule, v: Value) -> BResult { let ty = match m.types().get(m.value(v)?.ty)? { Type::Pointer { pointee, .. } => m.types().get(*pointee)?, ty => ty, diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 1f800d7bd..40474c0d6 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -2486,11 +2486,6 @@ field metal2vulkan::pipeline::ImageHandleClass.sampled_type pub sampled_type: Sa field metal2vulkan::pipeline::InputAttachmentUse.color_index pub color_index: u32 field metal2vulkan::pipeline::InputAttachmentUse.format_class pub format_class: SampledType field metal2vulkan::pipeline::InputAttachmentUse.input_attachment_index pub input_attachment_index: u32 -field metal2vulkan::pipeline::LevelReads.any pub any: bool -field metal2vulkan::pipeline::LevelReads.lowest_read pub lowest_read: Option -field metal2vulkan::pipeline::LevelReads.named pub named: Option -field metal2vulkan::pipeline::LevelReads.sampled pub sampled: Vec -field metal2vulkan::pipeline::LevelReads.slot pub slot: u32 field metal2vulkan::pipeline::LineBandState.primitive pub primitive: BandPrimitive field metal2vulkan::pipeline::LineBandState.push_offset pub push_offset: u32 field metal2vulkan::pipeline::LinkedFunction.constants pub constants: FunctionConstantValues @@ -2688,17 +2683,8 @@ field metal2vulkan::pipeline::ResourceSlot.kind pub kind: ResourceKind field metal2vulkan::pipeline::ResourceSlot.stage pub stage: Stage field metal2vulkan::pipeline::RuntimeDependency.fact pub fact: RuntimeFact field metal2vulkan::pipeline::RuntimeDependency.mechanism pub mechanism: Mechanism -field metal2vulkan::pipeline::SampledLevels.computed pub computed: bool -field metal2vulkan::pipeline::SampledLevels.highest_lod_bits pub highest_lod_bits: Option -field metal2vulkan::pipeline::SampledLevels.lowest_lod_bits pub lowest_lod_bits: Option -field metal2vulkan::pipeline::SampledLevels.sampler pub sampler: crate::pipeline::sym::SamplerRef field metal2vulkan::pipeline::SamplerArray.samplers pub samplers: Vec field metal2vulkan::pipeline::SamplerArray.slot pub slot: ResourceSlot -field metal2vulkan::pipeline::SamplerLevels.bias pub bias: f32 -field metal2vulkan::pipeline::SamplerLevels.finite_texels pub finite_texels: bool -field metal2vulkan::pipeline::SamplerLevels.linear pub linear: bool -field metal2vulkan::pipeline::SamplerLevels.max_lod pub max_lod: f32 -field metal2vulkan::pipeline::SamplerLevels.min_lod pub min_lod: f32 field metal2vulkan::pipeline::SamplerSlot.compare pub compare: bool field metal2vulkan::pipeline::SamplerSlot.coordinate_sensitive pub coordinate_sensitive: bool field metal2vulkan::pipeline::SlotRef.class pub class: SlotClass @@ -2729,7 +2715,6 @@ field metal2vulkan::pipeline::StageInputLayoutDescriptor.step_rate pub step_rate field metal2vulkan::pipeline::StageInputLayoutDescriptor.stride pub stride: Option field metal2vulkan::pipeline::StageModule.constant_blob pub constant_blob: Option> field metal2vulkan::pipeline::StageModule.entry_point pub entry_point: String -field metal2vulkan::pipeline::StageModule.level_reads pub level_reads: Vec field metal2vulkan::pipeline::StageModule.own_pixel_textures pub own_pixel_textures: Vec field metal2vulkan::pipeline::StageModule.precision_notes pub precision_notes: Vec field metal2vulkan::pipeline::StageModule.private_bytes pub private_bytes: u64 @@ -6669,12 +6654,6 @@ method metal2vulkan::pipeline::ResourceSlot::separate_texture pub fn separate_te method metal2vulkan::pipeline::ResourceSlot::separate_texture_of pub fn separate_texture_of(&self) -> Option<(u32, CombinedSampler)> method metal2vulkan::pipeline::RuntimeDependency::new pub fn new(fact: RuntimeFact, mechanism: Mechanism) -> RuntimeDependency method metal2vulkan::pipeline::RuntimeFact::name pub fn name(self) -> &'static str -method metal2vulkan::pipeline::SampledLevels::highest_lod pub fn highest_lod(&self) -> Option -method metal2vulkan::pipeline::SampledLevels::level pub fn level(&self, s: SamplerLevels) -> Option -method metal2vulkan::pipeline::SampledLevels::lowest pub fn lowest(&self, s: SamplerLevels) -> u32 -method metal2vulkan::pipeline::SampledLevels::lowest_lod pub fn lowest_lod(&self) -> Option -method metal2vulkan::pipeline::SamplerLevels::finite_texels pub fn finite_texels(format: vk::Format) -> bool -method metal2vulkan::pipeline::SamplerLevels::of pub fn of(desc: &vk::SamplerDesc, finite_texels: bool) -> SamplerLevels method metal2vulkan::pipeline::SamplerRef::constexpr_address_modes pub fn constexpr_address_modes(self) -> Option<[crate::metal::SamplerAddressMode; 3]> method metal2vulkan::pipeline::SpecTest::differ pub fn differ(key: SpecKey, mask: u32, bits: u32) -> SpecTest method metal2vulkan::pipeline::SpecTest::equal pub fn equal(key: SpecKey, mask: u32, bits: u32) -> SpecTest @@ -7130,7 +7109,6 @@ struct metal2vulkan::pipeline::GraphicsState #[cfg_attr(feature = "serde", deriv struct metal2vulkan::pipeline::ImageHandleClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct ImageHandleClass struct metal2vulkan::pipeline::IndirectDrawLayout #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct IndirectDrawLayout struct metal2vulkan::pipeline::InputAttachmentUse #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct InputAttachmentUse -struct metal2vulkan::pipeline::LevelReads #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, Default, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct LevelReads struct metal2vulkan::pipeline::LineBandState #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct LineBandState struct metal2vulkan::pipeline::LinkedFunction #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct LinkedFunction struct metal2vulkan::pipeline::LinkedFunctions #[derive(Clone, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub struct LinkedFunctions @@ -7150,9 +7128,7 @@ struct metal2vulkan::pipeline::RenderPipelineDescriptor #[derive(Clone, Debug, P struct metal2vulkan::pipeline::RenderPipelineKeys #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct RenderPipelineKeys struct metal2vulkan::pipeline::ResourceSlot #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ResourceSlot struct metal2vulkan::pipeline::RuntimeDependency #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct RuntimeDependency -struct metal2vulkan::pipeline::SampledLevels #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct SampledLevels struct metal2vulkan::pipeline::SamplerArray #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct SamplerArray -struct metal2vulkan::pipeline::SamplerLevels #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] pub struct SamplerLevels struct metal2vulkan::pipeline::SamplerSlot #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct SamplerSlot struct metal2vulkan::pipeline::SlotRef #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct SlotRef struct metal2vulkan::pipeline::SpecClause #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub struct SpecClause diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index e8af8657b..167125040 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -372,16 +372,13 @@ surface! { enum BufferKind N; struct BufferSlot N; struct CommandWrites E; - struct LevelReads N; enum NumberedSampler N; enum PatchDomain N; struct PipelineInterface N; struct PlacedField N; enum PushLoc N; struct PushPlacement N; - struct SampledLevels N; struct SamplerArray N; - struct SamplerLevels N; struct SamplerSlot N; enum SlotInterface N; struct TextureAccess N; diff --git a/docs/API.md b/docs/API.md index a48918b00..d2b056a80 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1416,17 +1416,6 @@ exception: on a device without maximal reconvergence its precision notes may add return before the body and SPIR-V reconverges only over all invocations (section 2.2.5; the note's entry in the precision-note catalogue). -### Levels a slot reads - -Each texture slot of a stage states the levels of its bound view its reads reach, counted from the -view's first level (`StageModule::level_reads`, one `LevelReads` a slot): whether some read may -reach any level (`any`: a level the function computes, a level-count query used beyond the -containment of a constant level, a level-of-detail query, a sample through no sampler or with a -minimum level of detail, a storage access, or a use the analysis does not follow), the highest -constant level a fetch, size query or gather names (`named`) and the lowest whose texels a fetch -or gather reads (`lowest_read`), and its samples by the sampler each reads through (`sampled`, with the highest -and the lowest constant level of detail). A sample's level is its sampler's to bound. - ### Indirect command buffers An indirect command buffer's commands are records in ordinary buffer storage diff --git a/docs/HOWTO.md b/docs/HOWTO.md index 72f3b3ee3..2fb3d66a1 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -35,8 +35,7 @@ walks the flow in the order a consumer meets it: [a render pipeline](API.md#4-a-render-pipeline), under a `Budget`. 4. [The interface](API.md#5-the-interface): the layout, what each slot binds, what a dispatch or draw needs. -5. [At bind time](API.md#6-at-bind-time): a dispatch's regions, the levels a slot reads, and - indirect command buffers. +5. [At bind time](API.md#6-at-bind-time): a dispatch's regions and indirect command buffers. Every `air.simd_*` operation keeps Metal's 32-lane simdgroup; there is no option to use the driver's subgroup width instead.