diff --git a/crates/metal2vulkan-runtime/src/alias_split.rs b/crates/metal2vulkan-runtime/src/alias_split.rs index 3984a6bda..8edf620ab 100644 --- a/crates/metal2vulkan-runtime/src/alias_split.rs +++ b/crates/metal2vulkan-runtime/src/alias_split.rs @@ -22,9 +22,20 @@ //! (`EncoderCore::split_at_aliases`), which notes none. An encoder that joined a group goes on //! in a `VkCommandBuffer` of its own after the group's: its part's submission orders it after //! the group's first part, the tracker's barrier between them in a command buffer of barriers, -//! the form measured to read the write. A render encoder records no barrier inside its pass, -//! so on such a device it joins no group whose earlier encoders wrote bytes -//! (`State::join_fold`). Counted: `WorkCounts::command_buffers_split_at_aliases`. +//! the form measured to read the write. Counted: `WorkCounts::command_buffers_split_at_aliases`. +//! - **Render encoders.** A pass records no barrier, nor a new `VkCommandBuffer`, inside it, so +//! the split goes before it. One whose pass records at its end joins a group as any encoder +//! (`State::join_fold`). Its draws, recorded into its secondary, run after every command it +//! records into the `VkCommandBuffer` before the pass, whichever came first: each draw's image +//! uses are noted apart ([`AliasWrites::noted_apart`]), and where one meets a noted write, or a +//! write noted later meets one ([`AliasWrites::note`]), the encoder owes a split. The first +//! command it then records into the `VkCommandBuffer` (a shadow's copy before a later draw, or +//! at its end the steps before its pass and the pass, whose uses hold its attachments') goes in +//! a new one where it owes one, or where its own uses meet the writes: so every image the pass +//! uses is checked against every write before it before the pass records. The images noted +//! apart stay noted in the new one, whose later writes their draws still follow. One whose +//! first instance records inline joins no group (`encoder_fold.rs`): its draws record from its +//! first on, before its later calls are known. //! - **Scope.** The measured direction alone: a use through an image after a write through a //! buffer. A use through a buffer after a write through an image is not measured and takes no //! split. A render pass's draws record inside its pass, where no `VkCommandBuffer` ends; what @@ -45,18 +56,66 @@ pub(crate) fn splits_at_aliases(facts: &BTreeSet) -> bool { facts.contains(&DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer) } -/// The most writes an [`AliasWrites`] notes apart: past them a new key's write makes every image -/// use meet a write, so the next one splits and the list starts again. +/// The most keys an [`AliasWrites`] notes the bytes of apart, in its writes and in its images +/// noted apart each: past them a new key makes every range meet, so the next image use, or the +/// next write, splits. const KEPT: usize = 32; -/// The bytes of each key the commands recorded into an encoder's current `VkCommandBuffer` wrote -/// (the module docs), on a device that splits at aliases: at most [`KEPT`], a key's writes -/// joined into the range that holds them all where it has one, and past that every key's. +/// Ranges of bytes of keys' memory: at most [`KEPT`] keys', a key's ranges joined into the range +/// that holds them all, and past that every key's. +#[derive(Default)] +struct Noted { + ranges: Vec<(ResourceKey, Range)>, + /// A range of more keys than [`KEPT`] was noted: every range meets one. + every: bool, +} + +impl Noted { + /// Note `bytes` of `key`: joined into the key's noted range where it has one, else apart + /// while fewer than [`KEPT`] keys are. + fn add(&mut self, key: ResourceKey, bytes: Range) { + if self.every { + return; + } + if let Some((_, range)) = self.ranges.iter_mut().find(|(noted, _)| *noted == key) { + range.start = range.start.min(bytes.start); + range.end = range.end.max(bytes.end); + } else if self.ranges.len() < KEPT { + self.ranges.push((key, bytes)); + } else { + self.every = true; + } + } + + /// Whether `bytes` of `key` meet a noted range. + fn meets(&self, key: ResourceKey, bytes: &Range) -> bool { + self.every + || (self.ranges.iter()).any(|(noted, range)| { + *noted == key && range.start < bytes.end && bytes.start < range.end + }) + } + + fn clear(&mut self) { + self.ranges.clear(); + self.every = false; + } +} + +/// What an encoder's commands on a device that splits at aliases noted (the module docs): the +/// bytes of each key the commands recorded into its current `VkCommandBuffer` wrote, and the +/// memory the images of its commands recorded apart use, which run after them (a pass's draws). +/// Each holds at most [`KEPT`] keys' ranges, and past that every key's. #[derive(Default)] pub(crate) struct AliasWrites { - writes: Vec<(ResourceKey, Range)>, - /// A write of more keys than [`KEPT`] was noted: every image use meets one. - every: bool, + writes: Noted, + /// The bytes the images of the commands recorded outside the `VkCommandBuffer`, which a + /// later command there executes, use ([`noted_apart`](Self::noted_apart)): kept from one + /// `VkCommandBuffer` to the next, as those commands run after what either records before them. + apart: Noted, + /// A command noted apart uses an image whose memory meets a noted write, or a write noted + /// since meets an image one uses: the next command recorded into the `VkCommandBuffer` goes + /// in a new one. + owed: bool, } impl AliasWrites { @@ -65,53 +124,52 @@ impl AliasWrites { pub(crate) fn joining(order: Option<&FoldOrder>) -> AliasWrites { let mut writes = AliasWrites::default(); for (key, bytes) in order.into_iter().flat_map(FoldOrder::byte_writes) { - writes.wrote(key, bytes); + writes.writes.add(key, bytes); } writes } - /// Note a command recorded with `uses`: the bytes it writes. + /// Note a command recorded into the `VkCommandBuffer` with `uses`: the bytes it writes, and + /// whether one meets the memory of an image a command noted apart uses, which runs after it + /// ([`noted_apart`](Self::noted_apart)): the next command recorded there goes in a new one. pub(crate) fn note(&mut self, uses: &[Use]) { for used in uses.iter().filter(|used| !used.write.is_empty()) { if let UseRange::Bytes(bytes) = &used.range { - self.wrote(used.key, bytes.clone()); + self.owed |= self.apart.meets(used.key, bytes); + self.writes.add(used.key, bytes.clone()); } } } - /// Note a write of `bytes` of `key`: joined into the range of the key's noted writes where - /// it has one, else apart while fewer than [`KEPT`] are. - fn wrote(&mut self, key: ResourceKey, bytes: Range) { - if self.every { - return; - } - if let Some((_, range)) = self.writes.iter_mut().find(|(noted, _)| *noted == key) { - range.start = range.start.min(bytes.start); - range.end = range.end.max(bytes.end); - } else if self.writes.len() < KEPT { - self.writes.push((key, bytes)); - } else { - self.every = true; + /// Note a command recorded outside the `VkCommandBuffer` with `uses`, which a later command + /// there executes (a draw of a pass recorded at its end, into its secondary): the memory its + /// images use, and whether it meets a noted write. Where it does, now or once a later write + /// meets it ([`note`](Self::note)), the next command recorded there goes in a new one + /// ([`meets`](Self::meets)). + pub(crate) fn noted_apart(&mut self, uses: &[Use]) { + for used in uses { + if let Some(bytes) = used.range.image_bytes() { + self.owed |= self.writes.meets(used.key, &bytes); + self.apart.add(used.key, bytes); + } } } /// Whether a command with `uses` uses an image whose memory meets bytes a command before it - /// in the `VkCommandBuffer` wrote: it goes in a new one (the module docs). + /// in the `VkCommandBuffer` wrote, or follows a command noted apart whose images do + /// ([`noted_apart`](Self::noted_apart)): it goes in a new one (the module docs). pub(crate) fn meets(&self, uses: &[Use]) -> bool { - uses.iter() - .filter(|used| matches!(used.range, UseRange::Image { .. })) - .any(|used| { - self.every - || (self.writes.iter()).any(|(key, bytes)| { - *key == used.key - && used.range.shares_memory(&UseRange::Bytes(bytes.clone())) - }) + self.owed + || (uses.iter()).any(|used| { + (used.range.image_bytes()).is_some_and(|bytes| self.writes.meets(used.key, &bytes)) }) } - /// The encoder went on in a new `VkCommandBuffer`: no command wrote anything there yet. + /// The encoder went on in a new `VkCommandBuffer`: no command wrote anything there yet, and + /// nothing is owed. The images noted apart stay: their commands run after what the new one + /// records before them. pub(crate) fn begun(&mut self) { self.writes.clear(); - self.every = false; + self.owed = false; } } diff --git a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs index 945fdcf9a..aefff10e0 100644 --- a/crates/metal2vulkan-runtime/src/command_buffer/fold.rs +++ b/crates/metal2vulkan-runtime/src/command_buffer/fold.rs @@ -19,14 +19,11 @@ impl State { /// the tail, which the encoder records into, and, where it is the group's second encoder, the /// group's order built from its first part's summary (`Fold::order`). `None` where it joins /// none, the group left in place: the encoder's open closes it once it opened - /// ([`close_fold`](Self::close_fold)). On a device that `splits_at_aliases`, a render - /// encoder joins no group whose earlier encoders wrote bytes: its pass records no barrier, nor - /// a new `VkCommandBuffer`, before a use of an image over them (`alias_split.rs`). - pub(crate) fn join_fold( - &mut self, - joining: Joining, - (trail, splits_at_aliases): (bool, bool), - ) -> Option> { + /// ([`close_fold`](Self::close_fold)). On a device that splits at aliases + /// (`alias_split.rs`), a render encoder whose pass records at its end joins as any encoder: + /// the first command it records into the tail at its end, where its pass or a draw of it uses + /// an image over bytes the group's earlier encoders wrote, goes in a new `VkCommandBuffer`. + pub(crate) fn join_fold(&mut self, joining: Joining, trail: bool) -> Option> { let fold = self.fold.as_ref()?; let joins = fold.admits(joining) && self.tail == Some(fold.tail) @@ -43,11 +40,6 @@ impl State { 1 => Some(FoldOrder::after(&self.recorded.get(fold.leader)?.summary)), _ => None, }; - let render = matches!(joining, Joining::Render { .. }); - let wrote_bytes = || (order.as_ref().unwrap_or(&fold.order).byte_writes().next()).is_some(); - if splits_at_aliases && render && wrote_bytes() { - return None; - } self.tail = None; let mut fold = self.fold.take()?; if let Some(order) = order { diff --git a/crates/metal2vulkan-runtime/src/encoder.rs b/crates/metal2vulkan-runtime/src/encoder.rs index 5ebb834c2..932949c6e 100644 --- a/crates/metal2vulkan-runtime/src/encoder.rs +++ b/crates/metal2vulkan-runtime/src/encoder.rs @@ -731,9 +731,7 @@ impl EncoderCore { return Err(invalid(call, problem)); } let shared = command_buffer.device().shared(); - let fold = joining.and_then(|joining| { - state.join_fold(joining, (shared.encoder_trail, shared.splits_at_aliases)) - }); + let fold = joining.and_then(|joining| state.join_fold(joining, shared.encoder_trail)); let (raw, barriered) = match &fold { Some(fold) => { shared.counts.encoder_folded(); @@ -2276,6 +2274,12 @@ impl EncoderCore { /// memory beside them ([`aliased`](Self::aliased)), worked out into the vector the encoder /// keeps for them. fn record_aliased(&mut self, stages: vk::PipelineStageFlags2, uses: &[Use]) { + // The images of a draw recorded apart, which runs after every command recorded into the + // `VkCommandBuffer` before its pass: where one lies over bytes a command there wrote, or a + // later one writes, the pass goes in a new one (`alias_split.rs`). + if let Some(writes) = &mut self.alias_writes { + writes.noted_apart(uses); + } let aliases = &self.open.command_buffer.generation().aliases; let quiet = Some(&mut self.aliases_quiet); let all = match aliases.augment_into(uses, &mut self.aliased_uses, quiet) { @@ -2735,6 +2739,12 @@ impl EncoderCore { if self.skips(uses.iter().map(|used| used.key)) { return; } + // A copy that uses an image over bytes a command before it wrote in the `VkCommandBuffer`, + // or after a draw noted apart that does, goes in a new one (`alias_split.rs`). + let split = (self.alias_writes.as_ref()).is_some_and(|writes| writes.meets(uses)); + if split && !self.split_at_aliases() { + return; + } let aliased = self.aliased(uses); let tracked = aliased.as_deref().unwrap_or(uses); if run.before(tracked, writes_truth) { diff --git a/crates/metal2vulkan-runtime/src/encoder_fold.rs b/crates/metal2vulkan-runtime/src/encoder_fold.rs index 38f13d797..f465c1406 100644 --- a/crates/metal2vulkan-runtime/src/encoder_fold.rs +++ b/crates/metal2vulkan-runtime/src/encoder_fold.rs @@ -71,8 +71,10 @@ //! `VkCommandBuffer` (`DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`), a command //! that uses an image over bytes the group's earlier encoders wrote ([`FoldOrder::byte_writes`]) //! or its own encoder's earlier commands wrote ends the tail and goes on in a `VkCommandBuffer` -//! of its own, as a folded encoder that leaves work for later does (below), and a render -//! encoder joins no group whose earlier encoders wrote bytes. +//! of its own, as a folded encoder that leaves work for later does (below); a render encoder +//! that joined a group does so before its pass, at the first command it records into the tail +//! once a draw uses such an image or a write meets an image a draw uses, or at its end where its +//! pass's own uses meet them. //! - **Its submission.** The folded encoder's part holds no `VkCommandBuffer`, and its summary //! holds its fence updates alone; its uses and its fence waits join the summary of the group's //! first part, whose `VkCommandBuffer` holds them all, so what the tracker plans before that diff --git a/crates/metal2vulkan-runtime/src/tests/alias_split.rs b/crates/metal2vulkan-runtime/src/tests/alias_split.rs index 4efce4050..d3a002006 100644 --- a/crates/metal2vulkan-runtime/src/tests/alias_split.rs +++ b/crates/metal2vulkan-runtime/src/tests/alias_split.rs @@ -115,6 +115,68 @@ fn a_joining_encoder_meets_what_the_group_wrote() { assert!(!AliasWrites::joining(None).meets(&[image_read(heap, 0..16384)])); } +/// A render pass recorded at its end, in a group whose earlier encoders wrote a heap's bytes: a +/// draw noted apart (into the pass's secondary) that samples an image over them makes the next +/// command recorded into the `VkCommandBuffer`, whatever it uses, go in a new one, which nothing +/// owes; a draw that samples an image placed apart, or reads the bytes through a buffer, owes +/// nothing. +#[test] +fn a_draw_noted_apart_over_written_bytes_splits_the_next_command() { + let heap = ResourceKey::new(); + let first = Summary::outside_encoders(vec![bytes_written(heap, 0..16384)]); + let order = FoldOrder::after(&first); + let mut writes = AliasWrites::joining(Some(&order)); + let buffer_read = Use::reads(heap, true, UseRange::Bytes(0..16384), copy_read()); + writes.noted_apart(&[image_read(heap, 16384..32768), buffer_read]); + assert!( + !writes.meets(&[]), + "a draw over bytes placed apart owes nothing" + ); + writes.noted_apart(&[image_read(heap, 0..16384)]); + assert!(writes.meets(&[]), "the pass's next command after the draw"); + writes.begun(); + assert!(!writes.meets(&[]), "the new `VkCommandBuffer` owes nothing"); + assert!(!writes.meets(&[image_read(heap, 0..16384)])); +} + +/// A draw noted apart runs in its pass, after every command recorded into the `VkCommandBuffer` +/// before the pass, whichever came first: a write noted after the draw, over the bytes of an +/// image the draw uses, makes the next command go in a new one, as a write before it does; a write +/// of bytes placed apart, of another key's, or through an image owes nothing. The draw's images +/// stay noted in the new one, whose later writes the draw still follows; past the keys it keeps +/// apart, every write meets one. +#[test] +fn a_write_after_a_draw_noted_apart_over_its_image_splits_the_next_command() { + let heap = ResourceKey::new(); + let other = ResourceKey::new(); + let mut writes = AliasWrites::default(); + writes.noted_apart(&[image_read(heap, 0..16384)]); + assert!(!writes.meets(&[]), "nothing written"); + let image_written = Use { + write: copy_write(), + read: Access::NONE, + ..image_read(heap, 0..16384) + }; + writes.note(&[ + bytes_written(heap, 16384..32768), + bytes_written(other, 0..16384), + image_written, + ]); + assert!(!writes.meets(&[]), "writes that meet none of its images"); + writes.note(&[bytes_written(heap, 8192..8256)]); + assert!(writes.meets(&[]), "a write under its image"); + writes.begun(); + assert!(!writes.meets(&[]), "the new `VkCommandBuffer` owes nothing"); + writes.note(&[bytes_written(heap, 0..64)]); + assert!(writes.meets(&[]), "a write in the new one under its image"); + let mut many = AliasWrites::default(); + for _ in 0..40 { + many.noted_apart(&[image_read(ResourceKey::new(), 0..64)]); + } + many.note(&[bytes_written(ResourceKey::new(), 0..64)]); + assert!(many.meets(&[]), "past the kept keys, any write"); +} + /// Past the writes it keeps apart, a write of a new key makes every image use meet one, until the /// next `VkCommandBuffer`: the noted writes stay bounded. #[test] diff --git a/crates/metal2vulkan-runtime/src/tests/render_fold.rs b/crates/metal2vulkan-runtime/src/tests/render_fold.rs index c0ae67274..7480dc4c9 100644 --- a/crates/metal2vulkan-runtime/src/tests/render_fold.rs +++ b/crates/metal2vulkan-runtime/src/tests/render_fold.rs @@ -6,12 +6,6 @@ //! buffer over host pages: each lane but [`a_render_encoder_without_a_log_takes_no_group`] makes //! one first. //! -//! On a device that splits at aliases (`DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`, -//! `alias_split.rs`) a render encoder joins no group whose earlier encoders wrote bytes -//! (`State::join_fold`): it begins one of its own where it may lead one, which the encoders after -//! it join. Each lane's render encoder follows a compute encoder that wrote its colors, so each -//! lane's counts follow the device's rule ([`Lane::joins_after_writes`]). -//! //! The hazards a missing barrier leaves are checked by what each encoder reads, a draw's colors //! that the compute encoder before it wrote and a copy of the target the draw wrote; a CPU device //! may run them in order without the barrier, so each lane also counts the barrier at each render @@ -137,12 +131,6 @@ impl Lane { Lane::new(scratch, RenderLoweringPolicy::AtCall, true) } - /// Whether a render encoder joins a group whose earlier encoders wrote bytes: not on a device - /// that splits at aliases (the module docs). - fn joins_after_writes(&self) -> bool { - !self.device.shared().splits_at_aliases - } - /// A `Private` target, cleared to zero and warm: each pass shape the lanes draw, and a /// dispatch and a copy, ran once, so the chains below record each at once (no draw waits /// for its pipeline, which would leave work for later). @@ -321,24 +309,10 @@ fn chain(lane: &Lane) -> (Moved, Vec) { (moved, backs.iter().map(wrong_texels).collect()) } -/// The `encoders_folded`, `command_buffers_begun_encoders` and fewest `command_barriers` of a -/// [`chain`] on `lane`: every encoder after the first joins the first's group, each render -/// encoder's open recording a barrier and each copy's one; where a render encoder joins no group -/// after a write, each begins a group of its own, which the copy and the next step's compute -/// encoder join, and only the copies record a barrier (each after its draw). -fn chain_counts(lane: &Lane) -> (u64, u64, u64) { - match lane.joins_after_writes() { - true => (3 * STEPS - 1, 1, 2 * STEPS), - false => (2 * STEPS - 1, STEPS + 1, STEPS), - } -} - /// Render encoders whose passes record at their ends join the group of the compute and blit /// encoders around them: one `VkCommandBuffer` for the chain, and each draw's secondary. Each /// draw reads the colors the compute encoder before it wrote, and each copy the texels the draw -/// before it wrote: each render encoder's open recorded one barrier, and each copy's one. Where a -/// render encoder joins no group after a write, a `VkCommandBuffer` for the first compute encoder -/// and one for each step from its render encoder on ([`chain_counts`]). +/// before it wrote: each render encoder's open recorded one barrier, and each copy's one. #[test] fn render_encoders_whose_pass_records_at_its_end_join_their_group() { let scratch = Scratch::new("render-fold-chain"); @@ -348,17 +322,15 @@ fn render_encoders_whose_pass_records_at_its_end_join_their_group() { let (moved, wrong) = chain(&lane); println!("RENDER-FOLD-CHAIN {moved:?} wrong texels by step {wrong:?}"); assert_eq!(wrong, vec![0; STEPS as usize], "every texel is the draw's"); - let (folded, begun, barriers) = chain_counts(&lane); assert_eq!( (moved.folded, moved.begun, moved.secondaries), - (folded, begun, STEPS), - "every encoder after the first joined the first's group, or each render encoder began \ - one: {moved:?}" + (3 * STEPS - 1, 1, STEPS), + "every encoder after the first joined the first's group: {moved:?}" ); assert!( - moved.barriers >= barriers, - "each render encoder that joined ordered after the group at its open, each copy after \ - its draw: {moved:?}" + moved.barriers >= 2 * STEPS, + "each render encoder ordered after the group at its open, each copy after its draw: \ + {moved:?}" ); } @@ -374,13 +346,12 @@ fn render_encoders_lowered_after_their_calls_join_their_group() { let (moved, wrong) = chain(&lane); println!("RENDER-FOLD-WORKER {moved:?} wrong texels by step {wrong:?}"); assert_eq!(wrong, vec![0; STEPS as usize], "every texel is the draw's"); - let (folded, begun, barriers) = chain_counts(&lane); assert_eq!( (moved.folded, moved.begun, moved.secondaries), - (folded, begun, STEPS), + (3 * STEPS - 1, 1, STEPS), "{moved:?}" ); - assert!(moved.barriers >= barriers, "{moved:?}"); + assert!(moved.barriers >= 2 * STEPS, "{moved:?}"); } /// A render encoder whose first instance records inline joins no group but begins one: the @@ -447,9 +418,6 @@ fn a_render_encoder_without_a_log_takes_no_group() { /// A compute encoder, a render encoder that joins its group and whose pass `encode` leaves work /// for later, and a copy of the texture the pass rendered: the render encoder joins, and the /// group ends after it, so the copy begins a `VkCommandBuffer` of its own. What moved. -/// -/// Where a render encoder joins no group after a write it begins its own, which leads no group -/// as its pass leaves work for later, and the copy begins another ([`ended_counts`]). fn ends_its_group( lane: &Lane, encode: impl FnOnce(&CommandBuffer) -> Texture, @@ -476,14 +444,6 @@ fn ends_its_group( moved } -/// The `encoders_folded` and `command_buffers_begun_encoders` of [`ends_its_group`] on `lane`. -fn ended_counts(lane: &Lane) -> (u64, u64) { - match lane.joins_after_writes() { - true => (1, 2), - false => (0, 3), - } -} - /// A draw whose pipeline is still being made (the pool held) records its pass later, as a /// segment: the render encoder joined the compute encoder's group, which ends after it. #[test] @@ -528,9 +488,8 @@ fn a_draw_whose_pipeline_is_being_made_ends_its_group() { ); assert_eq!( (moved.folded, moved.begun), - ended_counts(&lane), - "the render encoder joined where it joins after a write, the copy began its own: \ - {moved:?}" + (1, 2), + "the render encoder joined, the copy began its own: {moved:?}" ); } @@ -593,9 +552,8 @@ fn an_execution_of_render_commands_ends_its_group() { ); assert_eq!( (moved.folded, moved.begun), - ended_counts(&lane), - "the render encoder joined where it joins after a write, the copy began its own: \ - {moved:?}" + (1, 2), + "the render encoder joined, the copy began its own: {moved:?}" ); } @@ -651,17 +609,15 @@ fn a_tile_dispatch_whose_pipeline_is_being_made_ends_its_group() { assert!(targets.stored(), "the dispatch stored what Metal's stores"); assert_eq!( (moved.folded, moved.begun), - ended_counts(&lane), - "the render encoder joined where it joins after a write, the copy began its own: \ - {moved:?}" + (1, 2), + "the render encoder joined, the copy began its own: {moved:?}" ); } /// A four-sample pass whose color is resolved into a target set late /// (`set_color_resolve_target`, `render/late_resolve.rs`) records its pass, the resolve with it, /// at its end in the group's `VkCommandBuffer`: it joins, and so does the copy of the resolved -/// target after it, which reads every texel the resolve wrote. Where a render encoder joins no -/// group after a write, it begins one, which the copy joins. +/// target after it, which reads every texel the resolve wrote. #[test] fn a_late_resolve_records_in_its_group() { let scratch = Scratch::new("render-fold-resolve"); @@ -719,15 +675,10 @@ fn a_late_resolve_records_in_its_group() { let moved = Moved::of(&before, &lane.device.work_counts()); println!("RENDER-FOLD-RESOLVE {moved:?}"); assert_eq!(wrong_texels(&back), 0, "every resolved texel is the draw's"); - let expected = match lane.joins_after_writes() { - true => (2, 1), - false => (1, 2), - }; assert_eq!( (moved.folded, moved.begun), - expected, - "the render encoder and the copy joined the compute encoder's group, or the copy the \ - render encoder's: {moved:?}" + (2, 1), + "the render encoder and the copy joined the compute encoder's group: {moved:?}" ); } @@ -735,11 +686,8 @@ fn a_late_resolve_records_in_its_group() { /// the fill updating a fence, which ends the group, and a compute encoder after it, committed as /// failed with `encoders`: which of the five ran (each compute encoder writes the colors of a /// buffer of its own, the render encoder draws over a target the copy after the commit reads), -/// how many encoders the commit encoded again (`WorkCounts::encoders_reencoded`), and whether the -/// render encoder joined the first compute encoder's group ([`Lane::joins_after_writes`]): where -/// it does not, the first compute encoder is a group of its own, and the render encoder leads -/// the group of the next two. -fn failed_with(encoders: FailedEncoders) -> ([bool; 5], u64, bool) { +/// and how many encoders the commit encoded again (`WorkCounts::encoders_reencoded`). +fn failed_with(encoders: FailedEncoders) -> ([bool; 5], u64) { let scratch = Scratch::new("render-fold-failed"); let lane = Lane::at_call(&scratch).expect("the device imports host memory"); let queue = lane.device.new_command_queue().unwrap(); @@ -758,12 +706,7 @@ fn failed_with(encoders: FailedEncoders) -> ([bool; 5], u64, bool) { blit.end_encoding().unwrap(); lane.dispatch(&command_buffer, &outputs[4]); let moved = Moved::of(&before, &lane.device.work_counts()); - let joins = lane.joins_after_writes(); - let expected = match joins { - true => (3, 2), - false => (2, 3), - }; - assert_eq!((moved.folded, moved.begun), expected, "{moved:?}"); + assert_eq!((moved.folded, moved.begun), (3, 2), "{moved:?}"); let failure = CommitFailure { code: 2, encoders, @@ -786,43 +729,31 @@ fn failed_with(encoders: FailedEncoders) -> ([bool; 5], u64, bool) { _ => words_of(&outputs[at]).iter().any(|&word| word != 0), }; let reencoded = after.encoders_reencoded - before.encoders_reencoded; - let ran = [ran(0), ran(1), ran(2), ran(3), ran(4)]; - println!("RENDER-FOLD-FAILED {moved:?} ran {ran:?} reencoded {reencoded} joins {joins}"); - (ran, reencoded, joins) + ([ran(0), ran(1), ran(2), ran(3), ran(4)], reencoded) } /// A failed set that names a group's render encoder fails it alone: the group's other three are -/// encoded again apart at the commit (the two after it, of the group it leads, where it joins no -/// group after a write), and the encoder after it runs. +/// encoded again apart at the commit, and the encoder after it runs. #[test] fn a_failed_render_encoder_inside_a_group_fails_alone() { let set = FailedEncoders::Set(BTreeSet::from([1])); - let (ran, reencoded, joins) = failed_with(set); - assert_eq!(ran, [true, false, true, true, true]); - assert_eq!(reencoded, if joins { 3 } else { 2 }); + assert_eq!(failed_with(set), ([true, false, true, true, true], 3)); } /// A failed set that names the compute encoder before a group's render encoder fails it alone: -/// the render encoder is encoded again from its log, apart, with the other two. Where it joins -/// no group after a write, the failed encoder is a group of its own, and nothing is encoded -/// again. +/// the render encoder is encoded again from its log, apart, with the other two. #[test] fn a_failed_encoder_before_a_render_encoder_of_its_group_fails_alone() { let set = FailedEncoders::Set(BTreeSet::from([0])); - let (ran, reencoded, joins) = failed_with(set); - assert_eq!(ran, [false, true, true, true, true]); - assert_eq!(reencoded, if joins { 3 } else { 0 }); + assert_eq!(failed_with(set), ([false, true, true, true, true], 3)); } /// A first failed encoder past a group's render encoder fails from there on: the compute and -/// render encoders before it are encoded again apart at the commit, and run (the render encoder -/// alone, which leads the failed encoder's group, where it joins no group after a write). +/// render encoders before it are encoded again apart at the commit, and run. #[test] fn a_first_failed_encoder_after_a_render_encoder_runs_it() { let from = FailedEncoders::From(2); - let (ran, reencoded, joins) = failed_with(from); - assert_eq!(ran, [true, true, false, false, false]); - assert_eq!(reencoded, if joins { 2 } else { 1 }); + assert_eq!(failed_with(from), ([true, true, false, false, false], 2)); } /// A compute encoder, a render encoder whose pass records at its end and a compute encoder, of @@ -830,9 +761,7 @@ fn a_first_failed_encoder_after_a_render_encoder_runs_it() { /// submission check that fails the render encoder's, the commit encodes them again apart /// (`State::split_failure`; the pass not where the check failed it first), as the group's /// `VkCommandBuffer` holds commands of each: the pass runs nothing and the dispatches around it -/// run, as on Metal; the check sees each submission once. Where a render encoder joins no group -/// after a write, the first compute encoder is a group of its own and the render encoder leads -/// the second's, which the commit encodes again apart. +/// run, as on Metal; the check sees each submission once. #[test] fn a_check_failing_a_group_s_render_pass_fails_it_alone() { let scratch = Scratch::new("render-fold-checked"); @@ -846,12 +775,7 @@ fn a_check_failing_a_group_s_render_pass_fails_it_alone() { lane.draw(&command_buffer, &target, LoadAction::DontCare, &lane.colors); lane.dispatch(&command_buffer, &outputs[2]); let moved = Moved::of(&before, &lane.device.work_counts()); - let joins = lane.joins_after_writes(); - let expected = match joins { - true => (2, 1), - false => (1, 2), - }; - assert_eq!((moved.folded, moved.begun), expected, "{moved:?}"); + assert_eq!((moved.folded, moved.begun), (2, 1), "{moved:?}"); let seen = Arc::new(Mutex::new(Vec::new())); let noted = Arc::clone(&seen); let check: SubmissionCheck = Arc::new(move |submission: &Submission<'_>| { @@ -871,12 +795,7 @@ fn a_check_failing_a_group_s_render_pass_fails_it_alone() { // The pass's encoding again takes its place too, unless the check, on the scheduler's // thread, failed its submission first (`command_buffer/reencode.rs`, **Split at the commit**). let reencoded = after.encoders_reencoded - before.encoders_reencoded; - println!("RENDER-FOLD-CHECKED {moved:?} reencoded {reencoded}"); - let pass_too = u64::from(joins); - assert!( - (1 + pass_too..=2 + pass_too).contains(&reencoded), - "{reencoded}" - ); + assert!(matches!(reencoded, 2 | 3), "{reencoded}"); assert_eq!( *seen.lock().unwrap(), [ @@ -905,9 +824,7 @@ fn a_check_failing_a_group_s_render_pass_fails_it_alone() { /// A group of a compute encoder and a render encoder that draws with colors from a buffer over /// host pages, committed behind an event wait only the host signals, the buffer rebound to other /// pages before the signal: the rebind encodes both again (`command_buffer/reencode.rs`, groups -/// whole), refusing none, and the draw takes its colors from the new pages. Where a render -/// encoder joins no group after a write, it is a group of its own, which the rebind encodes -/// again alone. +/// whole), refusing none, and the draw takes its colors from the new pages. #[test] fn a_rebind_encodes_a_group_with_a_render_encoder_again() { // Declared before the lane, so dropped after it. @@ -967,18 +884,17 @@ fn a_rebind_encodes_a_group_with_a_render_encoder_again() { after.encoders_reencoded - before.encoders_reencoded, after.reencodes_refused - before.reencodes_refused ); - let joins = u64::from(lane.joins_after_writes()); assert_eq!( - moved.folded, joins, - "the render encoder joined the compute encoder's group where it joins after a write" + moved.folded, 1, + "the render encoder joined the compute encoder's group" ); assert_eq!( ( after.encoders_reencoded - before.encoders_reencoded, after.reencodes_refused - before.reencodes_refused ), - (1 + joins, 0), - "the rebind encoded every encoder of the render encoder's group again" + (2, 0), + "the rebind encoded both encoders of the group again" ); assert_eq!( wrong_texels(&back), diff --git a/crates/metal2vulkan-runtime/src/tracker.rs b/crates/metal2vulkan-runtime/src/tracker.rs index 082eccee6..3546d4862 100644 --- a/crates/metal2vulkan-runtime/src/tracker.rs +++ b/crates/metal2vulkan-runtime/src/tracker.rs @@ -293,6 +293,16 @@ impl UseRange { } } + /// The bytes of its key's memory an image's range lies in, as + /// [`shares_memory`](Self::shares_memory) takes them: its place's, rounded out, or all of them + /// where its place is not known. `None` for a range of bytes. + pub(super) fn image_bytes(&self) -> Option> { + match self { + UseRange::Image { place, .. } => Some(place.range().unwrap_or(0..u64::MAX)), + UseRange::Bytes(_) => None, + } + } + /// Whether this range holds all of `other`. pub(super) fn contains(&self, other: &UseRange) -> bool { match (self, other) { diff --git a/crates/metal2vulkan-validation/fixtures/public/examples/TOOLCHAIN b/crates/metal2vulkan-validation/fixtures/public/examples/TOOLCHAIN index 3977f1733..76aea5980 100644 --- a/crates/metal2vulkan-validation/fixtures/public/examples/TOOLCHAIN +++ b/crates/metal2vulkan-validation/fixtures/public/examples/TOOLCHAIN @@ -6,4 +6,5 @@ llvm-dis: Homebrew LLVM version 21.1.8 llvm-as: Homebrew LLVM version 21.1.8 # Fixtures compiled by another Metal toolchain (regen-air-fixtures.sh ...). fixture fixed_indices: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) +fixture heap_draws: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) fixture texel_rows: metal: Apple metal version 32023.922 (metalfe-32023.922.4); macosx-sdk: 27.2 (26B118) diff --git a/crates/metal2vulkan-validation/fixtures/public/examples/heap_draws.air.ll b/crates/metal2vulkan-validation/fixtures/public/examples/heap_draws.air.ll new file mode 100644 index 000000000..e9da599e8 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/examples/heap_draws.air.ll @@ -0,0 +1,170 @@ +; Generated by scripts/regen-air-fixtures from heap_draws.metal (typed pointers; xcrun metal-as reassembles it). Do not edit. +; ModuleID = '-' +source_filename = "-" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +%struct._texture_2d_t = type opaque +%struct._sampler_t = type opaque +%struct.HeapTexture = type { %"struct.metal::texture2d" } +%"struct.metal::texture2d" = type { %struct._texture_2d_t addrspace(1)* } + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +define <{ <4 x float> }> @cover_vertex(i32 noundef %0) local_unnamed_addr #0 { + %2 = shl i32 %0, 1 + %3 = and i32 %2, 2 + %4 = tail call fast float @air.convert.f.f32.u.i32(i32 %3) #7 + %5 = insertelement <2 x float> undef, float %4, i64 0 + %6 = and i32 %0, 2 + %7 = tail call fast float @air.convert.f.f32.u.i32(i32 %6) #7 + %8 = insertelement <2 x float> %5, float %7, i64 1 + %9 = fmul fast <2 x float> %8, + %10 = fadd fast <2 x float> %9, + %11 = shufflevector <2 x float> %10, <2 x float> poison, <4 x i32> + %12 = shufflevector <4 x float> %11, <4 x float> , <4 x i32> + %13 = insertvalue <{ <4 x float> }> undef, <4 x float> %12, 0 + ret <{ <4 x float> }> %13 +} + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +declare float @air.convert.f.f32.u.i32(i32) local_unnamed_addr #1 + +; Function Attrs: mustprogress nofree nounwind readonly willreturn +define <4 x float> @read_fragment(<4 x float> %0, %struct._texture_2d_t addrspace(1)* nocapture readonly %1) local_unnamed_addr #2 { + %3 = shufflevector <4 x float> %0, <4 x float> poison, <2 x i32> + %4 = tail call <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float> %3) #7 + %5 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #8 + %6 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %1, %struct._sampler_t addrspace(2)* %5, <2 x i32> %4, <2 x i32> zeroinitializer, i32 0, i32 1) #9 + %7 = extractvalue { <4 x float>, i8 } %6, 0 + ret <4 x float> %7 +} + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +declare <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float>) local_unnamed_addr #1 + +; Function Attrs: mustprogress nofree norecurse nosync nounwind readnone willreturn +define <{ <4 x float>, <4 x float> }> @two_colors_fragment(<4 x float> %0) local_unnamed_addr #3 { + ret <{ <4 x float>, <4 x float> }> <{ <4 x float> , <4 x float> }> +} + +; Function Attrs: mustprogress nofree nounwind readonly willreturn +define <4 x float> @read_argument_fragment(<4 x float> %0, %struct.HeapTexture addrspace(2)* nocapture noundef readonly align 8 dereferenceable(8) "air-buffer-no-alias" %1) local_unnamed_addr #2 { + %3 = shufflevector <4 x float> %0, <4 x float> poison, <2 x i32> + %4 = tail call <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float> %3) #7 + %5 = getelementptr inbounds %struct.HeapTexture, %struct.HeapTexture addrspace(2)* %1, i64 0, i32 0, i32 0 + %6 = load %struct._texture_2d_t addrspace(1)*, %struct._texture_2d_t addrspace(1)* addrspace(2)* %5, align 8, !tbaa !43, !alias.scope !48 + %7 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #8 + %8 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %6, %struct._sampler_t addrspace(2)* %7, <2 x i32> %4, <2 x i32> zeroinitializer, i32 0, i32 1) #9 + %9 = extractvalue { <4 x float>, i8 } %8, 0 + ret <4 x float> %9 +} + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @read_argument_kernel(%struct.HeapTexture addrspace(2)* nocapture noundef readonly align 8 dereferenceable(8) "air-buffer-no-alias" %0, i32 addrspace(1)* nocapture noundef writeonly "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #4 { + %4 = getelementptr inbounds %struct.HeapTexture, %struct.HeapTexture addrspace(2)* %0, i64 0, i32 0, i32 0 + %5 = load %struct._texture_2d_t addrspace(1)*, %struct._texture_2d_t addrspace(1)* addrspace(2)* %4, align 8, !tbaa !43, !alias.scope !51, !noalias !54 + %6 = tail call i32 @air.get_width_texture_2d(%struct._texture_2d_t addrspace(1)* nocapture readonly %5, i32 0) #9 + %7 = tail call %struct._sampler_t addrspace(2)* @air.get_read_sampler() #8 + %8 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly %5, %struct._sampler_t addrspace(2)* %7, <2 x i32> %2, <2 x i32> zeroinitializer, i32 0, i32 1) #9 + %9 = extractvalue { <4 x float>, i8 } %8, 0 + %10 = tail call i32 @air.pack.unorm4x8.v4f32(<4 x float> %9) #7 + %11 = extractelement <2 x i32> %2, i64 1 + %12 = mul i32 %6, %11 + %13 = extractelement <2 x i32> %2, i64 0 + %14 = add i32 %12, %13 + %15 = zext i32 %14 to i64 + %16 = getelementptr inbounds i32, i32 addrspace(1)* %1, i64 %15 + store i32 %10, i32 addrspace(1)* %16, align 4, !tbaa !56, !alias.scope !54, !noalias !51 + ret void +} + +; Function Attrs: mustprogress nofree nosync nounwind readnone willreturn +declare i32 @air.pack.unorm4x8.v4f32(<4 x float>) local_unnamed_addr #1 + +; Function Attrs: inaccessiblememonly mustprogress nofree nounwind readonly willreturn +declare %struct._sampler_t addrspace(2)* @air.get_read_sampler() local_unnamed_addr #5 + +; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(%struct._texture_2d_t addrspace(1)* nocapture readonly, %struct._sampler_t addrspace(2)*, <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #6 + +; Function Attrs: argmemonly mustprogress nofree nounwind readonly willreturn +declare i32 @air.get_width_texture_2d(%struct._texture_2d_t addrspace(1)* nocapture readonly, i32) local_unnamed_addr #6 + +attributes #0 = { mustprogress nofree nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { mustprogress nofree nosync nounwind readnone willreturn } +attributes #2 = { mustprogress nofree nounwind readonly willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { mustprogress nofree norecurse nosync nounwind readnone willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #4 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #5 = { inaccessiblememonly mustprogress nofree nounwind readonly willreturn } +attributes #6 = { argmemonly mustprogress nofree nounwind readonly willreturn } +attributes #7 = { nounwind readnone willreturn } +attributes #8 = { inaccessiblememonly nounwind readonly willreturn } +attributes #9 = { argmemonly nounwind readonly willreturn } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.vertex = !{!9} +!air.fragment = !{!14, !20, !26} +!air.kernel = !{!31} +!air.compile_options = !{!37, !38, !39} +!llvm.ident = !{!40} +!air.version = !{!41} +!air.language_version = !{!42} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{<{ <4 x float> }> (i32)* @cover_vertex, !10, !12} +!10 = !{!11} +!11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!12 = !{!13} +!13 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"id"} +!14 = !{<4 x float> (<4 x float>, %struct._texture_2d_t addrspace(1)*)* @read_fragment, !15, !17} +!15 = !{!16} +!16 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!17 = !{!18, !19} +!18 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!19 = !{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"source"} +!20 = !{<{ <4 x float>, <4 x float> }> (<4 x float>)* @two_colors_fragment, !21, !24} +!21 = !{!22, !23} +!22 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"first"} +!23 = !{!"air.render_target", i32 1, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"second"} +!24 = !{!25} +!25 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!26 = !{<4 x float> (<4 x float>, %struct.HeapTexture addrspace(2)*)* @read_argument_fragment, !15, !27} +!27 = !{!18, !28} +!28 = !{i32 1, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !29, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"HeapTexture", !"air.arg_name", !"arguments"} +!29 = !{i32 0, i32 8, i32 0, !"texture2d", !"source", !"air.indirect_argument", !30} +!30 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"source"} +!31 = !{void (%struct.HeapTexture addrspace(2)*, i32 addrspace(1)*, <2 x i32>)* @read_argument_kernel, !32, !33} +!32 = !{} +!33 = !{!34, !35, !36} +!34 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !29, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"HeapTexture", !"air.arg_name", !"arguments"} +!35 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!36 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"at"} +!37 = !{!"air.compile.denorms_disable"} +!38 = !{!"air.compile.fast_math_enable"} +!39 = !{!"air.compile.framebuffer_fetch_enable"} +!40 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!41 = !{i32 2, i32 8, i32 0} +!42 = !{!"Metal", i32 4, i32 0, i32 0} +!43 = !{!44, !45, i64 0} +!44 = !{!"_ZTSN5metal9texture2dIfLNS_6accessE1ELNS_16memory_coherenceE0EvEE", !45, i64 0} +!45 = !{!"__metal_texture_2d_t", !46, i64 0} +!46 = !{!"omnipotent char", !47, i64 0} +!47 = !{!"Simple C++ TBAA"} +!48 = !{!49} +!49 = distinct !{!49, !50, !"air-alias-scope-arg(1)"} +!50 = distinct !{!50, !"air-alias-scopes(read_argument_fragment)"} +!51 = !{!52} +!52 = distinct !{!52, !53, !"air-alias-scope-arg(0)"} +!53 = distinct !{!53, !"air-alias-scopes(read_argument_kernel)"} +!54 = !{!55} +!55 = distinct !{!55, !53, !"air-alias-scope-arg(1)"} +!56 = !{!57, !57, i64 0} +!57 = !{!"int", !46, i64 0} diff --git a/crates/metal2vulkan-validation/fixtures/public/examples/heap_draws.ll b/crates/metal2vulkan-validation/fixtures/public/examples/heap_draws.ll new file mode 100644 index 000000000..c9c3d2a45 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/examples/heap_draws.ll @@ -0,0 +1,168 @@ +; Generated by scripts/regen-air-fixtures from heap_draws.metal (llvm-dis of heap_draws.air). Do not edit. +; ModuleID = '' +source_filename = "-" +target datalayout = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32" +target triple = "air64_v28-apple-macosx26.0.0" + +%struct.HeapTexture = type { %"struct.metal::texture2d" } +%"struct.metal::texture2d" = type { ptr addrspace(1) } + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +define <{ <4 x float> }> @cover_vertex(i32 noundef %0) local_unnamed_addr #0 { + %2 = shl i32 %0, 1 + %3 = and i32 %2, 2 + %4 = tail call fast float @air.convert.f.f32.u.i32(i32 %3) #7 + %5 = insertelement <2 x float> undef, float %4, i64 0 + %6 = and i32 %0, 2 + %7 = tail call fast float @air.convert.f.f32.u.i32(i32 %6) #7 + %8 = insertelement <2 x float> %5, float %7, i64 1 + %9 = fmul fast <2 x float> %8, splat (float 2.000000e+00) + %10 = fadd fast <2 x float> %9, splat (float -1.000000e+00) + %11 = shufflevector <2 x float> %10, <2 x float> poison, <4 x i32> + %12 = shufflevector <4 x float> %11, <4 x float> , <4 x i32> + %13 = insertvalue <{ <4 x float> }> undef, <4 x float> %12, 0 + ret <{ <4 x float> }> %13 +} + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +declare float @air.convert.f.f32.u.i32(i32) local_unnamed_addr #1 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(read) +define <4 x float> @read_fragment(<4 x float> %0, ptr addrspace(1) readonly captures(none) %1) local_unnamed_addr #2 { + %3 = shufflevector <4 x float> %0, <4 x float> poison, <2 x i32> + %4 = tail call <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float> %3) #7 + %5 = tail call ptr addrspace(2) @air.get_read_sampler() #8 + %6 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %1, ptr addrspace(2) %5, <2 x i32> %4, <2 x i32> zeroinitializer, i32 0, i32 1) #9 + %7 = extractvalue { <4 x float>, i8 } %6, 0 + ret <4 x float> %7 +} + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +declare <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float>) local_unnamed_addr #1 + +; Function Attrs: mustprogress nofree norecurse nosync nounwind willreturn memory(none) +define <{ <4 x float>, <4 x float> }> @two_colors_fragment(<4 x float> %0) local_unnamed_addr #3 { + ret <{ <4 x float>, <4 x float> }> <{ <4 x float> , <4 x float> }> +} + +; Function Attrs: mustprogress nofree nounwind willreturn memory(read) +define <4 x float> @read_argument_fragment(<4 x float> %0, ptr addrspace(2) noundef readonly align 8 captures(none) dereferenceable(8) "air-buffer-no-alias" %1) local_unnamed_addr #2 { + %3 = shufflevector <4 x float> %0, <4 x float> poison, <2 x i32> + %4 = tail call <2 x i32> @air.convert.u.v2i32.f.v2f32(<2 x float> %3) #7 + %5 = getelementptr inbounds %struct.HeapTexture, ptr addrspace(2) %1, i64 0, i32 0, i32 0 + %6 = load ptr addrspace(1), ptr addrspace(2) %5, align 8, !tbaa !43, !alias.scope !48 + %7 = tail call ptr addrspace(2) @air.get_read_sampler() #8 + %8 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %6, ptr addrspace(2) %7, <2 x i32> %4, <2 x i32> zeroinitializer, i32 0, i32 1) #9 + %9 = extractvalue { <4 x float>, i8 } %8, 0 + ret <4 x float> %9 +} + +; Function Attrs: mustprogress nofree nounwind willreturn +define void @read_argument_kernel(ptr addrspace(2) noundef readonly align 8 captures(none) dereferenceable(8) "air-buffer-no-alias" %0, ptr addrspace(1) noundef writeonly captures(none) "air-buffer-no-alias" %1, <2 x i32> noundef %2) local_unnamed_addr #4 { + %4 = getelementptr inbounds %struct.HeapTexture, ptr addrspace(2) %0, i64 0, i32 0, i32 0 + %5 = load ptr addrspace(1), ptr addrspace(2) %4, align 8, !tbaa !43, !alias.scope !51, !noalias !54 + %6 = tail call i32 @air.get_width_texture_2d(ptr addrspace(1) readonly captures(none) %5, i32 0) #9 + %7 = tail call ptr addrspace(2) @air.get_read_sampler() #8 + %8 = tail call { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none) %5, ptr addrspace(2) %7, <2 x i32> %2, <2 x i32> zeroinitializer, i32 0, i32 1) #9 + %9 = extractvalue { <4 x float>, i8 } %8, 0 + %10 = tail call i32 @air.pack.unorm4x8.v4f32(<4 x float> %9) #7 + %11 = extractelement <2 x i32> %2, i64 1 + %12 = mul i32 %6, %11 + %13 = extractelement <2 x i32> %2, i64 0 + %14 = add i32 %12, %13 + %15 = zext i32 %14 to i64 + %16 = getelementptr inbounds i32, ptr addrspace(1) %1, i64 %15 + store i32 %10, ptr addrspace(1) %16, align 4, !tbaa !56, !alias.scope !54, !noalias !51 + ret void +} + +; Function Attrs: mustprogress nofree nosync nounwind willreturn memory(none) +declare i32 @air.pack.unorm4x8.v4f32(<4 x float>) local_unnamed_addr #1 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(inaccessiblemem: read) +declare ptr addrspace(2) @air.get_read_sampler() local_unnamed_addr #5 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read) +declare { <4 x float>, i8 } @air.read_texture_2d.v4f32(ptr addrspace(1) readonly captures(none), ptr addrspace(2), <2 x i32>, <2 x i32>, i32, i32) local_unnamed_addr #6 + +; Function Attrs: mustprogress nofree nounwind willreturn memory(argmem: read) +declare i32 @air.get_width_texture_2d(ptr addrspace(1) readonly captures(none), i32) local_unnamed_addr #6 + +attributes #0 = { mustprogress nofree nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="0" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #1 = { mustprogress nofree nosync nounwind willreturn memory(none) } +attributes #2 = { mustprogress nofree nounwind willreturn memory(read) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #3 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #4 = { mustprogress nofree nounwind willreturn "approx-func-fp-math"="true" "frame-pointer"="all" "min-legal-vector-width"="128" "no-builtins" "no-infs-fp-math"="true" "no-nans-fp-math"="true" "no-signed-zeros-fp-math"="true" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "unsafe-fp-math"="true" } +attributes #5 = { mustprogress nofree nounwind willreturn memory(inaccessiblemem: read) } +attributes #6 = { mustprogress nofree nounwind willreturn memory(argmem: read) } +attributes #7 = { nounwind willreturn memory(none) } +attributes #8 = { nounwind willreturn memory(inaccessiblemem: read) } +attributes #9 = { nounwind willreturn memory(argmem: read) } + +!llvm.module.flags = !{!0, !1, !2, !3, !4, !5, !6, !7, !8} +!air.vertex = !{!9} +!air.fragment = !{!14, !20, !26} +!air.kernel = !{!31} +!air.compile_options = !{!37, !38, !39} +!llvm.ident = !{!40} +!air.version = !{!41} +!air.language_version = !{!42} + +!0 = !{i32 2, !"SDK Version", [2 x i32] [i32 27, i32 2]} +!1 = !{i32 1, !"wchar_size", i32 4} +!2 = !{i32 7, !"frame-pointer", i32 2} +!3 = !{i32 7, !"air.max_device_buffers", i32 31} +!4 = !{i32 7, !"air.max_constant_buffers", i32 31} +!5 = !{i32 7, !"air.max_threadgroup_buffers", i32 31} +!6 = !{i32 7, !"air.max_textures", i32 128} +!7 = !{i32 7, !"air.max_read_write_textures", i32 8} +!8 = !{i32 7, !"air.max_samplers", i32 16} +!9 = !{ptr @cover_vertex, !10, !12} +!10 = !{!11} +!11 = !{!"air.position", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!12 = !{!13} +!13 = !{i32 0, !"air.vertex_id", !"air.arg_type_name", !"uint", !"air.arg_name", !"id"} +!14 = !{ptr @read_fragment, !15, !17} +!15 = !{!16} +!16 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"} +!17 = !{!18, !19} +!18 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"} +!19 = !{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"source"} +!20 = !{ptr @two_colors_fragment, !21, !24} +!21 = !{!22, !23} +!22 = !{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"first"} +!23 = !{!"air.render_target", i32 1, i32 0, !"air.arg_type_name", !"float4", !"air.arg_name", !"second"} +!24 = !{!25} +!25 = !{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position", !"air.arg_unused"} +!26 = !{ptr @read_argument_fragment, !15, !27} +!27 = !{!18, !28} +!28 = !{i32 1, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !29, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"HeapTexture", !"air.arg_name", !"arguments"} +!29 = !{i32 0, i32 8, i32 0, !"texture2d", !"source", !"air.indirect_argument", !30} +!30 = !{i32 0, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.read", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"source"} +!31 = !{ptr @read_argument_kernel, !32, !33} +!32 = !{} +!33 = !{!34, !35, !36} +!34 = !{i32 0, !"air.indirect_buffer", !"air.buffer_size", i32 8, !"air.location_index", i32 0, i32 1, !"air.read", !"air.address_space", i32 2, !"air.struct_type_info", !29, !"air.arg_type_size", i32 8, !"air.arg_type_align_size", i32 8, !"air.arg_type_name", !"HeapTexture", !"air.arg_name", !"arguments"} +!35 = !{i32 1, !"air.buffer", !"air.location_index", i32 1, i32 1, !"air.read_write", !"air.address_space", i32 1, !"air.arg_type_size", i32 4, !"air.arg_type_align_size", i32 4, !"air.arg_type_name", !"uint", !"air.arg_name", !"out"} +!36 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint2", !"air.arg_name", !"at"} +!37 = !{!"air.compile.denorms_disable"} +!38 = !{!"air.compile.fast_math_enable"} +!39 = !{!"air.compile.framebuffer_fetch_enable"} +!40 = !{!"Apple metal version 32023.922 (metalfe-32023.922.4)"} +!41 = !{i32 2, i32 8, i32 0} +!42 = !{!"Metal", i32 4, i32 0, i32 0} +!43 = !{!44, !45, i64 0} +!44 = !{!"_ZTSN5metal9texture2dIfLNS_6accessE1ELNS_16memory_coherenceE0EvEE", !45, i64 0} +!45 = !{!"__metal_texture_2d_t", !46, i64 0} +!46 = !{!"omnipotent char", !47, i64 0} +!47 = !{!"Simple C++ TBAA"} +!48 = !{!49} +!49 = distinct !{!49, !50, !"air-alias-scope-arg(1)"} +!50 = distinct !{!50, !"air-alias-scopes(read_argument_fragment)"} +!51 = !{!52} +!52 = distinct !{!52, !53, !"air-alias-scope-arg(0)"} +!53 = distinct !{!53, !"air-alias-scopes(read_argument_kernel)"} +!54 = !{!55} +!55 = distinct !{!55, !53, !"air-alias-scope-arg(1)"} +!56 = !{!57, !57, i64 0} +!57 = !{!"int", !46, i64 0} diff --git a/crates/metal2vulkan-validation/fixtures/public/examples/heap_draws.metal b/crates/metal2vulkan-validation/fixtures/public/examples/heap_draws.metal new file mode 100644 index 000000000..452e28d17 --- /dev/null +++ b/crates/metal2vulkan-validation/fixtures/public/examples/heap_draws.metal @@ -0,0 +1,59 @@ +// Owned fixture: the functions the metal2vulkan-validation crate's heap textures lane draws +// with (src/runtime_lane/heap_textures.rs): one triangle over the whole target, and fragments that +// read a texture under them, directly or through an argument buffer, or write two colors, and a +// kernel that reads a texture through an argument buffer. Written from scratch for it; +// `scripts/regen-air-fixtures/regen-air-fixtures.sh --dir examples heap_draws` compiles it. No +// translator sweep reads this directory. +#include +using namespace metal; + +struct Covered { + float4 position [[position]]; +}; + +// Vertex `id` of one triangle that covers the whole target: (-1, -1), (3, -1) and (-1, 3). +vertex Covered cover_vertex(uint id [[vertex_id]]) { + float2 corner = float2(float((id << 1) & 2), float(id & 2)); + Covered out; + out.position = float4(corner * 2.0 - 1.0, 0.0, 1.0); + return out; +} + +// The texel of `source` under each fragment. +fragment float4 read_fragment(Covered in [[stage_in]], + texture2d source [[texture(0)]]) { + return source.read(uint2(in.position.xy)); +} + +struct TwoColors { + float4 first [[color(0)]]; + float4 second [[color(1)]]; +}; + +// One color into each attachment: for a pipeline whose first attachment writes nothing. +fragment TwoColors two_colors_fragment(Covered in [[stage_in]]) { + TwoColors out; + out.first = float4(1.0, 0.0, 1.0, 1.0); + out.second = float4(0.25, 0.5, 0.75, 1.0); + return out; +} + +// The texture the functions below read, at field 0 of their argument buffer: a heap's texture an +// encoder made resident with `useHeap:`, bound at no texture slot. +struct HeapTexture { + texture2d source [[id(0)]]; +}; + +// The texel of the argument buffer's texture under each fragment. +fragment float4 read_argument_fragment(Covered in [[stage_in]], + constant HeapTexture &arguments [[buffer(0)]]) { + return arguments.source.read(uint2(in.position.xy)); +} + +// Each texel of the argument buffer's texture into `out`, packed `RGBA8Unorm`, rows packed. +kernel void read_argument_kernel(constant HeapTexture &arguments [[buffer(0)]], + device uint *out [[buffer(1)]], + uint2 at [[thread_position_in_grid]]) { + uint width = arguments.source.get_width(); + out[at.y * width + at.x] = pack_float_to_unorm4x8(arguments.source.read(at)); +} diff --git a/crates/metal2vulkan-validation/src/runtime_lane/heap_textures.rs b/crates/metal2vulkan-validation/src/runtime_lane/heap_textures.rs index 35ea93e07..5cd238b07 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/heap_textures.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/heap_textures.rs @@ -31,7 +31,7 @@ use super::degrade_notices::counts; use super::heap_layouts::HEAP_LAYOUTS; use super::heap_metal_sizes::STACKED_NIL_ALIGNMENT; use super::host_memory::on_device_with; -use super::host_memory::{gpu_fill, gpu_read, on_device, run}; +use super::host_memory::{gpu_fill, gpu_read, host_page, no_copy, on_device, run, Mapping}; use super::presenting::Adopted; use super::textures::{no_texture_alone, pattern, texel_bytes}; use super::{ @@ -46,12 +46,14 @@ use metal2vulkan::device::{DriverFact, HeapCompressionPolicy}; use metal2vulkan::error::{Feature, LinearNeed, Needs}; use metal2vulkan::metal::format::{copies_only, footprint, is_depth_stencil, Footprint}; use metal2vulkan::metal::{ - IndirectCommandType, PixelFormat, PrimitiveType, RenderStages, ResourceUsage, TextureType, - TextureUsage, + ColorWriteMask, IndirectCommandType, PixelFormat, PrimitiveType, RenderStages, ResourceUsage, + TextureType, TextureUsage, +}; +use metal2vulkan::pipeline::{ + ColorAttachmentDescriptor, ComputePipelineDescriptor, RenderPipelineDescriptor, StageSource, }; -use metal2vulkan::pipeline::{RenderPipelineDescriptor, StageSource}; use metal2vulkan::vk::{DriverId, NumericFormat}; -use metal2vulkan_devtools::{engine_dir, llvm_assemble}; +use metal2vulkan_devtools::{engine_dir, fixtures_dir, llvm_assemble}; use metal2vulkan_runtime::{ BlitOption, Buffer, CommandQueue, CpuCacheMode, Degradation, Device, Error, HazardTrackingMode, Heap, HeapDescriptor, HeapProblem, HeapType, IndirectCommandBufferDescriptor, Invalid, @@ -878,6 +880,303 @@ fn a_buffer_write_shows_in_an_overlapping_texture() { layer_reported_nothing_at_all(&messages); } +/// How a command uses a heap's texture after a blit encoder's write of the buffer over its bytes, +/// the two consecutive encoders of one command buffer +/// ([`blit_write_then_texture_use`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum TextureUse { + /// A render encoder's draw reads the texture's texels (`read_fragment`) into a target loaded + /// `DontCare`: the pass records at its end, its draw in a secondary command buffer. + ReadAtEnd, + /// The texture is a render encoder's first color, loaded and stored, which the draw leaves + /// (its write mask none), beside a second loaded `DontCare` that the draw writes + /// (`two_colors_fragment`): the pass records at its end. + LoadedAtEnd, + /// A render encoder's draw reads the texture's texels into a target cleared and stored: its + /// first instance records inline, from its draw on. + ReadInline, + /// As [`ReadAtEnd`](Self::ReadAtEnd), the draw reading the texture through an argument buffer + /// (`read_argument_fragment`), its encoder making the heap resident (`use_heap`) and binding + /// the texture at no slot. + ReadThroughHeapAtEnd, + /// A compute encoder's dispatch reads the texture's texels into a buffer through an argument + /// buffer (`read_argument_kernel`), its encoder making the heap resident (`use_heap`) and + /// binding the texture at no slot. + DispatchedThroughHeap, +} + +/// A blit encoder's copy into a heap's buffer, then an encoder's use of a texture over the same +/// bytes, in one command buffer: every texel the command reads, or loads and stores, is the +/// copy's, in a tracked `Shared` and a tracked `Private` placement heap, a 64x64 `RGBA8Unorm` +/// texture of sampled and render-target usage at offset 0 and a buffer of its answered size there. +/// The copy writes one texel's bytes into every word, so every texel the texture reads is that +/// texel whatever the device's layout; the blit before it wrote `texel_pattern`, none of whose +/// texels it is. The device has a buffer over host pages, so its render encoders log their calls +/// and may join the blit encoder's group of encoders (`WorkCounts::encoders_folded`), as its +/// compute encoders do. +/// +/// A pass that records at its end joins the group, as a compute encoder does; where the device's +/// driver misses, in a use of an image, a write through a buffer over its memory recorded before +/// it in the same `VkCommandBuffer` (`DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`), +/// the pass or the dispatch goes in a new one (`WorkCounts::command_buffers_split_at_aliases`, at +/// least one), whether its draw reads the texture bound or through the heap made resident, or its +/// pass loads it; elsewhere none splits. A pass whose first instance records inline joins no +/// group (`WorkCounts::render_passes_begun_inline`), its draws in a `VkCommandBuffer` of its own: +/// none splits anywhere. `HEAPTEX use` lines print the counts. +fn blit_write_then_texture_use(used: TextureUse) { + const SIDE: u64 = 64; + let messages = Messages::default(); + let cache = ScratchCache::new().unwrap(); + { + let device = &validated_device(TEST_DEVICE, &messages, cache.path()).unwrap(); + let pages = Mapping::anonymous(host_page()); + // SAFETY: the mapping outlives the buffer, dropped before it with the device, and no + // command uses it. + let over_pages = unsafe { + no_copy( + device, + pages.pointer(), + host_page(), + ResourceOptions::shared(), + None, + ) + }; + let _over_pages = match over_pages { + Ok(buffer) => buffer, + Err(error @ Error::Unsupported(_)) => { + eprintln!("HEAPTEX use {used:?}: no buffer over host pages, {error:?}"); + return; + } + Err(error) => panic!("new_buffer_with_bytes_no_copy: {error:?}"), + }; + let splitting = (device.properties().driver_facts) + .contains(&DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer); + let bitcode = llvm_assemble(&fixtures_dir().join("examples/heap_draws.ll")).unwrap(); + let library = device.new_library_with_air(&bitcode).unwrap(); + let function = |name: &str| { + StageSource::Function( + library + .new_function_with_name(name) + .unwrap() + .function_descriptor(), + ) + }; + let rgba = PixelFormat::RGBA8Unorm; + let mut descriptor = RenderPipelineDescriptor::new(function("cover_vertex")); + descriptor.color_attachments[0] = Some(ColorAttachmentDescriptor::new(rgba)); + // The function that uses the texture: the fragment function, or the kernel. + let user = match used { + TextureUse::ReadAtEnd | TextureUse::ReadInline => "read_fragment", + TextureUse::LoadedAtEnd => { + let mut first = ColorAttachmentDescriptor::new(rgba); + first.write_mask = ColorWriteMask::NONE; + descriptor.color_attachments[0] = Some(first); + descriptor.color_attachments[1] = Some(ColorAttachmentDescriptor::new(rgba)); + "two_colors_fragment" + } + TextureUse::ReadThroughHeapAtEnd => "read_argument_fragment", + TextureUse::DispatchedThroughHeap => "read_argument_kernel", + }; + // A render state for a draw, a compute state for a dispatch. + let (render, compute) = match used { + TextureUse::DispatchedThroughHeap => { + let descriptor = ComputePipelineDescriptor::new(function(user)); + let compute = + device.new_compute_pipeline_state(&descriptor, &PipelineOptions::default()); + (None, Some(compute.unwrap())) + } + _ => { + descriptor.fragment = Some(function(user)); + let render = + device.new_render_pipeline_state(&descriptor, &PipelineOptions::default()); + (Some(render.unwrap()), None) + } + }; + let queue = device.new_command_queue().unwrap(); + let before = device.work_counts(); + let mut made = 0; + for storage in [StorageMode::Shared, StorageMode::Private] { + let options = ResourceOptions::new( + storage, + CpuCacheMode::DefaultCache, + HazardTrackingMode::Tracked, + ); + let heap = heap(device, HeapType::Placement, 1 << 20, options); + let mut descriptor = rgba8(SIDE, options); + descriptor.usage = TextureUsage::SHADER_READ | TextureUsage::RENDER_TARGET; + let what = format!("{used:?} {storage:?} {SIDE}x{SIDE}"); + let texture = match heap.new_texture_at_offset(&descriptor, 0) { + Ok(texture) => texture, + Err(error) if tiling_refusal(&error).is_some() => { + eprintln!("HEAPTEX use {what}: refused {error:?}"); + continue; + } + Err(error) => panic!("{what}: {error:?}"), + }; + made += 1; + let size = device + .heap_texture_size_and_align(&descriptor) + .unwrap() + .size; + let buffer = heap.new_buffer_at_offset(size, options, 0).unwrap(); + let pattern = texel_pattern(SIDE); + let source = staged(device, &pattern); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_texture( + &source, + 0, + SIDE * 4, + SIDE * SIDE * 4, + Size::new(SIDE, SIDE, 1), + &texture, + 0, + 0, + Origin::new(0, 0, 0), + BlitOption::None, + ) + .unwrap(); + blit.end_encoding().unwrap(); + run(&command_buffer); + assert_eq!(texels(&queue, &texture, SIDE), pattern, "{what}"); + // One texel, none of the pattern's (whose alpha is 0xCD), in every word. + const WRITTEN: [u8; 4] = [0x12, 0x34, 0x56, 0x78]; + let words = staged(device, &WRITTEN.repeat((size / 4) as usize)); + let mut target = rgba8(SIDE, ResourceOptions::private()); + target.usage = TextureUsage::RENDER_TARGET; + let target = device.new_texture(&target).unwrap(); + // The texture's ID, the argument buffer's one field. + let arguments = staged(device, &texture.gpu_resource_id().0.to_le_bytes()); + let out = device + .new_buffer(SIDE * SIDE * 4, ResourceOptions::shared()) + .unwrap(); + let command_buffer = queue.command_buffer().unwrap(); + let mut blit = command_buffer.blit_command_encoder().unwrap(); + blit.copy_from_buffer_to_buffer(&words, 0, &buffer, 0, size) + .unwrap(); + blit.end_encoding().unwrap(); + if let Some(compute) = &compute { + let mut encoder = command_buffer.compute_command_encoder().unwrap(); + encoder.set_compute_pipeline_state(compute).unwrap(); + encoder.use_heap(&heap).unwrap(); + encoder.set_buffer(Some(&arguments), 0, 0).unwrap(); + encoder.set_buffer(Some(&out), 0, 1).unwrap(); + encoder + .dispatch_threads(Size::new(SIDE, SIDE, 1), Size::new(16, 16, 1)) + .unwrap(); + encoder.end_encoding().unwrap(); + } else if let Some(render) = &render { + let mut pass = RenderPassDescriptor::new(); + let (first, load) = match used { + TextureUse::LoadedAtEnd => (&texture, LoadAction::Load), + TextureUse::ReadInline => (&target, LoadAction::Clear), + _ => (&target, LoadAction::DontCare), + }; + let color = &mut pass.color_attachments[0]; + color.texture = Some(first.clone()); + color.load_action = load; + color.store_action = StoreAction::Store; + if used == TextureUse::LoadedAtEnd { + let color = &mut pass.color_attachments[1]; + color.texture = Some(target.clone()); + color.load_action = LoadAction::DontCare; + color.store_action = StoreAction::Store; + } + let mut encoder = command_buffer.render_command_encoder(&pass).unwrap(); + encoder.set_render_pipeline_state(render).unwrap(); + match used { + TextureUse::ReadAtEnd | TextureUse::ReadInline => { + encoder.set_fragment_texture(Some(&texture), 0).unwrap(); + } + TextureUse::ReadThroughHeapAtEnd => { + encoder.use_heap(&heap, RenderStages::FRAGMENT).unwrap(); + encoder.set_fragment_buffer(Some(&arguments), 0, 0).unwrap(); + } + TextureUse::LoadedAtEnd | TextureUse::DispatchedThroughHeap => {} + } + encoder + .draw_primitives(PrimitiveType::Triangle, 0, 3, 1, 0) + .unwrap(); + encoder.end_encoding().unwrap(); + } + run(&command_buffer); + let read = match used { + TextureUse::LoadedAtEnd => texels(&queue, &texture, SIDE), + TextureUse::DispatchedThroughHeap => gpu_read(&queue, &out, 0..SIDE * SIDE * 4), + _ => texels(&queue, &target, SIDE), + }; + let written = (read.as_chunks::<4>().0.iter()) + .filter(|&&texel| texel == WRITTEN) + .count(); + eprintln!( + "HEAPTEX use {what}: {written} of {} texels the copy's", + SIDE * SIDE + ); + assert_eq!( + written, + (SIDE * SIDE) as usize, + "{what}: texels the command took from before the copy" + ); + } + let after = device.work_counts(); + let split = + after.command_buffers_split_at_aliases - before.command_buffers_split_at_aliases; + let folded = after.encoders_folded - before.encoders_folded; + let inline = after.render_passes_begun_inline - before.render_passes_begun_inline; + eprintln!( + "HEAPTEX use {used:?}: {made} heaps, {folded} encoders folded, {inline} passes begun \ + inline, {split} command buffers split at aliases (the driver's image uses miss \ + buffer writes inside one: {splitting})" + ); + match used { + TextureUse::ReadInline => { + assert_eq!(inline, made, "each pass's first instance recorded inline"); + assert_eq!(split, 0, "an inline pass joins no group"); + } + _ => { + assert_eq!(inline, 0, "a pass recorded at its end, or none"); + assert!(folded >= made, "each encoder joined the blit's group"); + assert_eq!(split > 0, splitting && made > 0); + } + } + } + layer_reported_nothing_at_all(&messages); +} + +/// [`blit_write_then_texture_use`]: a draw of a pass recorded at its end reads the texture. +#[test] +fn a_blit_write_shows_in_a_render_pass_s_use_of_an_overlapping_texture() { + blit_write_then_texture_use(TextureUse::ReadAtEnd); +} + +/// [`blit_write_then_texture_use`]: a pass recorded at its end loads and stores the texture as its +/// first color. +#[test] +fn a_blit_write_shows_in_a_render_pass_s_load_of_an_overlapping_texture() { + blit_write_then_texture_use(TextureUse::LoadedAtEnd); +} + +/// [`blit_write_then_texture_use`]: a draw of a pass whose first instance records inline reads the +/// texture. +#[test] +fn a_blit_write_shows_in_an_inline_render_pass_s_use_of_an_overlapping_texture() { + blit_write_then_texture_use(TextureUse::ReadInline); +} + +/// [`blit_write_then_texture_use`]: a draw of a pass recorded at its end reads the texture through +/// an argument buffer, its heap made resident. +#[test] +fn a_blit_write_shows_in_a_render_pass_s_use_of_an_overlapping_texture_through_its_heap() { + blit_write_then_texture_use(TextureUse::ReadThroughHeapAtEnd); +} + +/// [`blit_write_then_texture_use`]: a dispatch reads the texture through an argument buffer, its +/// heap made resident. +#[test] +fn a_blit_write_shows_in_a_dispatch_s_use_of_an_overlapping_texture_through_its_heap() { + blit_write_then_texture_use(TextureUse::DispatchedThroughHeap); +} + /// Under the default `HeapCompressionPolicy::Compressed`, where the device's driver may keep a /// compressed image's texels apart from its memory /// (`DriverFact::CompressedImagesHideAliasedWrites`: ANV), a heap's `RGBA8Unorm` texture that Metal diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index a0f038912..4b5292985 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523; /// changes no behaviour, and then updates that hash alone with the commit saying why, or changes /// behaviour and also bumps this version. The commit that bumps it says what changed; this comment /// keeps no history. -pub const RUNTIME_VERSION: u32 = 2332; +pub const RUNTIME_VERSION: u32 = 2333; /// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex, /// of the manifest, the build script, and exactly the files the crate roots' module tree compiles diff --git a/docs/API.md b/docs/API.md index c23451e7c..d5bb4814e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -5557,9 +5557,10 @@ each item named states the rule in full. joins none. On a device whose driver's image uses miss a write through a buffer over their memory recorded before them in the same `VkCommandBuffer` (`DriverFact::ImageUsesMissBufferWritesInOneCommandBuffer`: NVIDIA's 620.70.06 on the RTX - 3090), a render encoder joins no group whose encoders wrote a buffer's bytes, and a command that - uses an image over bytes written before it in its `VkCommandBuffer` goes on in a new one, a - grouped encoder's in its own (`WorkCounts::command_buffers_split_at_aliases`). A failure that + 3090), a command that uses an image over bytes written before it in its `VkCommandBuffer` goes + on in a new one, a grouped encoder's in its own (`WorkCounts::command_buffers_split_at_aliases`); + a grouped render encoder's pass goes on in a new one before it where the pass or one of its + draws uses such an image. A failure that fails some of such a group's encoders and not the others (a `FailedEncoders::From(n)` whose `n` lies inside it, a `FailedEncoders::Set` that names some of them, a fault or a recording failure at one)