diff --git a/crates/metal2vulkan-runtime/src/counters.rs b/crates/metal2vulkan-runtime/src/counters.rs index ea8d23f24..ebfb83ac5 100644 --- a/crates/metal2vulkan-runtime/src/counters.rs +++ b/crates/metal2vulkan-runtime/src/counters.rs @@ -503,6 +503,10 @@ pub(crate) enum Gauge { Kernels, /// [`Gauges::kernel_variants`]. KernelVariants, + /// [`Gauges::word_pipelines`]. + WordPipelines, + /// [`Gauges::word_texture_buffers`]. + WordTextureBuffers, /// [`Gauges::kernel_entries`]. KernelEntries, /// [`Gauges::render_contents`]. @@ -815,6 +819,8 @@ struct Atomics { first_use_sites: [[AtomicU64; 3]; FIRST_USE_SITES], /// The makes ahead of a dispatch: their count and total nanoseconds. made_ahead: [AtomicU64; 2], + /// The words twins made: their count and total nanoseconds. + word_pipelines_made: [AtomicU64; 2], /// The pipelines `finish_pipeline` calls made: their count and total nanoseconds. finished: [AtomicU64; 2], /// [`Metrics::failed_finishes`]. @@ -954,6 +960,8 @@ struct Atomics { pipelines: AtomicU64, kernels: AtomicU64, kernel_variants: AtomicU64, + word_pipelines: AtomicU64, + word_texture_buffers: AtomicU64, kernel_entries: AtomicU64, render_contents: AtomicU64, attachment_views: AtomicU64, @@ -1189,6 +1197,14 @@ impl Counters { total.fetch_add(nanos, Relaxed); } + /// One more words twin made, for `nanos` nanoseconds of its make + /// ([`Metrics::word_pipelines_created`]). + pub(crate) fn word_pipeline(&self, nanos: u64) { + let [count, total] = &self.atomics.word_pipelines_made; + count.fetch_add(1, Relaxed); + total.fetch_add(nanos, Relaxed); + } + /// One more pipeline a `finish_pipeline` call made, for `nanos` nanoseconds /// ([`Metrics::finished_pipelines`]). pub(crate) fn finished(&self, nanos: u64) { @@ -1879,6 +1895,11 @@ impl Counters { .is_ok() } + /// The live resources of `gauge`'s kind. + pub(crate) fn live(&self, gauge: Gauge) -> u64 { + self.gauge(gauge).load(Relaxed) + } + /// One fewer live resource of `gauge`'s kind. pub(crate) fn fall(&self, gauge: Gauge) { self.gauge(gauge).fetch_sub(1, Relaxed); @@ -1912,6 +1933,8 @@ impl Counters { Gauge::Pipelines => &a.pipelines, Gauge::Kernels => &a.kernels, Gauge::KernelVariants => &a.kernel_variants, + Gauge::WordPipelines => &a.word_pipelines, + Gauge::WordTextureBuffers => &a.word_texture_buffers, Gauge::KernelEntries => &a.kernel_entries, Gauge::RenderContents => &a.render_contents, Gauge::AttachmentViews => &a.attachment_views, @@ -1995,6 +2018,7 @@ impl Counters { ] .map(first_use); let made_ahead = (a.made_ahead.each_ref()).map(|n| n.load(Relaxed)); + let word_pipelines = (a.word_pipelines_made.each_ref()).map(|n| n.load(Relaxed)); let finished = (a.finished.each_ref()).map(|n| n.load(Relaxed)); let part = |part: Part| { let [count, bytes, total, _, over_1, over_5, over_20] = &a.parts[part as usize]; @@ -2132,6 +2156,8 @@ impl Counters { first_use_unfinished_wait_max_nanos: unfinished[2], made_ahead_variants: made_ahead[0], made_ahead_variant_nanos: made_ahead[1], + word_pipelines_created: word_pipelines[0], + word_pipeline_nanos: word_pipelines[1], finished_pipelines: finished[0], finished_pipeline_nanos: finished[1], failed_finishes: a.failed_finishes.load(Relaxed), @@ -2335,6 +2361,8 @@ impl Counters { pipelines: a.pipelines.load(Relaxed), kernels: a.kernels.load(Relaxed), kernel_variants: a.kernel_variants.load(Relaxed), + word_pipelines: a.word_pipelines.load(Relaxed), + word_texture_buffers: a.word_texture_buffers.load(Relaxed), kernel_entries: a.kernel_entries.load(Relaxed), render_contents: a.render_contents.load(Relaxed), attachment_views: a.attachment_views.load(Relaxed), @@ -2808,6 +2836,17 @@ pub struct Metrics { pub made_ahead_variants: u64, /// The nanoseconds of the [`made_ahead_variants`](Self::made_ahead_variants), in total. pub made_ahead_variant_nanos: u64, + /// Words twins made ([`Gauges::word_pipelines`]): the second `VkPipeline` of each make of a + /// module that declares `SpecKey::TexelBufferWords`, also counted in + /// [`pipelines_created`](Self::pipelines_created). Only a device that holds some format's + /// texture buffer as words makes them. + pub word_pipelines_created: u64, + /// The nanoseconds of [`host_time`](crate::host_time) the + /// [`word_pipelines_created`](Self::word_pipelines_created) took, in total, each its + /// specialization and its driver's create: also counted in + /// [`pipeline_creation_nanos`](Self::pipeline_creation_nanos) and in the time of the make + /// that made it. + pub word_pipeline_nanos: u64, /// The states' main pipelines that `finish_pipeline` calls made on their callers' threads, /// after the state's creation answered /// ([`ComputePipelineState::finish_pipeline`](crate::ComputePipelineState::finish_pipeline), @@ -3765,6 +3804,16 @@ pub struct Gauges { /// past them, which it keeps for later dispatches, and those past them that command buffers /// not yet retired held at its last make. pub kernel_variants: u64, + /// Words twins: `VkPipeline`s of modules that declare `SpecKey::TexelBufferWords`, + /// specialized with it true, each made in the same make as its plain pipeline, which a draw or + /// dispatch that binds a texture buffer held as words runs; also counted in + /// [`kernel_variants`](Self::kernel_variants)' kernels' variants and in a render content's + /// pipelines. Only a device that holds some format's texture buffer as words makes them. + pub word_pipelines: u64, + /// Texture buffers held as words (`metal2vulkan::metal::format::texel_buffer_form`): while + /// any lives, a draw or dispatch of a stage that reaches a texture buffer through a handle runs + /// its words twin ([`word_pipelines`](Self::word_pipelines)). + pub word_texture_buffers: u64, /// Entries of the device's map of compiled contents, compute and render, which holds at most /// 1,024 and forgets the least recently used past them. pub kernel_entries: u64, diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 55468d55f..edd45f5d3 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -355,6 +355,8 @@ struct Last { content: u64, module: Module, local: [u32; 3], + /// It is the module's words twin (`pipeline::Twins`). + words: bool, pipeline: vk::Pipeline, } @@ -1310,8 +1312,18 @@ impl ComputeCommandEncoder { if direct.is_some_and(|(_, groups, _)| groups.contains(&0)) { return Ok(()); } + // The module's words twin where a texture buffer held as words is bound where it reaches + // one. + let textures = &self.textures; + let words = kernel.binds_words( + core, + |slot| matches!(textures.get(slot as usize), Some(Some(t)) if t.held_as_words()), + ); let vk_pipeline = match self.last { - Some(last) if (last.content, last.module, last.local) == (inner.id, module, local) => { + Some(last) + if (last.content, last.module, last.local, last.words) + == (inner.id, module, local, words) => + { last.pipeline } _ => { @@ -1325,7 +1337,7 @@ impl ComputeCommandEncoder { // A variant past the kernel's cells is held by the command buffer from its first // dispatch, so no make evicts it while the command buffer is not retired. let site = inner.first_use(variant); - kernel.pipeline(core, variant, site, |listed| { + kernel.pipeline(core, (variant, words), site, |listed| { recording(&mut self.building).hold_variant(listed) })? } @@ -1334,6 +1346,7 @@ impl ComputeCommandEncoder { content: inner.id, module, local, + words, pipeline: vk_pipeline, }); let interface = &kernel.interface; diff --git a/crates/metal2vulkan-runtime/src/pipeline.rs b/crates/metal2vulkan-runtime/src/pipeline.rs index 2b53a6cb2..3f849a6c4 100644 --- a/crates/metal2vulkan-runtime/src/pipeline.rs +++ b/crates/metal2vulkan-runtime/src/pipeline.rs @@ -78,7 +78,7 @@ use metal2vulkan::cache::Hash256; use metal2vulkan::device::{VkLimit, KERNEL_BUFFER_BINDINGS}; use metal2vulkan::error::{Capability, Error as TranslationError, Feature, Needs, Unsupported}; use metal2vulkan::library::{CompiledFunction, FunctionCompileKey}; -use metal2vulkan::metal::{BindingAccess, BindingType, TextureUsage}; +use metal2vulkan::metal::{BindingAccess, BindingType, TextureType, TextureUsage}; use metal2vulkan::pipeline::{ arena_bytes, threadgroup_constants, AccessSet, BindingSource, BufferKind, CombinedSampler, ComputePipeline, ComputePipelineDescriptor, DescriptorSetLayout, FunctionDescriptor, @@ -563,7 +563,7 @@ const LISTED_VARIANTS: usize = 56; /// made, so makes of different variants run at once and one variant is made once at a time. #[derive(Default)] struct Variants { - cells: [OnceLock<(Variant, vk::Pipeline)>; VARIANT_CELLS], + cells: [OnceLock<(Variant, Twins)>; VARIANT_CELLS], more: Mutex, /// Signalled when a make ends, made or failed: a dispatch waiting for its pending variant /// looks again. @@ -593,7 +593,27 @@ struct Making { /// idle, and stays idle while the lock is held. pub(crate) struct Listed { variant: Variant, - pipeline: vk::Pipeline, + pipeline: Twins, +} + +/// A variant's `VkPipeline`s: its module's specialized with `SpecKey::TexelBufferWords` false, +/// and, where the module declares that constant ([`Interface::words`]), its words twin, the same +/// module specialized with it true, made in the same make; null where the module declares none. +#[derive(Clone, Copy)] +pub(crate) struct Twins { + plain: vk::Pipeline, + words: vk::Pipeline, +} + +impl Twins { + /// The pipeline a dispatch that binds a texture buffer held as words where the kernel reaches + /// it runs (`words`), or the plain one. + fn of(self, words: bool) -> vk::Pipeline { + match words && self.words != vk::Pipeline::null() { + true => self.words, + false => self.plain, + } + } } impl crate::kept::Handle for Arc { @@ -624,7 +644,7 @@ impl Variants { /// The pipeline of the variant of `size`, threadgroup memory `lengths` (the imageblock's size /// with them) and `tiles`, where its cell holds it, read with no lock; `more`, the list past /// the cells, where they are all full. - fn in_cells(&self, (size, lengths, tiles): Key<'_>) -> Result { + fn in_cells(&self, (size, lengths, tiles): Key<'_>) -> Result { for cell in &self.cells { match cell.get() { Some((variant, pipeline)) if variant.is(size, lengths, tiles) => { @@ -639,7 +659,7 @@ impl Variants { } /// The pipeline of the variant `key` where it is made, read under the lock `more` is. - fn made(&self, more: &More, key: Key<'_>) -> Option { + fn made(&self, more: &More, key: Key<'_>) -> Option { match self.in_cells(key) { Ok(pipeline) => Some(pipeline), Err(false) => None, @@ -654,7 +674,7 @@ impl Variants { more: &mut More, key: Key<'_>, hold: &mut impl FnMut(&Arc), - ) -> Option { + ) -> Option { match self.in_cells(key) { Ok(pipeline) => Some(pipeline), Err(false) => None, @@ -676,9 +696,12 @@ impl Variants { core: &Core, more: &'m mut More, variant: Variant, - pipeline: vk::Pipeline, + pipeline: Twins, ) -> Option<&'m Arc> { core.counters.rise(Gauge::KernelVariants); + if pipeline.words != vk::Pipeline::null() { + core.counters.rise(Gauge::WordPipelines); + } // Only a making fills a cell, under the lock: the empty one stays empty until this. if let Some(cell) = self.cells.iter().find(|cell| cell.get().is_none()) { let _ = cell.set((variant, pipeline)); @@ -701,7 +724,7 @@ impl Variants { } /// Every pipeline, taken out to give back. - fn drain(&mut self) -> impl Iterator + '_ { + fn drain(&mut self) -> impl Iterator + '_ { let more = self.more.get_mut().unwrap_or_else(PoisonError::into_inner); (self.cells.iter_mut()) .filter_map(|cell| cell.take().map(|(_, pipeline)| pipeline)) @@ -709,10 +732,14 @@ impl Variants { } } -/// Gives a kernel's variant's `pipeline` to the reaper, no longer counted live. -fn give_back(core: &Core, pipeline: vk::Pipeline) { +/// Gives a kernel's variant's `pipeline`s to the reaper, no longer counted live. +fn give_back(core: &Core, pipeline: Twins) { core.counters.fall(Gauge::KernelVariants); - core.reaper.give(Job::Free(Free::Pipeline(pipeline))); + core.reaper.give(Job::Free(Free::Pipeline(pipeline.plain))); + if pipeline.words != vk::Pipeline::null() { + core.counters.fall(Gauge::WordPipelines); + core.reaper.give(Job::Free(Free::Pipeline(pipeline.words))); + } } /// A variant entered as pending under [`Variants`]'s lock, for the thread that makes it, started @@ -726,7 +753,7 @@ struct Pending<'a, H: FnMut(&Arc)> { variant: DispatchVariant, start: VariantStart, began: u64, - made: Option<(Variant, vk::Pipeline)>, + made: Option<(Variant, Twins)>, hold: &'a mut H, } @@ -826,6 +853,9 @@ pub(crate) struct Interface { pub(crate) imageblock: Option, /// The kernel's specialization constants: each one's id and what sets it. pub(crate) constants: Vec<(u32, Constant)>, + /// Where the kernel declares `SpecKey::TexelBufferWords`, what a dispatch reads to pick its + /// words twin ([`Kernel::binds_words`]). + pub(crate) words: Option, /// The index of each threadgroup memory argument the kernel takes, in the order of /// [`Variant::lengths`]' words. pub(crate) threadgroups: Vec, @@ -890,6 +920,16 @@ impl Memory { } } +/// The texture buffers of a kernel that declares `SpecKey::TexelBufferWords` +/// ([`Interface::words`]). +pub(crate) struct WordReach { + /// Its texture buffer slots. + pub(crate) slots: Vec, + /// It reaches a texture buffer through a handle (an argument buffer's texture), which no slot + /// names. + pub(crate) handles: bool, +} + /// What sets a specialization constant. #[derive(Clone, Copy)] pub(crate) enum Constant { @@ -907,6 +947,8 @@ pub(crate) enum Constant { /// tile; 0 for every other launch, whose region states the pipeline's own threadgroup size, /// so the kernel takes `L` from its workgroup size and reads no decode. MultiRegion, + /// `TexelBufferWords`: 1 for a variant's words twin ([`Twins`]), 0 for its plain pipeline. + TexelWords, } /// A parameter and where it goes. @@ -1851,6 +1893,7 @@ pub(crate) fn interface( let mut usages = Vec::new(); let mut storage_reads = Vec::new(); let mut formatless = Vec::new(); + let mut texel_buffers = Vec::new(); for (slot, used) in &translated.slots { match (slot.stage, slot.class, used) { (Stage::Kernel, SlotClass::Buffer, SlotInterface::Buffer(buffer)) @@ -1871,6 +1914,9 @@ pub(crate) fn interface( if texture.storage && !texture.declared_format { formatless.push(slot.index); } + if texture.texture_type == TextureType::TextureBuffer { + texel_buffers.push(slot.index); + } } (Stage::Kernel, SlotClass::Sampler, SlotInterface::Sampler(_)) => {} _ => return Err(KernelInputKind::Slot), @@ -2029,6 +2075,7 @@ pub(crate) fn interface( return Err(KernelInputKind::Specialization); } let mut constants = Vec::new(); + let mut words = None; for constant in &stage.specialization.constants { if constant.size != 4 { return Err(KernelInputKind::Specialization); @@ -2050,6 +2097,18 @@ pub(crate) fn interface( SpecKey::StageInReach => continue, SpecKey::ImageblockWidth => Constant::Imageblock(0), SpecKey::ImageblockHeight => Constant::Imageblock(1), + // Whether the dispatch binds a texture buffer held as words where the kernel reaches + // it: each variant's words twin, made with its plain pipeline ([`Twins`]). + SpecKey::TexelBufferWords { + stage: Stage::Kernel, + handles, + } => { + words = Some(WordReach { + slots: texel_buffers.clone(), + handles, + }); + Constant::TexelWords + } _ => return Err(KernelInputKind::Specialization), }; constants.push((constant.id, set)); @@ -2102,6 +2161,7 @@ pub(crate) fn interface( imageblock, fields, constants, + words, threadgroups, max_total_threads, metal_max_total_threads, @@ -2840,18 +2900,19 @@ impl Kernel { /// that make, also a first-use wait counted in that make's [`VariantMake::waits`], and makes /// it itself where that one failed. One of the kernel's first [`VARIANT_CELLS`] variants is /// found with no lock and no hold; one past them `hold` takes for the dispatch's command - /// buffer, under the kernel's lock. + /// buffer, under the kernel's lock. The variant's words twin where `words` + /// ([`Kernel::binds_words`]), made with the plain one. pub(crate) fn pipeline( &self, core: &Core, - variant: DispatchVariant, + (variant, words): (DispatchVariant, bool), site: FirstUse, mut hold: impl FnMut(&Arc), ) -> Result { let variants = &self.variants; let key = variant.key(); if let Ok(pipeline) = variants.in_cells(key) { - return Ok(pipeline); + return Ok(pipeline.of(words)); } let began = host_time(); let waited = @@ -2863,7 +2924,7 @@ impl Kernel { if waits { waited(core); } - return Ok(pipeline); + return Ok(pipeline.of(words)); } let Some(at) = more.pending(key) else { break; @@ -2882,7 +2943,7 @@ impl Kernel { let start = VariantStart::FirstUse; let pipeline = self.make_pending(core, more, variant, start, Some(began), &mut hold)?; waited(core); - Ok(pipeline) + Ok(pipeline.of(words)) } /// Whether the variant `key` is made: read from its cell with no lock, and past the cells under @@ -2932,7 +2993,7 @@ impl Kernel { start: VariantStart, wait: Option, hold: &mut impl FnMut(&Arc), - ) -> Result { + ) -> Result { more.pending.push(Making { variant, waits: u32::from(wait.is_some()), @@ -2954,14 +3015,47 @@ impl Kernel { lengths: *lengths, tiles, }; - let pipeline = self.make(core, &made)?; + let plain = self.make(core, &made, false)?; + // The words twin, in the same make: a dispatch that binds a texture buffer held as words + // makes no pipeline its plain twin would not. + let words = match self.interface.words { + Some(_) => { + let began = host_time(); + match self.make(core, &made, true) { + Ok(words) => { + core.counters + .word_pipeline(host_time().saturating_sub(began)); + words + } + Err(error) => { + core.reaper.give(Job::Free(Free::Pipeline(plain))); + return Err(error); + } + } + } + None => vk::Pipeline::null(), + }; + let pipeline = Twins { plain, words }; pending.made = Some((made, pipeline)); Ok(pipeline) } + /// Whether a dispatch runs the words twin, `held` answering whether a texture slot holds a + /// texture buffer held as words: where the kernel declares `SpecKey::TexelBufferWords` + /// ([`Interface::words`]), such a texture at a texture buffer slot it declares, or, where it + /// reaches a texture buffer through a handle, a live texture buffer held as words on the + /// device ([`Gauges::word_texture_buffers`](crate::Gauges::word_texture_buffers)). + pub(crate) fn binds_words(&self, core: &Core, held: impl Fn(u32) -> bool) -> bool { + let Some(reach) = &self.interface.words else { + return false; + }; + reach.slots.iter().any(|&slot| held(slot)) + || reach.handles && core.counters.live(Gauge::WordTextureBuffers) > 0 + } + /// The ids of the kernel's specialization constants and their values for `variant`, 4 bytes - /// each, in order. - fn specialization(&self, variant: &Variant) -> (Vec, Vec) { + /// each, in order: its words twin's where `words`. + fn specialization(&self, variant: &Variant, words: bool) -> (Vec, Vec) { let constants = &self.interface.constants; let ids: Vec = constants.iter().map(|&(id, _)| id).collect(); let threadgroup = threadgroup_constants(variant.size); @@ -2975,6 +3069,7 @@ impl Kernel { Constant::ThreadgroupLength(at) => variant.lengths.as_slice()[at], Constant::Imageblock(axis) => variant.lengths.imageblock[axis], Constant::MultiRegion => u32::from(variant.tiles), + Constant::TexelWords => u32::from(words), }) .flat_map(u32::to_ne_bytes) .collect(); @@ -3001,12 +3096,13 @@ impl Kernel { /// For the device tests: the words a create of `variant` makes its shader module of. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn driver_words(&self, variant: &Variant) -> Result, Error> { - let (ids, data) = self.specialization(variant); + let (ids, data) = self.specialization(variant, false); self.create(&ids, &data).specialize(self.code.words()) } - fn make(&self, core: &Core, variant: &Variant) -> Result { - let (ids, data) = self.specialization(variant); + /// The `VkPipeline` of `variant`, its words twin's where `words`. + fn make(&self, core: &Core, variant: &Variant, words: bool) -> Result { + let (ids, data) = self.specialization(variant, words); let stage = self.create(&ids, &data); let words = stage.specialize(self.code.words())?; // The translator pins a size only for a stage the device lists in diff --git a/crates/metal2vulkan-runtime/src/render.rs b/crates/metal2vulkan-runtime/src/render.rs index eb03ea546..d52bc2a9b 100644 --- a/crates/metal2vulkan-runtime/src/render.rs +++ b/crates/metal2vulkan-runtime/src/render.rs @@ -266,6 +266,10 @@ pub(crate) struct Draws { pub(crate) buffers: Vec<(usize, u32, Access)>, /// Each texture slot a function uses, likewise. pub(crate) textures: Vec<(usize, u32, Access)>, + /// Each texture buffer slot a function uses, with its function: where a texture buffer held as + /// words is bound at one, a draw of a content with a words twin runs it + /// ([`RenderCompiled::binds_words`]). + pub(crate) texel_buffers: Vec<(usize, u32)>, /// Each texture slot a function uses, with its function and the usage Metal asks of the /// texture bound there (`crate::pipeline::slot_usage`). pub(crate) usages: Vec<(usize, u32, TextureUsage)>, @@ -395,19 +399,14 @@ pub(crate) struct RenderCompiled { /// makes a pipeline for the loop; a draw that reads none is valid with it. A content that can /// read no texture never reads an attachment other than as one. pub(crate) flags: vk::PipelineCreateFlags, - /// The content's main `VkPipeline`: the triangle class's, or a post-tessellation vertex - /// function's patch class's, its only class, at the default [`Raster`]. - primary: Main, - /// The line or the point class's `VkPipeline` at the default raster state, by its list - /// topology, a main one too, where the descriptor names that class - /// (`inputPrimitiveTopology`). - named: Option<(vk::PrimitiveTopology, Main)>, - /// The content's other `VkPipeline`s, each by its class's list topology and its raster state, - /// each made by the first draw that takes it: the line and the point class's at the default - /// raster state where the descriptor names neither, and those under other raster states. At - /// most 15: the triangle or patch class's seven other raster states, and four of each other - /// class. - later: Mutex>, + /// The content's `VkPipeline`s of [`stages`](Self::stages). + cells: Cells, + /// The line or the point class's list topology, where the descriptor names that class + /// (`inputPrimitiveTopology`): its `VkPipeline` at the default raster state is a main one too + /// ([`Cells::named`]). + named: Option, + /// The words twin, where a stage declares `SpecKey::TexelBufferWords`. + words: Option>, /// Whether a draw of points rasterizes them: the vertex function writes `[[point_size]]`, or /// the descriptor names the point class, under which Metal draws a point of a function that /// writes no size 1 pixel wide (the module writes `PointSize` 1.0). Under any other class @@ -465,8 +464,47 @@ pub(crate) struct Raster { pub(crate) positions: bool, } -/// One of a content's main `VkPipeline`s ([`RenderCompiled::primary`], -/// [`RenderCompiled::named`]): made by a state's [`RenderPipelineState::finish_pipeline`] call, +/// A render content's `VkPipeline`s of one set of stage modules: its plain modules' or its words +/// twin's ([`RenderWords`]). +#[derive(Default)] +struct Cells { + /// The main `VkPipeline`: the triangle class's, or a post-tessellation vertex function's patch + /// class's, its only class, at the default [`Raster`]. + primary: Main, + /// The named class's `VkPipeline` at the default raster state, a main one too, where the + /// descriptor names the line or the point class ([`RenderCompiled::named`]). + named: Main, + /// The other `VkPipeline`s, each by its class's list topology and its raster state, each made + /// by the first draw that takes it: the line and the point class's at the default raster state + /// where the descriptor names neither, and those under other raster states. At most 15: the + /// triangle or patch class's seven other raster states, and four of each other class. + later: Mutex>, +} + +impl Cells { + /// Every `VkPipeline` made: a main one no call or draw made, or whose make failed, is none. + fn made(&mut self) -> Vec { + let later = self.later.get_mut().unwrap_or_else(|e| e.into_inner()); + (self.primary.get().into_iter()) + .chain(self.named.get()) + .chain(later.iter().map(|&(.., pipeline)| pipeline)) + .collect() + } +} + +/// A render content's words twin: each stage's module specialized with +/// `SpecKey::TexelBufferWords` true, whose `VkPipeline`s a draw that binds a texture buffer held +/// as words where a function reaches it runs, each made in the same make as the plain one of its +/// class and raster state, counted ([`Gauges::word_pipelines`](crate::Gauges::word_pipelines)). +struct RenderWords { + stages: Vec, + cells: Cells, + /// A stage reaches a texture buffer through a handle (an argument buffer's texture), which no + /// slot names. + handles: bool, +} + +/// One of a content's main `VkPipeline`s ([`Cells::primary`], [`Cells::named`]): made by a state's [`RenderPipelineState::finish_pipeline`] call, /// or by the first draw that needs it, which waits for a make in flight. It is made by one thread /// at a time; a make that failed keeps nothing, and the next call or draw makes it again. #[derive(Default)] @@ -936,6 +974,7 @@ fn draws( } let mut buffers = Vec::new(); let mut textures = Vec::new(); + let mut texel_buffers = Vec::new(); let mut usages = Vec::new(); let mut storage_reads = Vec::new(); let mut formatless = Vec::new(); @@ -950,6 +989,9 @@ fn draws( (SlotClass::Texture, SlotInterface::Texture(texture)) => { textures.push((at, slot.index, texture_access(texture.access))); usages.push((at, slot.index, slot_usage(texture))); + if texture.texture_type == metal2vulkan::metal::TextureType::TextureBuffer { + texel_buffers.push((at, slot.index)); + } if texture.storage && texture.access.read { storage_reads.push((at, slot.index)); } @@ -1166,6 +1208,7 @@ fn draws( let draws = Draws { buffers, textures, + texel_buffers, usages, storage_reads, formatless, @@ -1472,61 +1515,46 @@ impl RenderCompiled { let samples = lowered.raster_sample_count; let mut stages = Vec::new(); let mut notes: Vec<_> = constexpr_notes(translator.profile(), &constexprs).collect(); + // Where a stage declares `SpecKey::TexelBufferWords`, whether one reaches a texture buffer + // through a handle: the content's words twin is made beside it. + let mut handles = None; for stage in &pipeline.stages { - let mut values = Vec::new(); for constant in &stage.specialization.constants { - let value: u32 = match (constant.key, constant.size) { - (SpecKey::SampleCount, 4) => samples, - (SpecKey::AmplificationCount, 4) => 1, - _ => { - release(core, &stages); - return Err(Error::Unsupported(Gap::RenderPipeline { - kind: RenderPipelineKind::Specialization, - })); - } - }; - values.push((constant.id, u64::from(value))); + if let SpecKey::TexelBufferWords { handles: h, .. } = constant.key { + handles = Some(handles.unwrap_or(false) | h); + } } - // The stage's constants fixed at the content's values, so the driver is handed no - // specialization, as a kernel's module is. - let words = match specialize(&stage.spirv, &values) { - Ok(words) => words, + match stage_module(core, stage, samples, false) { + Ok(module) => stages.push(module), Err(error) => { release(core, &stages); - return Err(Error::translation(error)); + return Err(error); } - }; - // The translator's entry points hold no NUL; one that did would name no entry point. - let Ok(entry) = CString::new(stage.entry_point.as_str()) else { - release(core, &stages); - return Err(Error::Unsupported(Gap::RenderPipeline { - kind: RenderPipelineKind::SynthesizedStages, - })); - }; - let flags = vk::PipelineShaderStageCreateFlags::from_raw(stage.stage_flags.as_raw()); - let kind = vk::ShaderStageFlags::from_raw(stage.stage.as_raw()); - let info = vk::ShaderModuleCreateInfo::default().code(&words); - // SAFETY: the words are the translator's SPIR-V with its constants fixed, valid where - // the translator's are, for the features device creation enabled. - let module = match unsafe { core.device.create_shader_module(&info, None) } { - Ok(module) => module, - Err(result) => { - release(core, &stages); - return Err(Error::Vulkan { - call: "vkCreateShaderModule", - result, - }); - } - }; - stages.push(Module { - module, - entry, - stage: kind, - flags, - subgroup_size: stage.required_subgroup_size, - }); + } notes.extend(stage.precision_notes.iter().copied()); } + // The words twin's modules: each stage's specialized with the constant true. + let words = match handles { + Some(handles) => { + let mut twin = Vec::new(); + for stage in &pipeline.stages { + match stage_module(core, stage, samples, true) { + Ok(module) => twin.push(module), + Err(error) => { + release(core, &stages); + release(core, &twin); + return Err(error); + } + } + } + Some(Box::new(RenderWords { + stages: twin, + cells: Cells::default(), + handles, + })) + } + None => None, + }; notes.sort_unstable(); notes.dedup(); core.counters.rise(Gauge::RenderContents); @@ -1549,9 +1577,9 @@ impl RenderCompiled { true => vk::PipelineCreateFlags::COLOR_ATTACHMENT_FEEDBACK_LOOP_EXT, false => vk::PipelineCreateFlags::empty(), }, - primary: Main::default(), - named: named.map(|list| (list, Main::default())), - later: Mutex::new(Vec::new()), + cells: Cells::default(), + named, + words, rasterizes_points: pipeline.graphics.writes_point_size || lowered.input_primitive_topology == PrimitiveTopologyClass::Point, interpolates_at_sample: pipeline.graphics.interpolates_at_sample, @@ -1575,14 +1603,15 @@ impl RenderCompiled { /// named class's, each counted as made, both tried where the first fails. Err: the first /// make's error, the call counted as failed. fn finish(&self) -> Result<(), Error> { + let cells = &self.cells; let primary = ( self.class(vk::PrimitiveTopology::TRIANGLE_LIST), - &self.primary, + &cells.primary, ); - let named = (self.named.as_ref()).map(|(list, named)| (*list, named)); + let named = self.named.map(|list| (list, &cells.named)); let mut failed = None; for (class, main) in std::iter::once(primary).chain(named) { - match main.make_ahead(|| self.make(class, Raster::default())) { + match main.make_ahead(|| self.make_twinned(class, Raster::default())) { Ok(Some(nanos)) => self.core.counters.finished(nanos), Ok(None) => {} Err(error) => failed = failed.or(Some(error)), @@ -1636,6 +1665,7 @@ impl RenderCompiled { &self, topology: vk::PrimitiveTopology, raster: Raster, + words: bool, ) -> Result { use vk::PrimitiveTopology as T; if raster.positions && self.interpolates_at_sample { @@ -1650,28 +1680,62 @@ impl RenderCompiled { lines: raster.lines && polygons, positions: raster.positions, }; + let plain = self.found(&self.cells, (class, raster), || { + self.make_twinned(class, raster) + })?; + match (words, &self.words) { + (true, Some(twin)) => self.found(&twin.cells, (class, raster), || { + self.make_twin(twin, class, raster) + }), + _ => Ok(plain), + } + } + + /// Whether a draw with `tables` bound runs the words twin: where a stage declares + /// `SpecKey::TexelBufferWords`, a texture buffer held as words bound at a texture buffer slot + /// a function declares, or, where one reaches a texture buffer through a handle, a live texture + /// buffer held as words on the device + /// ([`Gauges::word_texture_buffers`](crate::Gauges::word_texture_buffers)). `held` answers + /// whether a function's slot holds such a texture. + pub(crate) fn binds_words(&self, held: impl Fn(usize, u32) -> bool) -> bool { + let Some(twin) = &self.words else { + return false; + }; + (self.draws.texel_buffers.iter()).any(|&(table, slot)| held(table, slot)) + || twin.handles && self.core.counters.live(Gauge::WordTextureBuffers) > 0 + } + + /// The `VkPipeline` of `cells` for `class` under `raster`, made by `make` where it is not: + /// a main one by [`Main::pipeline`], another by the first draw that takes it, a first-use + /// wait, as [`RenderCompiled::pipeline`] counts them. + fn found( + &self, + cells: &Cells, + (class, raster): (vk::PrimitiveTopology, Raster), + make: impl FnOnce() -> Result, + ) -> Result { + use vk::PrimitiveTopology as T; + let polygons = matches!(class, T::TRIANGLE_LIST | T::PATCH_LIST); let counters = &self.core.counters; if polygons && raster == Raster::default() { - return (self.primary).pipeline(counters, || self.make(class, raster)); + return (cells.primary).pipeline(counters, make); } - if let Some((list, named)) = &self.named { - if (*list, raster) == (class, Raster::default()) { - return named.pipeline(counters, || self.make(class, raster)); - } + if self.named == Some(class) && raster == Raster::default() { + return (cells.named).pipeline(counters, make); } - let mut later = lock(&self.later); + let mut later = lock(&cells.later); if let Some(&(.., made)) = (later.iter()).find(|&&(c, r, _)| (c, r) == (class, raster)) { return Ok(made); } let began = host_time(); - let made = self.make(class, raster)?; + let made = make()?; later.push((class, raster, made)); let site = match (class, raster == Raster::default()) { (T::LINE_LIST, true) => FirstUse::Lines, (T::POINT_LIST, true) => FirstUse::Points, _ => FirstUse::Raster, }; - (self.core.counters).first_use_wait(site, host_time().saturating_sub(began)); + counters.first_use_wait(site, host_time().saturating_sub(began)); Ok(made) } @@ -1679,13 +1743,52 @@ impl RenderCompiled { /// ones first. #[cfg(all(test, any(m2v_gpu, m2v_cpu_icd)))] pub(crate) fn made_flags(&self) -> Vec { - let named = (self.named.as_ref()).and_then(|(_, named)| named.get()); - let made = usize::from(self.primary.get().is_some()) - + usize::from(named.is_some()) - + lock(&self.later).len(); + let cells = &self.cells; + let made = usize::from(cells.primary.get().is_some()) + + usize::from(cells.named.get().is_some()) + + lock(&cells.later).len(); vec![self.flags; made] } + /// The plain `VkPipeline` of `class` under `raster`, and, where the content has a words twin, + /// the twin's of the same class and raster state in the same make, kept in its cells: a draw + /// that binds a texture buffer held as words then makes nothing its plain pipeline's draw + /// would not. The twin's make is counted + /// ([`Metrics::word_pipelines_created`](crate::Metrics::word_pipelines_created)); where it + /// fails, the plain one is given back and the error answered. + fn make_twinned( + &self, + class: vk::PrimitiveTopology, + raster: Raster, + ) -> Result { + let plain = self.make(&self.stages, class, raster)?; + let Some(twin) = &self.words else { + return Ok(plain); + }; + let make = || self.make_twin(twin, class, raster); + let cells = &twin.cells; + let made = match (class, raster == Raster::default()) { + (vk::PrimitiveTopology::TRIANGLE_LIST | vk::PrimitiveTopology::PATCH_LIST, true) => { + cells.primary.make_ahead(make).map(drop) + } + (class, true) if self.named == Some(class) => cells.named.make_ahead(make).map(drop), + _ => { + let mut later = lock(&cells.later); + match (later.iter()).any(|&(c, r, _)| (c, r) == (class, raster)) { + true => Ok(()), + false => make().map(|made| later.push((class, raster, made))), + } + } + }; + match made { + Ok(()) => Ok(plain), + Err(error) => { + (self.core.reaper).give(Job::Free(Free::Pipeline(plain))); + Err(error) + } + } + } + /// Whether the content's `VkPipeline`s render into `pass`'s attachments: its colour formats are /// the pass's colour attachments', by index, an absent one where the pass has none, its /// depth and stencil formats the pass's depth and stencil attachments', or none without one, @@ -1748,17 +1851,39 @@ impl RenderCompiled { .fold(0, |bits, &color| bits | 1 << color) } + /// The words twin's `VkPipeline` of `class` under `raster`, counted live and made + /// ([`Metrics::word_pipelines_created`](crate::Metrics::word_pipelines_created)). + fn make_twin( + &self, + twin: &RenderWords, + class: vk::PrimitiveTopology, + raster: Raster, + ) -> Result { + let began = host_time(); + let made = self.make(&twin.stages, class, raster)?; + self.core + .counters + .word_pipeline(host_time().saturating_sub(began)); + self.core.counters.rise(Gauge::WordPipelines); + Ok(made) + } + /// A `VkPipeline` of the content for draws of the class of `topology`, a list topology, under /// `raster`, made through the device's pipeline data, rendering dynamically into the /// descriptor's attachment formats. A draw sets its own topology within the class as dynamic /// state. A patch list takes the translator's control points per patch. - fn make(&self, topology: vk::PrimitiveTopology, raster: Raster) -> Result { + fn make( + &self, + stages: &[Module], + topology: vk::PrimitiveTopology, + raster: Raster, + ) -> Result { let core = &self.core; let fixed = &self.fixed; // A stage at the subgroup size the translator pins, as a kernel's is: one it pins none for // runs at the device's own size. - let mut subgroups = subgroup_sizes(&self.stages); - let stages = stage_infos(&self.stages, &mut subgroups); + let mut subgroups = subgroup_sizes(stages); + let stages = stage_infos(stages, &mut subgroups); let mut divided = vk::PipelineVertexInputDivisorStateCreateInfoKHR::default() .vertex_binding_divisors(&fixed.divisors); let mut vertex_input = vk::PipelineVertexInputStateCreateInfo::default() @@ -1883,6 +2008,56 @@ impl RenderCompiled { } } +/// The module of `stage`, its specialization constants fixed at the content's values: the +/// descriptor's raster `samples`, and `SpecKey::TexelBufferWords` true for the words twin +/// (`words`), so the driver is handed no specialization, as a kernel's module is. +/// +/// Err: [`RenderPipelineKind::Specialization`] for a constant a draw does not set; +/// [`RenderPipelineKind::SynthesizedStages`] for an entry point a C string cannot name; the +/// translator's error of the specialization; [`Error::Vulkan`] where the module's create fails. +fn stage_module( + core: &Core, + stage: &metal2vulkan::pipeline::StageModule, + samples: u32, + words: bool, +) -> Result { + let mut values = Vec::new(); + for constant in &stage.specialization.constants { + let value: u32 = match (constant.key, constant.size) { + (SpecKey::SampleCount, 4) => samples, + (SpecKey::AmplificationCount, 4) => 1, + (SpecKey::TexelBufferWords { .. }, 4) => u32::from(words), + _ => { + return Err(Error::Unsupported(Gap::RenderPipeline { + kind: RenderPipelineKind::Specialization, + })); + } + }; + values.push((constant.id, u64::from(value))); + } + let words = specialize(&stage.spirv, &values).map_err(Error::translation)?; + // The translator's entry points hold no NUL; one that did would name no entry point. + let Ok(entry) = CString::new(stage.entry_point.as_str()) else { + return Err(Error::Unsupported(Gap::RenderPipeline { + kind: RenderPipelineKind::SynthesizedStages, + })); + }; + let flags = vk::PipelineShaderStageCreateFlags::from_raw(stage.stage_flags.as_raw()); + let kind = vk::ShaderStageFlags::from_raw(stage.stage.as_raw()); + let info = vk::ShaderModuleCreateInfo::default().code(&words); + // SAFETY: the words are the translator's SPIR-V with its constants fixed, valid where the + // translator's are, for the features device creation enabled. + let module = unsafe { core.device.create_shader_module(&info, None) } + .map_err(Error::vulkan("vkCreateShaderModule"))?; + Ok(Module { + module, + entry, + stage: kind, + flags, + subgroup_size: stage.required_subgroup_size, + }) +} + /// Gives `stages`' modules to the reaper: a creation that failed after making them. fn release(core: &Core, stages: &[Module]) { for stage in stages { @@ -2150,13 +2325,17 @@ impl Drop for RenderCompiled { // it retired. self.core.counters.fall(Gauge::RenderContents); // Only what was made: a main pipeline no call or draw made, or whose make failed, is none. - let named = (self.named.iter()).filter_map(|(_, named)| named.get()); - let later = self.later.get_mut().unwrap_or_else(|e| e.into_inner()); - let later = later.iter().map(|&(.., pipeline)| pipeline); - for pipeline in (self.primary.get().into_iter()).chain(named).chain(later) { + for pipeline in self.cells.made() { (self.core.reaper).give(Job::Free(Free::Pipeline(pipeline))); } release(&self.core, &self.stages); + if let Some(twin) = &mut self.words { + for pipeline in twin.cells.made() { + self.core.counters.fall(Gauge::WordPipelines); + (self.core.reaper).give(Job::Free(Free::Pipeline(pipeline))); + } + release(&self.core, &twin.stages); + } } } diff --git a/crates/metal2vulkan-runtime/src/render_encoder.rs b/crates/metal2vulkan-runtime/src/render_encoder.rs index 86cfdf9bc..d3aa6dbb2 100644 --- a/crates/metal2vulkan-runtime/src/render_encoder.rs +++ b/crates/metal2vulkan-runtime/src/render_encoder.rs @@ -2995,7 +2995,13 @@ impl RenderCommandEncoder { }; // Points Metal does not rasterize: the vertex function runs, behind an empty scissor. let hidden = topology == vk::PrimitiveTopology::POINT_LIST && !compiled.rasterizes_points(); - let pipeline = compiled.pipeline(topology, self.raster)?; + let tables = &self.tables; + let words = compiled.binds_words(|table, slot| { + tables[table] + .texture(slot) + .is_some_and(|t| t.held_as_words()) + }); + let pipeline = compiled.pipeline(topology, self.raster, words)?; let discards = compiled.discards(); let writes_memory = draws.writes_memory; let building = (self.building.as_ref()) @@ -3499,7 +3505,13 @@ impl RenderCommandEncoder { })); }; let (topology, _) = executed_topology(buffer); - let pipeline = compiled.pipeline(topology, self.raster)?; + let tables = &self.tables; + let words = compiled.binds_words(|table, slot| { + tables[table] + .texture(slot) + .is_some_and(|t| t.held_as_words()) + }); + let pipeline = compiled.pipeline(topology, self.raster, words)?; let made = (&**compiled, self.raster, pipeline); let shape = indirect.shape( &self.core, diff --git a/crates/metal2vulkan-runtime/src/tests/indirect.rs b/crates/metal2vulkan-runtime/src/tests/indirect.rs index e96a2a44c..2ccf02ed1 100644 --- a/crates/metal2vulkan-runtime/src/tests/indirect.rs +++ b/crates/metal2vulkan-runtime/src/tests/indirect.rs @@ -90,6 +90,7 @@ fn draws(fields: Vec<(DrawPlace, usize, FieldValue)>) -> Draws { Draws { buffers: Vec::new(), textures: Vec::new(), + texel_buffers: Vec::new(), usages: Vec::new(), storage_reads: Vec::new(), formatless: Vec::new(), @@ -2012,7 +2013,11 @@ mod on_device { let compiled = &state.inner.compiled; let pipeline = ok( name, - compiled.pipeline(vk::PrimitiveTopology::TRIANGLE_LIST, Raster::default()), + compiled.pipeline( + vk::PrimitiveTopology::TRIANGLE_LIST, + Raster::default(), + false, + ), ); let layout = |vertex, fragment| IndirectDrawLayout::new(vertex, fragment).expect("a layout"); @@ -2024,7 +2029,7 @@ mod on_device { }; let other = ok( name, - compiled.pipeline(vk::PrimitiveTopology::TRIANGLE_LIST, clamped), + compiled.pipeline(vk::PrimitiveTopology::TRIANGLE_LIST, clamped, false), ); let before = indirect.held().1; ok( @@ -2105,8 +2110,11 @@ mod on_device { let indirect = (core.indirect.as_ref()).expect("the extension"); let pipeline = ok( name, - (state.inner.compiled) - .pipeline(vk::PrimitiveTopology::TRIANGLE_LIST, Raster::default()), + (state.inner.compiled).pipeline( + vk::PrimitiveTopology::TRIANGLE_LIST, + Raster::default(), + false, + ), ); let layout = IndirectDrawLayout::new(31, 31).expect("a layout"); let room = core.translator.profile().push_window() / 8 - 1; @@ -2164,7 +2172,11 @@ mod on_device { let compiled = &state.inner.compiled; let pipeline = ok( name, - compiled.pipeline(vk::PrimitiveTopology::TRIANGLE_LIST, Raster::default()), + compiled.pipeline( + vk::PrimitiveTopology::TRIANGLE_LIST, + Raster::default(), + false, + ), ); let layout = IndirectDrawLayout::new(3, 1).expect("a layout"); let shape = |capacity| { diff --git a/crates/metal2vulkan-runtime/src/texture.rs b/crates/metal2vulkan-runtime/src/texture.rs index e5a23a08c..851991386 100644 --- a/crates/metal2vulkan-runtime/src/texture.rs +++ b/crates/metal2vulkan-runtime/src/texture.rs @@ -296,6 +296,9 @@ struct Texels { /// The format's storage texel buffers are written through an image declared without a /// format ([`TexelForm`]'s `writes`). writes: bool, + /// It holds its texels as words ([`TexelForm`]'s `words`), counted live + /// ([`Gauges::word_texture_buffers`](crate::Gauges::word_texture_buffers)). + words: bool, } /// A texture's view of its image's shadow (`TextureInner::shadow`). @@ -1352,6 +1355,9 @@ impl Drop for TextureInner { // After its elements: the view goes once nothing reaches it through them. if let Body::Texels(texels) = &self.body { core.pool.release(core, Free::TexelView(texels.view)); + if texels.words { + core.counters.fall(Gauge::WordTextureBuffers); + } } // Its element is null, or another texture's: its view of the shadow goes before the // shadow, which its image holds. @@ -4464,6 +4470,13 @@ impl Transfer { } impl TextureInner { + /// Whether it is a texture buffer held as words + /// (`metal2vulkan::metal::format::texel_buffer_form`), for which a draw or dispatch that binds + /// it where a function reaches it runs its words twin. + pub(crate) fn held_as_words(&self) -> bool { + matches!(&self.body, Body::Texels(texels) if texels.words) + } + /// Checks a copy of `region` of `level` and `slice` with `len` bytes, rows `bytes_per_row` /// and images `bytes_per_image` apart. `None` for an empty region, which copies nothing. fn copy( @@ -7406,6 +7419,7 @@ impl Device { view, elements, writes: form.writes, + words: form.words.is_some(), }), format: form.format, storage_reads: form.reads, @@ -7432,6 +7446,9 @@ impl Device { shadow: None, levels: Mutex::new(None), }; + if form.words.is_some() { + core.counters.rise(Gauge::WordTextureBuffers); + } Ok(Texture { inner: Arc::new(inner), device: self.clone(), diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index cc7f4c2ea..ce8e78346 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -864,7 +864,7 @@ codec_enum! { ConstantLanes(f0), BoundTexelFormat(f0), OffsetBaseAxes(f0), SamplerAnisotropy(f0), NearestPixelSampler(f0), BoundSamplerWord(f0), StageInReach, HeapRawTextures(f0), BorderTexels(f0), HeapNanFamilies(f0), DeepThreadgroup, - WorkgroupSize(f0), + WorkgroupSize(f0), TexelBufferWords { stage, handles }, } PushField { RootTableAddress, ExecutionStatusAddress, DispatchRegion, BaseVertexInstance, diff --git a/crates/metal2vulkan/src/lower/access/handle.rs b/crates/metal2vulkan/src/lower/access/handle.rs index 1313de870..3a15d0244 100644 --- a/crates/metal2vulkan/src/lower/access/handle.rs +++ b/crates/metal2vulkan/src/lower/access/handle.rs @@ -1048,7 +1048,8 @@ pub fn emit( /// (`TextureWord::OUT_OF_BOUNDS_ALPHA_ONE`) moved to `HANDLE_ALPHA_ONE` where the function's /// handles carry it (`memory::handles::Lookup::Flagged`'s `alpha`), and the word's low bits /// above the index where the function reaches an argument buffer's texture buffer held as words -/// (`lower::texture::HANDLE_WORD`). The program writes the ID, so +/// and its stage's `SpecKey::TexelBufferWords` holds (`lower::texture::HANDLE_WORD`). The program +/// writes the ID, so /// the mask keeps any value it holds inside the arrays: a bad ID reads the element at its masked /// index. The admission allows no other form (`select::identity_admits`). fn emit_identity_handle( @@ -1087,6 +1088,10 @@ fn emit_identity_handle( let low = fb.binary(BinOp::BitwiseAnd, word, bits)?; let shift = k32(fb, HANDLE_WORD_SHIFT)?; let carried = fb.binary(BinOp::ShiftLeftLogical, low, shift)?; + // Only where the stage's `SpecKey::TexelBufferWords` holds. + let gate = crate::lower::texture::words_gate(cx, fb)?; + let none = k32(fb, 0)?; + let carried = fb.select(gate, carried, none)?; fb.binary(BinOp::BitwiseOr, h, carried)? } false => h, diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index 9cdb6b98a..f8a6e7390 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -693,18 +693,23 @@ pub(crate) struct HeapElement { /// The element of heap handle `h` (as the function's handle-table search yields it): the handle /// masked to its element where the search carries anything beside it /// (`memory::handles::Lookup::element_mask`), or, under the identity domains, where the handle -/// carries its word's low bits (`words::HANDLE_WORD`), else the handle itself. +/// carries its word's low bits (`words::HANDLE_WORD`, where the stage's +/// `SpecKey::TexelBufferWords` holds), else the handle itself. fn heap_element_index(cx: &EmitCx<'_>, fb: &mut FunctionBuilder<'_>, h: SValue) -> BResult { let form = cx.plan.families.access.lookup(); let carried = cx.plan.families.access.identity && cx.plan.families.texture.words.heap; - let element = match carried { - true => Some(crate::pipeline::link::IDENTITY_TEXTURES - 1), - false => form.element_mask(), + let mask = match (carried, form.element_mask()) { + (false, None) => return Ok(h), + (false, Some(element)) => u32s(fb, 1, element)?, + // The word's bits, which the handle carries only where the stage's + // `SpecKey::TexelBufferWords` holds (`words::gate`). + (true, plain) => { + let gate = super::words::gate(cx, fb)?; + let words = u32s(fb, 1, crate::pipeline::link::IDENTITY_TEXTURES - 1)?; + let plain = u32s(fb, 1, plain.unwrap_or(u32::MAX))?; + fb.select(gate, words, plain)? + } }; - let Some(element) = element else { - return Ok(h); - }; - let mask = u32s(fb, 1, element)?; fb.binary(BinOp::BitwiseAnd, h, mask) } diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 7e4864b75..542ff2dbd 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -188,7 +188,7 @@ pub(crate) use emit::{ pub use emit::{emit, held_texel, to_image}; pub(crate) use slot::depth_comparison; pub use status::StatusUse; -pub(crate) use words::{HANDLE_WORD, HANDLE_WORD_SHIFT}; +pub(crate) use words::{gate as words_gate, HANDLE_WORD, HANDLE_WORD_SHIFT}; use crate::lower::access::handle::HandleTarget; use crate::memory::handles::{Candidate, HeapGroups}; diff --git a/crates/metal2vulkan/src/lower/texture/words.rs b/crates/metal2vulkan/src/lower/texture/words.rs index d539b3ad6..a39a0e730 100644 --- a/crates/metal2vulkan/src/lower/texture/words.rs +++ b/crates/metal2vulkan/src/lower/texture/words.rs @@ -7,8 +7,11 @@ //! past its width (`resource_word::TextureWord::of_texture_buffer`); the module takes the codes its //! device holds as words from its profile (`metal::format::texel_buffer_word_codes`), and declares //! nothing of this where there are none. A texture-buffer slot's read, write and width query test -//! the code against those ([`Words`]): where the device does not hold it as words the access is the -//! texture's own view's, as it is for every other texture buffer; elsewhere a read or write calls +//! the code against those ([`Words`]), under the stage's `SpecKey::TexelBufferWords` ([`gate`]): +//! where that is false, as it is by default, the test and every arm of the words are dead code at +//! pipeline creation and each access is the texture's own view's alone. Where the device does +//! not hold the code as words the access is the texture's own view's, as it is for every other +//! texture buffer; elsewhere a read or write calls //! one of the module's routines ([`Routine`]), defined once and kept out of line (`DontInline`), //! which takes the texel's word from the view's element and converts it by the code, its cases //! the profile's codes alone. The width is the view's words times the @@ -397,7 +400,9 @@ pub(super) fn emit( w: &Words, ) -> BResult> { let (element, word) = element_word(cx, fb, w.image)?; - let held = held_test(fb, word, cx.plan.families.texture.words.codes)?; + let test = held_test(fb, word, cx.plan.families.texture.words.codes)?; + let gate = gate(cx, fb)?; + let held = fb.binary(BinOp::LogicalAnd, gate, test)?; let routine = match w.routine { Some(r) => match cx.decl.families.texture.words.routines.get(&r) { Some(f) => Some(*f), @@ -474,6 +479,19 @@ pub(super) fn emit( Ok(m.first().copied()) } +/// The stage's `SpecKey::TexelBufferWords`, a `bool` fixed at pipeline creation (false by +/// default), which gates each site's test and the word bits a handle carries: where it is false +/// they are dead code, and each access is its texture's own view's alone. +pub(crate) fn gate(cx: &EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult { + let ty = fb.module().ty(SType::Bool)?; + let key = crate::pipeline::sym::SpecKey::TexelBufferWords { + stage: cx.plan.stage, + handles: cx.plan.families.texture.words.heap, + }; + let c = fb.module().spec(key, ty, ConstBits(0))?; + fb.module().const_value(c) +} + /// Whether word `word` (`u32`) names a format of `codes` ([`WordsPlan::codes`]): where `codes` are /// every format's, whether its code is not 0; else the code's bit of `codes`. fn held_test(fb: &mut FunctionBuilder<'_>, word: SValue, codes: u64) -> BResult { diff --git a/crates/metal2vulkan/src/pipeline/sym.rs b/crates/metal2vulkan/src/pipeline/sym.rs index 5437e3bfc..e0f479dfe 100644 --- a/crates/metal2vulkan/src/pipeline/sym.rs +++ b/crates/metal2vulkan/src/pipeline/sym.rs @@ -729,6 +729,18 @@ pub enum SpecKey { /// `OpSpecConstantOp`: the size a driver reads from the composite's parts as declared is the /// one the body computes with. WorkgroupSize(Axis), + /// Boolean: the stage's texture buffers may be held as words (default false). Declared, under + /// the identity domains on a profile that holds some colour format's texture buffer as words + /// (`metal::format::texel_buffer_form`), by a stage that reads, writes or queries the width + /// of a texture buffer. Where it is false each such access is the texture's own view's alone, + /// and every arm of the words (`lower::texture::words`), with the word bits a handle carries, + /// is dead code at pipeline creation; where it is true each access tests its texture's word + /// and takes the words' routine where the device holds the format as words. `handles`: the + /// stage reaches a texture buffer through a handle (an argument buffer's texture), which no + /// texture slot of it names. A binder sets it true for a draw or dispatch that binds a texture + /// buffer held as words at a texture buffer slot the stage declares, or, where `handles`, while + /// a texture buffer held as words may be reached through a handle. + TexelBufferWords { stage: Stage, handles: bool }, } impl SpecKey { diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 6a32a4f73..19af2a465 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -1395,6 +1395,8 @@ field metal2vulkan-runtime::Gauges.textures pub textures: u64 field metal2vulkan-runtime::Gauges.textures_copied_over pub textures_copied_over: u64 field metal2vulkan-runtime::Gauges.threads pub threads: [u64; THREADS] field metal2vulkan-runtime::Gauges.timestamp_pools pub timestamp_pools: u64 +field metal2vulkan-runtime::Gauges.word_pipelines pub word_pipelines: u64 +field metal2vulkan-runtime::Gauges.word_texture_buffers pub word_texture_buffers: u64 field metal2vulkan-runtime::HeapRange.block pub block: BlockId field metal2vulkan-runtime::HeapRange.len pub len: u64 field metal2vulkan-runtime::HeapRange.offset pub offset: u64 @@ -1665,6 +1667,8 @@ field metal2vulkan-runtime::Metrics.upload_barriers pub upload_barriers: u64 field metal2vulkan-runtime::Metrics.upload_waits pub upload_waits: u64 field metal2vulkan-runtime::Metrics.visibility_interrupts_refused pub visibility_interrupts_refused: u64 field metal2vulkan-runtime::Metrics.waits_behind_counter pub waits_behind_counter: u64 +field metal2vulkan-runtime::Metrics.word_pipeline_nanos pub word_pipeline_nanos: u64 +field metal2vulkan-runtime::Metrics.word_pipelines_created pub word_pipelines_created: u64 field metal2vulkan-runtime::Metrics.zero_source_allocations pub zero_source_allocations: SiteAllocations field metal2vulkan-runtime::Metrics.zero_writes pub zero_writes: Timed field metal2vulkan-runtime::OverCopyKind.cause pub cause: OverCause @@ -10275,6 +10279,7 @@ variant metal2vulkan::pipeline::SpecKey::SamplerMinLevel SamplerMinLevel(SlotRef variant metal2vulkan::pipeline::SpecKey::SamplerState SamplerState { slot: SlotRef, fields: u32 } variant metal2vulkan::pipeline::SpecKey::SparseTexture SparseTexture(SlotRef) variant metal2vulkan::pipeline::SpecKey::StageInReach StageInReach +variant metal2vulkan::pipeline::SpecKey::TexelBufferWords TexelBufferWords { stage: Stage, handles: bool } variant metal2vulkan::pipeline::SpecKey::TextureSwizzle TextureSwizzle(SlotRef) variant metal2vulkan::pipeline::SpecKey::TgLength TgLength(u32) variant metal2vulkan::pipeline::SpecKey::TgOffset TgOffset(u32)