diff --git a/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs b/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs index cfe583073..4fbbff2e4 100644 --- a/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs +++ b/crates/metal2vulkan-runtime/src/pipeline/creation_log.rs @@ -17,8 +17,10 @@ //! the stage's discards wait until after its stores against its driver's store-dropping defect //! (its census's `fragment.discard.deferred`), `helper-guard ` with the number of the //! stage's selections whose helper invocations take another arm against the same defect (its -//! census's `fragment.helper-guard`), and the graphics key's other parts (topology, pass, -//! strides, fixed state, sample positions). A state's first pipeline prints every field; a later +//! census's `fragment.helper-guard`), `helper-fence ` with the number of the stage's +//! calls an identity shuffle follows against it (its census's `fragment.helper-fence`), and the +//! graphics key's other parts (topology, pass, strides, fixed state, sample positions). A +//! state's first pipeline prints every field; a later //! one prints the fields that differ from the state's closest earlier pipeline (the one with the //! fewest differing fields), each as `old -> new` with the parts both share elided. //! - **MoltenVK's split.** Where the device's driver is MoltenVK and its performance tracking is @@ -69,6 +71,9 @@ const DEFERRED_DISCARD_STRATEGY: &str = "fragment.discard.deferred"; /// arm. const HELPER_GUARD_STRATEGY: &str = "fragment.helper-guard"; +/// The census name of a fragment function's calls an identity shuffle follows. +const HELPER_FENCE_STRATEGY: &str = "fragment.helper-fence"; + /// Whether the log is on: read once, at the first state made. pub(crate) fn enabled() -> bool { static ON: OnceLock = OnceLock::new(); @@ -389,6 +394,14 @@ fn fields( guard.uses.to_string(), ); } + // The stage's calls an identity shuffle follows, against the same defect where no arm + // keeps the helpers out exactly. + if let Some(fence) = module.strategies.entries.get(HELPER_FENCE_STRATEGY) { + fields.insert( + format!("helper-fence {:?}", module.stage), + fence.uses.to_string(), + ); + } } let specialization = &key.specialization; for entry in &specialization.entries { diff --git a/crates/metal2vulkan-validation/src/runtime_lane/helper_tangle.rs b/crates/metal2vulkan-validation/src/runtime_lane/helper_tangle.rs index 2355bc242..3206b4b46 100644 --- a/crates/metal2vulkan-validation/src/runtime_lane/helper_tangle.rs +++ b/crates/metal2vulkan-validation/src/runtime_lane/helper_tangle.rs @@ -14,9 +14,11 @@ //! pixel. A covered pixel writes `(1, 0.5, 0.25, 1) + (2^-11, 2^-11, 2^-11, 0)`; a helper's write //! has no effect. Metal's answer is that. Apple's compiler loses a simdgroup's texture writes after //! an `optnone` call only its helpers make, but not where they make an implicit-LOD sample, a -//! derivative or a simdgroup ballot and shuffle after it: on MoltenVK on an Apple GPU the `after` -//! functions, whose tangled instruction reads the products, record no note and lose nothing, and -//! the `before` functions and `rch_tangle_unread`, whose tangled instruction reads none of them, +//! derivative or a simdgroup ballot and shuffle after it that reads what the call computes: on +//! MoltenVK on an Apple GPU the `after` functions, whose tangled instruction reads the products, +//! are left as they are, and the `before` functions and `rch_tangle_unread`, whose tangled +//! instruction reads none of them, are fenced where the device's fragment stage shuffles (an +//! identity shuffle of the products follows the call, census `fragment.helper-fence`), else //! record the note, their lost writes reported. No write may be lost where the note is not //! recorded, and none written outside the triangle. @@ -27,6 +29,7 @@ use super::guarded_effects::{ use super::resolves::{lane, quiet, Lane}; use crate::air_library::AirLibrary; use metal2vulkan::device::DriverWorkaround; +use metal2vulkan::device::OpBits; use metal2vulkan::metal::{PrimitiveType, TextureUsage}; use metal2vulkan::pipeline::{PrecisionNote, RenderPipelineDescriptor, StageSource}; use metal2vulkan::vk; @@ -71,21 +74,27 @@ fn descriptor(library: &Library, fragment: &str) -> RenderPipelineDescriptor { } /// Whether the fragment stage of `fragment`'s pipeline records -/// `PrecisionNote::HelperBranchDropsSimdgroupStores`. -fn noted(lane: &Lane, library: &Library, fragment: &str) -> bool { +/// `PrecisionNote::HelperBranchDropsSimdgroupStores`, and the calls it fences (its census's +/// `fragment.helper-fence`). +fn noted(lane: &Lane, library: &Library, fragment: &str) -> (bool, u32) { let compiled = lane .device .compile_device() .compile_render_pipeline(&descriptor(library, fragment), &Budget::standard()) .unwrap(); - compiled + let fragment = compiled .stages .iter() - .filter(|s| s.stage == vk::ShaderStage::FRAGMENT) - .any(|s| { - s.precision_notes - .contains(&PrecisionNote::HelperBranchDropsSimdgroupStores) - }) + .filter(|s| s.stage == vk::ShaderStage::FRAGMENT); + let note = fragment.clone().any(|s| { + s.precision_notes + .contains(&PrecisionNote::HelperBranchDropsSimdgroupStores) + }); + let fences = fragment + .filter_map(|s| s.strategies.entries.get("fragment.helper-fence")) + .map(|u| u.uses) + .sum(); + (note, fences) } /// One draw of `fragment`; the written texture's words. @@ -170,19 +179,19 @@ fn compare(got: &[u32], want: &[u32]) -> (usize, usize, Option) { (lost, extra, first) } -/// A write after a branch only helpers take is lost only where the fragment records the note, -/// and a tangled instruction reading the arm's products after them keeps the note away on a -/// device with the defect. +/// A write after a branch only helpers take is lost only where the fragment records the note; +/// on a device with the defect, a tangled instruction reading the arm's products after them keeps +/// the note away, and elsewhere the call is fenced where the fragment stage shuffles. #[test] fn a_write_after_a_helper_branch_is_lost_only_where_noted() { let (messages, _cache, lane) = lane(); let name = lane.device.name().to_owned(); - let defect = lane - .device - .compile_device() - .profile() + let profile = lane.device.compile_device().profile(); + let defect = profile .workarounds() .contains(&DriverWorkaround::DiscardDropsSimdgroupStores); + let fragment = &profile.subgroups().fragment; + let shuffles = fragment.supported && fragment.ops.contains(OpBits::SHUFFLE); let ll = Path::new(env!("CARGO_MANIFEST_DIR")).join("fixtures/public/engine/rch_helper_tangle.ll"); let library = lane @@ -191,16 +200,23 @@ fn a_write_after_a_helper_branch_is_lost_only_where_noted() { .unwrap(); let mut failures = Vec::new(); for (entry, reads) in CASES { - let note = noted(&lane, &library, entry); + let (note, fences) = noted(&lane, &library, entry); let (lost, extra, first) = compare(&draw(&lane, &library, entry), &expected()); eprintln!( - "helper tangle {entry} on {name} (defect {defect}): note {note}, {lost} lost, \ - {extra} extra {first:?}" + "helper tangle {entry} on {name} (defect {defect}, fragment shuffle {shuffles}): \ + note {note}, fences {fences}, {lost} lost, {extra} extra {first:?}" ); - if note != (defect && !reads) { + let bare = defect && !reads; + if note != (bare && !shuffles) { failures.push(format!( "{entry}: note {note}, expected {}", - defect && !reads + bare && !shuffles + )); + } + if (fences > 0) != (bare && shuffles) { + failures.push(format!( + "{entry}: {fences} fences, expected {}", + if bare && shuffles { "some" } else { "none" } )); } if (lost > 0 && !note) || extra > 0 { diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index 7d545c553..6e1eded1e 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -1428,7 +1428,8 @@ pub enum DriverWorkaround { /// threads only of their own branch too. Without any discard, the same fragment lost 1,040 to /// 1,063 of its 2,584 texels a run in 98 or 99 blocks where only those helpers took the branch /// with the `optnone` call (the probe). There the selections whose arms hold such a - /// call before a storage write send their helper invocations to another arm where that is exact + /// call before a storage write send their helper invocations to another arm where that is exact, + /// and an identity simdgroup shuffle of its result follows each such call left /// (`spirv::helper_branches`). DiscardDropsSimdgroupStores, /// The driver's compiler keeps a call to a function declared `DontInline` a call and diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 21801b5ba..355df25c8 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -1523,10 +1523,13 @@ pub enum PrecisionNote { /// compute there or after, an arm leaves its selection otherwise than at its merge, or the call /// is in a loop whose helper invocations may iterate alone. Only where a path from the call /// ends without a tangled instruction (an implicit-LOD sample, an LOD query, a derivative, a - /// subgroup operation) that reads what it computes: one after it keeps the writes. The live - /// fragments of a simdgroup (8 by 4 pixels) whose helpers make the call alone may lose their - /// texture writes (and, not measured, their buffer stores and atomics); color outputs are not - /// affected. + /// subgroup operation) that reads what it computes: one after it keeps the writes. And only + /// where no identity shuffle of the call's result can follow it, which the module places + /// elsewhere to keep the writes: the device has no fragment-stage subgroup shuffle, or the + /// result is a 64-bit or `bool` lane, or an 8- or 16-bit one without + /// `shaderSubgroupExtendedTypes`. The live fragments of a simdgroup (8 by 4 pixels) whose + /// helpers make the call alone may lose their texture writes (and, not measured, their buffer + /// stores and atomics); color outputs are not affected. /// /// Validation derives no tolerance and no explanation from it: a difference stays a /// mismatch for review, deferred in C3 until an exact path exists. diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 26810ac09..a3a9cd67a 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -2738,8 +2738,9 @@ fn compile_kept( // repeated regions are written once, as a loop. crate::spirv::roll::roll_entry(&mut module, m)?; // On a driver whose compiler loses a simdgroup's storage writes after an `optnone` call only - // its helper invocations make, those invocations take another arm where that is exact. - let helper_guard = crate::spirv::helper_branches::guard_for(&mut module, p, m)?; + // its helper invocations make, those invocations take another arm where that is exact, and + // each such call left is fenced once every analysis below has read the module. + let (helper_guard, fences) = crate::spirv::helper_branches::guard_for(&mut module, p, m)?; let function_tables = spec.function_tables.clone(); let reaches_command_buffers = spec.may_encode_indirect_commands(); let command_writes = spec.command_writes(); @@ -2898,6 +2899,8 @@ fn compile_kept( precision.push(PrecisionNote::DeviceSampling); precision.sort_unstable(); } + // The fences are identities, which the analyses above would read as moves between lanes. + fences.apply(&mut module)?; let stats = crate::spirv::verify::verify(&module, p, m)?; let kept = keep(&module); let mut symbols = @@ -3168,9 +3171,11 @@ fn census(plan: &Plan) -> StrategyCensus { c } -/// [`census`] of the emitted module: the plan's, and the selections whose helper invocations -/// take another arm (`spirv::helper_branches`), each with its helper query and one or two -/// logical operations (about 12 words). +/// [`census`] of the emitted module: the plan's, the selections whose helper invocations take +/// another arm (`spirv::helper_branches`), each with its helper query and one or two logical +/// operations (about 12 words), and the `optnone` calls an identity shuffle follows, each with +/// its lane's load and its shuffle (about 10 words; a structure's two members and their +/// construction about 30). fn emitted_census( plan: &Plan, helper_guard: crate::spirv::helper_branches::Guarded, @@ -3185,6 +3190,15 @@ fn emitted_census( }, ); } + if helper_guard.fences > 0 { + c.entries.insert( + crate::spirv::helper_branches::FENCE_STRATEGY.to_owned(), + StrategyUse { + uses: helper_guard.fences, + words: u64::from(helper_guard.fences) * 30, + }, + ); + } c } diff --git a/crates/metal2vulkan/src/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index 4384b3b95..4ff6e904b 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -387,7 +387,8 @@ fn typed_module_of( let crate::lower::emit::Emitted { mut module, .. } = crate::lower::emit::emit_module(&spec, &plan, m)?; crate::spirv::roll::roll_entry(&mut module, m)?; - crate::spirv::helper_branches::guard_for(&mut module, p, m)?; + let (_, fences) = crate::spirv::helper_branches::guard_for(&mut module, p, m)?; + fences.apply(&mut module)?; crate::spirv::verify::verify(&module, p, m)?; Ok((plan, module)) } diff --git a/crates/metal2vulkan/src/spirv/helper_branches.rs b/crates/metal2vulkan/src/spirv/helper_branches.rs index 821074742..3bb1bb6b6 100644 --- a/crates/metal2vulkan/src/spirv/helper_branches.rs +++ b/crates/metal2vulkan/src/spirv/helper_branches.rs @@ -47,13 +47,11 @@ //! instruction, leaves the selection as it is. //! //! A helper invocation's own writes and outputs have no effect, so its new route changes nothing -//! else. Where a call stays where only helper invocations may run before a storage write (an -//! arm of a selection that cannot be guarded exactly and that no enclosing guard covers, or a -//! loop, whose helpers may iterate alone), [`Guarded::exposed`] says so, and the caller records -//! `PrecisionNote::HelperBranchDropsSimdgroupStores`: the writes may be lost as the defect loses -//! them. +//! else. A call can stay where only helper invocations may run it before a storage write: an arm +//! of a selection that cannot be guarded exactly and that no enclosing guard covers, or a loop, +//! whose helpers may iterate alone. //! -//! Unless a tangled instruction follows the call: the defect loses nothing where the helpers make +//! There the call is harmless where a tangled instruction follows it: the defect loses nothing where the helpers make //! an implicit-LOD sample, a derivative, an LOD query or a simdgroup operation after the call. In //! plain Metal on an M4, 0 of 2,584 texels were lost with any of them after the call in its arm (a //! sample at a coordinate the call computes or of its own, `dfdx`, `fwidth`, either LOD query, @@ -69,16 +67,32 @@ //! `Private` variables too, but not back from a later block's phi or store. A call outside every //! selection and loop of a callee counts at its call sites. An arm a guard sends helpers past holds //! no tangled instruction, so the guards are as before. +//! +//! **Fences.** Each call that counts is fenced ([`Fences`]): an identity shuffle follows it, its +//! result read in every invocation from the invocation's own lane (`OpGroupNonUniformShuffle` at +//! `SubgroupLocalInvocationId`; a `MulExtended`'s structure member by member, put together again), +//! and every use of the result reads the shuffled value. Every invocation, a helper too, reads its +//! own value, so no answer changes and no lane reads another's (a guard's exactness holds); the +//! shuffle is the simdgroup operation after the call that reads what it computes, which keeps the +//! simdgroup's writes. The caller places the fences once every analysis of the module has run +//! ([`Fences::apply`]): they would read the shuffle as a move between lanes. A call stays bare where +//! the profile has no fragment shuffle (`subgroupSupportedStages` without the fragment stage, or +//! `subgroupSupportedOperations` without `SHUFFLE`) or its result is a lane no shuffle moves (a +//! 64-bit or `bool` one, or an 8- or 16-bit one without `shaderSubgroupExtendedTypes`); then +//! [`Guarded::exposed`] says so, and the caller records +//! `PrecisionNote::HelperBranchDropsSimdgroupStores`: the writes may be lost as the defect loses +//! them. use std::collections::{BTreeMap, BTreeSet}; use crate::budget::Meter; use crate::device::{DeviceProfile, DriverWorkaround}; use crate::error::{Error, InternalError, InternalKind}; -use crate::spirv::ids::{BlockId, FuncId, GlobalId, Value, VarId}; +use crate::spirv::ids::{BlockId, ConstId, FuncId, GlobalId, TypeId, Value, VarId}; use crate::spirv::ir::{ - BinOp, ConstBits, Constant, Contraction, Decl, ExecModel, GlslOp, Inst, InstNode, Merge, - StorageClass, Terminator, Type, TypedModule, UnOp, ValueDef, ValueOrigin, + BinOp, ConstBits, Constant, Contraction, Decl, ExecModel, GlobalKind, GlobalVar, GlslOp, + GroupInst, Inst, InstNode, IoDir, MemAccess, Merge, Scope, ScopeId, ShuffleOp, StorageClass, + Terminator, Type, TypedModule, UnOp, ValueDef, ValueOrigin, }; /// The census name of the selections [`guard`] guards ([`Guarded::selections`]), which the @@ -91,41 +105,85 @@ const NONE: u32 = u32::MAX; /// The most whole-module passes a taint analysis takes before it calls its guard inexact. const MAX_PASSES: u32 = 64; +/// The census name of the `optnone` calls [`guard`] fences ([`Guarded::fences`]), which the +/// runtime's pipeline creation log prints as `helper-fence `. +pub const FENCE_STRATEGY: &str = "fragment.helper-fence"; + /// What [`guard`] did to a module. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct Guarded { /// The selections whose helper invocations now take an arm without an `optnone` call. pub selections: u32, + /// The `optnone` calls an identity shuffle of what they compute follows ([`Fences`]). + pub fences: u32, /// An `optnone` call stays where only helper invocations may run it before a storage write. pub exposed: bool, } +/// The `optnone` calls a guard left where only helper invocations may make them before a storage +/// write, with no tangled instruction reading what they compute after them, each to be followed +/// by an identity shuffle of its result ([`Fences::apply`]). [`guard`] decides them; the caller +/// applies them once every analysis of the module has run, since a shuffle is an identity that +/// those analyses would read as a move between lanes. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Fences { + /// Each call's block and result. + sites: Vec<(BlockId, Value)>, +} + +/// The fences a profile can place: a fragment entry's `OpGroupNonUniformShuffle` +/// (`subgroupSupportedStages` with the fragment stage, `subgroupSupportedOperations` with +/// `SHUFFLE`), and of 8- and 16-bit values (`shaderSubgroupExtendedTypes`). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct FenceForms { + shuffle: bool, + extended: bool, +} + /// [`guard`] where `p`'s driver has the defect (`DriverWorkaround::DiscardDropsSimdgroupStores`); /// nothing elsewhere. A helper query needs `shaderDemoteToHelperInvocation`: without it nothing -/// is guarded, and a call where only helpers may run it is reported. +/// is guarded. A call that stays where only helpers may run it is fenced where the profile can +/// place the fence ([`Fences`]), else reported. pub fn guard_for( m: &mut TypedModule, p: &DeviceProfile, meter: &mut Meter, -) -> Result { +) -> Result<(Guarded, Fences), Error> { let fields = p.fields(); if !fields .workarounds .contains(&DriverWorkaround::DiscardDropsSimdgroupStores) { - return Ok(Guarded::default()); + return Ok((Guarded::default(), Fences::default())); } - guard(m, fields.fragment.demote_to_helper, meter) + let fragment = &fields.subgroup.fragment; + let forms = FenceForms { + shuffle: fragment.supported + && fragment + .ops + .contains(crate::device::subgroup::OpBits::SHUFFLE), + extended: fields + .enabled + .features + .contains(&crate::device::requirements::VkFeature::ShaderSubgroupExtendedTypes), + }; + guard(m, fields.fragment.demote_to_helper, forms, meter) } /// Keep `m`'s helper invocations out of the arms that hold an `optnone` call before a storage -/// write (the module docs), where `m` is a fragment entry that samples and writes storage. +/// write (the module docs), where `m` is a fragment entry that samples and writes storage, and +/// fence each call that stays where only they may make it (`forms`, [`Fences`]). /// `query`: the module may ask whether its invocation is a helper (`OpIsHelperInvocationEXT`). -fn guard(m: &mut TypedModule, query: bool, meter: &mut Meter) -> Result { +fn guard( + m: &mut TypedModule, + query: bool, + forms: FenceForms, + meter: &mut Meter, +) -> Result<(Guarded, Fences), Error> { if m.entry.model != ExecModel::Fragment { - return Ok(Guarded::default()); + return Ok((Guarded::default(), Fences::default())); } - let (guards, exposed) = { + let (guards, fences, exposed) = { let facts = Facts::new(m, meter)?; if !facts.samples || !facts @@ -134,9 +192,26 @@ fn guard(m: &mut TypedModule, query: bool, meter: &mut Meter) -> Result fences.sites.push((b, v)), + false => exposed = true, + } + } + } + (guards, fences, exposed) }; let selections = u32::try_from(guards.len()).map_err(|_| invariant("guard count"))?; if !guards.is_empty() { @@ -145,10 +220,15 @@ fn guard(m: &mut TypedModule, query: bool, meter: &mut Meter) -> Result Error { @@ -231,6 +311,19 @@ struct Guard { route: Route, } +/// What [`Facts::plan`] decides. +struct Plan { + /// The selections to guard. + guards: Vec, + /// Every bare `optnone` call (its block and result: one a path from which ends without + /// passing a tangled instruction that reads what it computes) where only helper invocations + /// may make it, or in a callee, outside its selections and loops, that its callers may call + /// so. + bare: Vec<(BlockId, Value)>, + /// A bare call where only helper invocations may make it. + problem: bool, +} + /// A structured construct of one function: the layout interval `[start, end)` from its header to /// its merge. #[derive(Clone, Copy, Debug)] @@ -524,6 +617,31 @@ impl<'a> Facts<'a> { Ok(decided.get(&v).copied().unwrap_or(false)) } + /// Whether the result `v` of an `optnone` call can be shuffled between lanes + /// ([`Fences::apply`]): a scalar or vector of 32-bit integers or floats, or of 8- or 16-bit + /// ones where `extended` (`shaderSubgroupExtendedTypes`), or a structure of such members (a + /// `MulExtended`'s). A 64-bit or `bool` lane is not: Metal's simdgroup shuffles move no + /// 64-bit value. + fn fenceable(&self, v: Value, extended: bool) -> Result { + let ty = self + .m + .values + .get(v.index()) + .map(|d| d.ty) + .ok_or_else(|| invariant("an optnone call's result"))?; + match self.m.types.get(ty)? { + Type::Struct { members, .. } => { + for member in members.iter() { + if !lane_type(self.m, *member, extended)? { + return Ok(false); + } + } + Ok(true) + } + _ => lane_type(self.m, ty, extended), + } + } + fn blocks_of(&self, f: FuncId) -> Vec { self.m .functions @@ -692,7 +810,7 @@ impl<'a> Facts<'a> { } /// Decide the guards, callees first, and whether a call stays exposed. - fn plan(&self, query: bool, meter: &mut Meter) -> Result<(Vec, bool), Error> { + fn plan(&self, query: bool, meter: &mut Meter) -> Result { let m = self.m; let nf = m.functions.len(); // By function: an `optnone` call no guard covers, before a write. @@ -702,6 +820,7 @@ impl<'a> Facts<'a> { let mut bare_fn = vec![false; nf]; let mut problem = false; let mut guards = Vec::new(); + let mut bare = Vec::new(); // Every guard exact at once, where the union of all candidates' taint reaches nothing. let mut all_exact: Option = None; let mut uniformity = Uniformity::default(); @@ -798,10 +917,7 @@ impl<'a> Facts<'a> { // computes. A call inside a selection or loop whose condition is not draw-uniform // records the note; one outside every such construct of a callee is its callers' to // count, through the call. Guards are as before: an arm they guard holds no tangled - // instruction at all. - if problem { - continue; - } + // instruction at all. Every function's bare calls are listed, whatever the note. let mut inner = Vec::new(); let mut outer = Vec::new(); for &p in &open { @@ -832,31 +948,50 @@ impl<'a> Facts<'a> { } } } - if self.any_bare(&blocks, &inner, meter)? { + let inner = self.bare(&blocks, &inner, meter)?; + let outer = self.bare(&blocks, &outer, meter)?; + if !inner.is_empty() { problem = true; - } else if self.any_bare(&blocks, &outer, meter)? { + } else if !outer.is_empty() { if let Some(x) = bare_fn.get_mut(f.index()) { *x = true; } } + for (p, i) in inner.into_iter().chain(outer) { + let Some(b) = blocks.get(p) else { + continue; + }; + // A call of a function is cured inside the function. + if let Some(node) = self.block(*b)?.insts.get(i).filter(|n| optnone(&n.inst)) { + let v = node + .result + .ok_or_else(|| invariant("an optnone call's result"))?; + bare.push((*b, v)); + } + } } - Ok((guards, problem)) + Ok(Plan { + guards, + bare, + problem, + }) } - /// Whether a path from one of `calls` (block position and instruction index in `blocks`, one - /// function's layout) ends without passing a tangled instruction that reads what the call - /// computes. The calls are taken 64 at a time: one pass over the function's layout from the - /// first of them marks, by block, the calls each tangled instruction there reads (a bit a + /// The calls of `calls` (block position and instruction index in `blocks`, one function's + /// layout) a path from which ends without passing a tangled instruction that reads what the + /// call computes. The calls are taken 64 at a time: one pass over the function's layout from + /// the first of them marks, by block, the calls each tangled instruction there reads (a bit a /// call, through every operand, phi, and `Function` or `Private` variable stored to, from the /// call on, in layout order, where a block's dominators come first; what a block reaches only /// through a later block's phi or store is not followed), then each call's paths are walked to /// their end or to such a block. - fn any_bare( + fn bare( &self, blocks: &[BlockId], calls: &[(usize, usize)], meter: &mut Meter, - ) -> Result { + ) -> Result, Error> { + let mut out = Vec::new(); for batch in calls.chunks(64) { let bit: BTreeMap<(usize, usize), u64> = batch .iter() @@ -908,13 +1043,13 @@ impl<'a> Facts<'a> { } } } - for (k, &(p, _)) in batch.iter().enumerate() { + for (k, &(p, i)) in batch.iter().enumerate() { if self.bare_path(blocks, &meets, p, 1u64 << k)? { - return Ok(true); + out.push((p, i)); } } } - Ok(false) + Ok(out) } /// Whether a path from the block at position `p` of `blocks` ends (a return, kill or @@ -1216,6 +1351,207 @@ impl<'a> Facts<'a> { } } +/// Whether a value of type `ty` is a lane a simdgroup shuffle moves ([`Facts::fenceable`]). +fn lane_type(m: &TypedModule, ty: TypeId, extended: bool) -> Result { + let scalar = match m.types.get(ty)? { + Type::Vector { elem, .. } => *elem, + _ => ty, + }; + Ok(match m.types.get(scalar)? { + Type::Int { width, .. } => *width == 32 || (extended && matches!(*width, 8 | 16)), + Type::Float { width } => *width == 32 || (extended && *width == 16), + _ => false, + }) +} + +impl Fences { + /// Follow each fenced call with an identity shuffle of what it computes: its result read in + /// every invocation from the invocation's own lane (`OpGroupNonUniformShuffle` at + /// `SubgroupLocalInvocationId`, a structure's members each), which every later use reads in + /// its place. Every invocation, a helper too, reads its own value, so no answer changes; the + /// shuffle is the tangled instruction after the call that keeps the simdgroup's writes on + /// Apple's compiler (the module docs). The entry reads the lane through the module's + /// `SubgroupLocalInvocationId` input, declared where the module has none. + pub fn apply(&self, m: &mut TypedModule) -> Result<(), Error> { + if self.sites.is_empty() { + return Ok(()); + } + let u32_ty = ty( + m, + Type::Int { + width: 32, + signed: false, + }, + )?; + let lane = lane_input(m, u32_ty)?; + let scope = ScopeId { + scope: Scope::Subgroup, + id: constant_id( + m, + Constant::Scalar { + ty: u32_ty, + bits: ConstBits(Scope::Subgroup.to_spirv() as u64), + }, + )?, + }; + for &(b, v) in &self.sites { + fence(m, (b, v), lane, u32_ty, scope)?; + } + m.rederive()?; + Ok(()) + } +} + +/// The pointer of the module's `SubgroupLocalInvocationId` input, declared where it has none. +fn lane_input(m: &mut TypedModule, u32_ty: TypeId) -> Result { + let builtin = crate::spv::BuiltIn::SubgroupLocalInvocationId; + let found = m.globals.iter().find(|g| { + g.kind + == GlobalKind::BuiltIn { + builtin, + dir: IoDir::Input, + } + && g.pointee == u32_ty + }); + if let Some(g) = found { + return Ok(g.value); + } + let class = StorageClass::Input; + let ptr_ty = ty( + m, + Type::Pointer { + class, + pointee: u32_ty, + }, + )?; + let id = GlobalId::new(u32::try_from(m.globals.len()).map_err(|_| invariant("global ids"))?); + let value = new_value(m, ptr_ty, ValueOrigin::Global(id))?; + m.globals.push(GlobalVar { + class, + pointee: u32_ty, + ptr_ty, + value, + init: None, + kind: GlobalKind::BuiltIn { + builtin, + dir: IoDir::Input, + }, + }); + m.decls.push(Decl::Global(id)); + Ok(value) +} + +/// Follow the call of block `b` whose result is `v` with an identity shuffle of `v` (a +/// structure's members each, put together again), renaming every use of `v` in its function to +/// the shuffled value. +fn fence( + m: &mut TypedModule, + (b, v): (BlockId, Value), + lane: Value, + u32_ty: TypeId, + scope: ScopeId, +) -> Result<(), Error> { + let blk = m + .blocks + .get(b.index()) + .ok_or_else(|| invariant("a fenced call's block"))?; + let func = blk.func; + let at = blk + .insts + .iter() + .position(|n| n.result == Some(v)) + .ok_or_else(|| invariant("a fenced call"))?; + let ty_of = |m: &TypedModule, x: Value| { + m.values + .get(x.index()) + .map(|d| d.ty) + .ok_or_else(|| invariant("a fenced value")) + }; + let result_ty = ty_of(m, v)?; + let fenced = new_value(m, result_ty, ValueOrigin::Inst(b))?; + // Every use reads the shuffled value; the shuffle, placed after this, reads the call's. + let rename = |x: &mut Value| { + if *x == v { + *x = fenced; + } + }; + for blk in m.blocks.iter_mut().filter(|blk| blk.func == func) { + for phi in &mut blk.phis { + for (x, _) in &mut phi.incoming { + rename(x); + } + } + for node in &mut blk.insts { + node.inst.for_each_value_mut(rename); + } + blk.term.for_each_value_mut(rename); + } + if m.stored_texels.contains(&v) { + m.stored_texels.insert(fenced); + } + let mut nodes = Vec::new(); + let id = new_value(m, u32_ty, ValueOrigin::Inst(b))?; + nodes.push(InstNode { + result: Some(id), + inst: Inst::Load { + ptr: lane, + access: MemAccess::default(), + }, + }); + let shuffle = |value| Inst::Group { + scope, + op: GroupInst::Shuffle { + op: ShuffleOp::Shuffle, + value, + x: id, + }, + }; + let members = match m.types.get(result_ty)? { + Type::Struct { members, .. } => Some(members.to_vec()), + _ => None, + }; + match members { + Some(members) => { + let mut parts = Vec::with_capacity(members.len()); + for (k, member) in members.into_iter().enumerate() { + let index = u32::try_from(k).map_err(|_| invariant("a member index"))?; + let part = new_value(m, member, ValueOrigin::Inst(b))?; + nodes.push(InstNode { + result: Some(part), + inst: Inst::CompositeExtract { + composite: v, + indices: Box::new([index]), + }, + }); + let moved = new_value(m, member, ValueOrigin::Inst(b))?; + nodes.push(InstNode { + result: Some(moved), + inst: shuffle(part), + }); + parts.push(moved); + } + nodes.push(InstNode { + result: Some(fenced), + inst: Inst::CompositeConstruct { + parts: parts.into_boxed_slice(), + }, + }); + } + None => nodes.push(InstNode { + result: Some(fenced), + inst: shuffle(v), + }), + } + let blk = m + .blocks + .get_mut(b.index()) + .ok_or_else(|| invariant("a fenced call's block"))?; + let tail = blk.insts.split_off(at + 1); + blk.insts.extend(nodes); + blk.insts.extend(tail); + Ok(()) +} + /// Make the header of `g` send its helper invocations by its route. fn apply(m: &mut TypedModule, g: &Guard) -> Result<(), Error> { let bool_ty = ty(m, Type::Bool)?; @@ -1341,6 +1677,12 @@ fn value( /// The value of plain constant `c`, declaring it when new. fn constant(m: &mut TypedModule, c: Constant) -> Result { + let id = constant_id(m, c)?; + Ok(m.const_value(id)?) +} + +/// Plain constant `c`, declared when new. +fn constant_id(m: &mut TypedModule, c: Constant) -> Result { let ty = c.ty(); let (id, fresh) = m.consts.intern(c, &m.types)?; if fresh { @@ -1351,5 +1693,5 @@ fn constant(m: &mut TypedModule, c: Constant) -> Result { m.const_values.push(v); m.decls.push(Decl::Const(id)); } - Ok(m.const_value(id)?) + Ok(id) } diff --git a/crates/metal2vulkan/src/tests/engine_fragment.rs b/crates/metal2vulkan/src/tests/engine_fragment.rs index f11547bff..2a8fd9f9d 100644 --- a/crates/metal2vulkan/src/tests/engine_fragment.rs +++ b/crates/metal2vulkan/src/tests/engine_fragment.rs @@ -5642,6 +5642,58 @@ fn helper_guards(m: &TypedModule) -> usize { .count() } +/// The identity shuffles of `m` that fence an `optnone` call (`spirv::helper_branches`'s +/// `Fences`): each `OpGroupNonUniformShuffle` at the `SubgroupLocalInvocationId` the module loads +/// of an `OpUMulExtended`'s member. +fn helper_fences(m: &TypedModule) -> usize { + use crate::spirv::ir::{BinOp, GlobalKind, GroupInst, ShuffleOp, ValueOrigin}; + let defs: std::collections::HashMap<_, _> = m + .blocks() + .iter() + .flat_map(|b| &b.insts) + .filter_map(|n| n.result.map(|r| (r, &n.inst))) + .collect(); + let lane = |v| match defs.get(&v) { + Some(Inst::Load { ptr, .. }) => match m.values().get(ptr.index()).map(|d| d.origin) { + Some(ValueOrigin::Global(g)) => m.globals().get(g.index()).is_some_and(|g| { + matches!( + g.kind, + GlobalKind::BuiltIn { + builtin: crate::spv::BuiltIn::SubgroupLocalInvocationId, + .. + } + ) + }), + _ => false, + }, + _ => false, + }; + let product = |v| match defs.get(&v) { + Some(Inst::CompositeExtract { composite, .. }) => matches!( + defs.get(composite), + Some(Inst::Binary { + op: BinOp::UMulExtended, + .. + }) + ), + _ => false, + }; + defs.values() + .filter(|inst| match inst { + Inst::Group { + op: + GroupInst::Shuffle { + op: ShuffleOp::Shuffle, + value, + x, + }, + .. + } => product(*value) && lane(*x), + _ => false, + }) + .count() +} + /// On MoltenVK on an Apple GPU (`DriverWorkaround::DiscardDropsSimdgroupStores`), Apple's compiler /// loses a simdgroup's storage writes after an `optnone` call only its helper invocations make, /// with no discard: the quad helpers past a primitive's edges take a branch alone. The owned @@ -5651,12 +5703,13 @@ fn helper_guards(m: &TypedModule) -> usize { /// it. There the branch's helper invocations take its empty arm where nothing they compute /// differently reaches a derivative: `rch_helper_branch` (no implicit LOD) and /// `rch_helper_branch_late` (an implicit-LOD sample after the branch at the pixel) are guarded, -/// census `fragment.helper-guard`, and record no note. `rch_helper_branch_gradient`, whose -/// implicit-LOD sample reads a coordinate the branch computes, is not guarded and records no note -/// either: the sample reads the product after it. `rch_helper_branch_loop`, whose product is in a -/// loop as long as the coverage, records `PrecisionNote::HelperBranchDropsSimdgroupStores`. One +/// census `fragment.helper-guard`. `rch_helper_branch_gradient`, whose implicit-LOD sample reads +/// a coordinate the branch computes, is neither guarded nor fenced: the sample reads the product +/// after it. `rch_helper_branch_loop`, whose product is in a loop as long as the coverage, is +/// fenced: an identity shuffle of each of its products' two members follows it, census +/// `fragment.helper-fence`. None records `PrecisionNote::HelperBranchDropsSimdgroupStores`. One /// that samples nothing (`rch_helper_branch_unsampled`) is left as it is. A device without the -/// defect (`intel-arl-anv`) guards nothing. Every module passes L3. +/// defect (`intel-arl-anv`) guards and fences nothing. Every module passes L3. #[test] fn helper_invocations_skip_an_optnone_branch_on_a_driver_that_drops_a_simdgroups_stores() { let Some(bc) = fixture("rch_helper_branch") else { @@ -5666,7 +5719,8 @@ fn helper_invocations_skip_an_optnone_branch_on_a_driver_that_drops_a_simdgroups let anv = profile("intel-arl-anv", DevicePolicy::default()).expect("profile"); let noted = PrecisionNote::HelperBranchDropsSimdgroupStores; let census = "fragment.helper-guard"; - // (entry, guarded on `moltenvk-m3`, noted there) + let fence_census = "fragment.helper-fence"; + // (entry, guarded on `moltenvk-m3`, fenced there) let cases = [ ("rch_helper_branch", true, false), ("rch_helper_branch_late", true, false), @@ -5675,22 +5729,34 @@ fn helper_invocations_skip_an_optnone_branch_on_a_driver_that_drops_a_simdgroups ("rch_helper_branch_loop", false, true), ]; let inputs = LoweringInputs::new(); - for (entry, guarded, note) in cases { - for (stem, p, guarded, note) in [ - ("moltenvk-m3", &mvk, guarded, note), + for (entry, guarded, fenced) in cases { + for (stem, p, guarded, fenced) in [ + ("moltenvk-m3", &mvk, guarded, fenced), ("intel-arl-anv", &anv, false, false), ] { let what = format!("{entry} on {stem}"); let (_, m) = typed_module_with(&bc, entry, p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); let guards = helper_guards(&m); + let fences = helper_fences(&m); let a = compile_with(&bc, entry, p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); let counted = a.strategies.entries.get(census).map(|u| u.uses as usize); + let fences_counted = a.strategies.entries.get(fence_census).map(|u| u.uses); let noted_here = a.precision.contains(¬ed); - eprintln!("observed: {what}: guards {guards}, census {counted:?}, note {noted_here}"); + eprintln!( + "observed: {what}: guards {guards}, census {counted:?}, fences {fences} \ + ({fences_counted:?}), note {noted_here}" + ); assert_eq!(guards > 0, guarded, "{what}: {guards} guards"); assert_eq!(counted, guarded.then_some(guards), "{what}: the census"); - assert_eq!(noted_here, note, "{what}: the note"); + // Each fenced product's two members are shuffled. + assert_eq!(fences > 0, fenced, "{what}: {fences} fences"); + assert_eq!( + fences_counted.map(|c| 2 * c as usize), + fenced.then_some(fences), + "{what}: the fence census" + ); + assert!(!noted_here, "{what}: the note"); link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); } } @@ -5747,16 +5813,17 @@ fn a_branch_every_invocation_takes_alike_leaves_no_helper_alone() { /// Apple's compiler loses nothing after an `optnone` call only helper invocations make where they /// make a tangled instruction (an implicit-LOD sample, a derivative, an LOD query, a simdgroup -/// operation) after it, so such a call records no note where every path from it passes a tangled -/// instruction reading what it computes. The owned fixture `rch_helper_tangle` takes the high -/// words of products (`mulhi`, an `OpUMulExtended`, which SPIRV-Cross writes through its `optnone` +/// operation) after it that reads what it computes, so a call is fenced only where some path from +/// it passes none. The owned fixture `rch_helper_tangle` takes the high words of products +/// (`mulhi`, an `OpUMulExtended`, which SPIRV-Cross writes through its `optnone` /// `spvMulExtended`) where only the quad helpers past a primitive's edges run more than once or at /// all, beside a tangled instruction, and writes a texture after it. On `moltenvk-m3` no arm is /// guarded; the `after` functions, whose tangled instruction reads the products (in the arm an /// implicit-LOD sample at them, `dfdx`, `quad_sum`, the LOD query; a sample after the branch's -/// merge; a sample after a loop only helpers repeat), record no -/// `HelperBranchDropsSimdgroupStores`; the `before` functions and `rch_tangle_unread`, whose -/// tangled instruction reads none of them, record it. Every module passes L3. +/// merge; a sample after a loop only helpers repeat), are not fenced; the `before` functions and +/// `rch_tangle_unread`, whose tangled instruction reads none of them, are: an identity shuffle of +/// each of the products' two members follows the call, census `fragment.helper-fence`. None +/// records `HelperBranchDropsSimdgroupStores`. Every module passes L3. #[test] fn a_tangled_instruction_reading_a_helper_call_keeps_the_note_away() { let Some(bc) = fixture("rch_helper_tangle") else { @@ -5764,7 +5831,7 @@ fn a_tangled_instruction_reading_a_helper_call_keeps_the_note_away() { }; let p = profile("moltenvk-m3", DevicePolicy::default()).expect("profile"); let noted = PrecisionNote::HelperBranchDropsSimdgroupStores; - // (entry, noted on `moltenvk-m3`) + // (entry, fenced on `moltenvk-m3`) let cases = [ ("rch_tangle_sample_after", false), ("rch_tangle_dfdx_after", false), @@ -5777,22 +5844,77 @@ fn a_tangled_instruction_reading_a_helper_call_keeps_the_note_away() { ("rch_tangle_unread", true), ]; let inputs = LoweringInputs::new(); - for (entry, note) in cases { + for (entry, fenced) in cases { let what = format!("{entry} on moltenvk-m3"); let (_, m) = typed_module_with(&bc, entry, &p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); let a = compile_with(&bc, entry, &p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); let noted_here = a.precision.contains(¬ed); + let fences = helper_fences(&m); + let counted = a + .strategies + .entries + .get("fragment.helper-fence") + .map(|u| u.uses); eprintln!( - "observed: {what}: guards {}, note {noted_here}", + "observed: {what}: guards {}, fences {fences} ({counted:?}), note {noted_here}", helper_guards(&m) ); assert_eq!(helper_guards(&m), 0, "{what}: guards"); - assert_eq!(noted_here, note, "{what}: the note"); + // Each fenced product's two members are shuffled. + assert_eq!(fences > 0, fenced, "{what}: {fences} fences"); + assert_eq!( + counted.map(|c| 2 * c as usize), + fenced.then_some(fences), + "{what}: the fence census" + ); + assert!(!noted_here, "{what}: the note"); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); } } +/// A call no identity shuffle can follow stays bare and records the note: on `moltenvk-m3` with +/// the fragment stage's shuffle taken out of its subgroup model (the `SHUFFLE` operation, or the +/// fragment stage), `rch_helper_tangle`'s `before` functions and `rch_tangle_unread` are not +/// fenced and record `PrecisionNote::HelperBranchDropsSimdgroupStores`, as every profile with the +/// defect and no fragment shuffle does. Every module passes L3. +#[test] +fn a_helper_call_no_shuffle_can_follow_keeps_the_note() { + let Some(bc) = fixture("rch_helper_tangle") else { + return; + }; + let base = profile("moltenvk-m3", DevicePolicy::default()).expect("profile"); + let mut no_op = base.clone(); + no_op + .edit(|f| f.subgroup.fragment.ops = OpBits(f.subgroup.fragment.ops.0 & !OpBits::SHUFFLE.0)); + let mut no_stage = base.clone(); + no_stage.edit(|f| f.subgroup.fragment.supported = false); + let noted = PrecisionNote::HelperBranchDropsSimdgroupStores; + let inputs = LoweringInputs::new(); + for (form, p) in [ + ("no fragment SHUFFLE", &no_op), + ("no fragment stage", &no_stage), + ] { + for entry in [ + "rch_tangle_quad_before", + "rch_tangle_sample_before", + "rch_tangle_unread", + ] { + let what = format!("{entry} on moltenvk-m3 with {form}"); + let (_, m) = + typed_module_with(&bc, entry, p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); + let a = compile_with(&bc, entry, p, &inputs).unwrap_or_else(|e| panic!("{what}: {e}")); + assert_eq!(helper_fences(&m), 0, "{what}: the fences"); + assert!( + !a.strategies.entries.contains_key("fragment.helper-fence"), + "{what}: the fence census" + ); + assert!(a.precision.contains(¬ed), "{what}: the note"); + link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); + } + } +} + /// The opcodes of every instruction in `words`, and the capabilities it declares. fn opcodes_and_capabilities(words: &[u32]) -> (Vec, Vec) { let (mut ops, mut caps) = (Vec::new(), Vec::new()); diff --git a/docs/API.md b/docs/API.md index 6a4573d91..fb5b71b10 100644 --- a/docs/API.md +++ b/docs/API.md @@ -3998,7 +3998,10 @@ bound. edges, or demoted invocations) may run it before a storage write, and keeping them out would not be exact (`spirv::helper_branches`): a derivative or subgroup operation reads what they compute there or after, an arm leaves its selection otherwise than at its merge, or the call is in a loop - whose helper invocations may iterate alone. + whose helper invocations may iterate alone; and no identity shuffle of the call's result can + follow it, which keeps the writes where the module places one: the device has no fragment-stage + subgroup shuffle, or the result is a 64-bit or `bool` lane, or an 8- or 16-bit one without + `shaderSubgroupExtendedTypes`. - `metal2vulkan-degrade-extended-range-float-blend-source` (precision). `PrecisionNote::ExtendedRangeFloatBlendSource`: `PrecisionNote::ExtendedRangeBlendSource` for a `float` color output (a scalar or vector of AIR's `float`): blended into an extended-range or