diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index cbcc04979..cfc13d525 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2297; +pub const SEMANTICS_VERSION: u32 = 2298; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another diff --git a/crates/metal2vulkan/src/lower/fragment/discard.rs b/crates/metal2vulkan/src/lower/fragment/discard.rs index 5c89da410..0836d127a 100644 --- a/crates/metal2vulkan/src/lower/fragment/discard.rs +++ b/crates/metal2vulkan/src/lower/fragment/discard.rs @@ -38,9 +38,8 @@ //! discarded thread only while its quad keeps a live thread, and drops a quad whose every thread is //! discarded from the simdgroup. Demote, which the profile lacks there, maps Metal's helper to //! Vulkan's, as for every other helper lane, and is the form every profile with it takes; -//! `MaximallyReconvergesKHR`, which an entry with a tangled instruction -//! declares where the profile has it (`lower::simd`), keeps such a helper a lane of later subgroup -//! operations. Demote needs no guard: Vulkan helper invocations have no memory side effects and +//! `MaximallyReconvergesKHR`, which an entry with a subgroup operation declares where the profile +//! has it (`lower::simd`), keeps such a helper a lane of later subgroup operations. Demote needs no guard: Vulkan helper invocations have no memory side effects and //! their outputs are discarded. //! //! **A quad of helpers alone**. Metal drops a quad whose every thread is discarded from the diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index 81776533a..0b1f7c99b 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -2395,6 +2395,7 @@ fn select_one( let value = id(cx, Value::Inst(at))?; if tangled { cx.tangled.insert(value); + cx.derivatives.insert(value); } let clamp_reference = clamps_reference(cx, comparison, sampler)?; let sampling = Sampling { diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 83c956f3f..4f91886c6 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -519,6 +519,10 @@ pub struct SelectCx<'a> { /// Tangled instructions (subgroup/quad ops, derivatives, implicit-LOD samples, barriers), /// which the families that select them add. pub tangled: BTreeSet, + /// The tangled instructions that read other lanes only to take derivatives: `dfdx`, `dfdy` + /// and `fwidth`, implicit-LOD samples and LOD queries (`lower::simd`'s module, + /// **Reconvergence**). + pub derivatives: BTreeSet, /// Each family's own plan. pub families: FamilyPlans, /// The offset shapes the access family has read while selecting this function's typed @@ -1245,6 +1249,7 @@ pub fn select( descriptors: DescriptorCounts::default(), simd: SimdClass::None, tangled: BTreeSet::new(), + derivatives: BTreeSet::new(), families: FamilyPlans::default(), shapes: access::local::Shapes::default(), root_sets, diff --git a/crates/metal2vulkan/src/lower/simd/mod.rs b/crates/metal2vulkan/src/lower/simd/mod.rs index 7935d2e3c..263142b1f 100644 --- a/crates/metal2vulkan/src/lower/simd/mod.rs +++ b/crates/metal2vulkan/src/lower/simd/mod.rs @@ -182,7 +182,14 @@ //! threadgroup barrier the lockstep pass inserted stands where the whole threadgroup runs together //! and depends on no reconvergence (`sync::barrier::BarrierPlan::uniform_placed`): an entry whose //! only tangled instructions are such barriers declares no mode and records `Guaranteed`, as does -//! an emulated kernel whose others are emulated sites (`workgroup::check`). +//! an emulated kernel whose others are emulated sites (`workgroup::check`). A fragment's +//! derivatives, implicit-LOD samples and LOD queries (`SelectCx::derivatives`) are Metal's only +//! where the quad reaches them together (MSL 6.11.1.1), which SPIR-V's own reconvergence gives +//! but in a loop a back edge re-enters from inside a selection: a fragment entry whose other +//! tangled instructions depend on no reconvergence takes the mode, and records +//! `ImplementationDefined` where the profile has no maximal reconvergence, only where its module +//! holds one of them in such a loop (`quad_loop`); elsewhere it declares no mode and records +//! `Guaranteed`. pub mod agx; pub mod divergent; @@ -190,6 +197,7 @@ mod group; pub mod lockstep; pub mod matrix; pub mod pressure; +pub mod quad_loop; #[cfg(test)] mod tests; pub mod uniform; @@ -212,7 +220,7 @@ use crate::lower::arith::legal::{form_on, wide_form_on, Form, Held, LoweredConst use crate::lower::emit::EmitCx; use crate::lower::select::{FamilyPlans, Plan, SelectCx}; use crate::lower::strategy::{FamilyStrategy, Strategy}; -use crate::pipeline::artifact::{PrecisionNote, Reconvergence}; +use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::sym::Stage; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::error::BResult; @@ -320,6 +328,12 @@ pub struct SimdPlan { pub mode: ReconvergenceMode, /// A tangled instruction runs without maximal reconvergence on this profile. pub implementation_defined: bool, + /// A fragment entry whose only tangled instructions that depend on reconvergence take + /// derivatives (`SelectCx::derivatives`): the mode and `implementation_defined` the profile + /// gives a tangled entry, which the entry takes only where its module holds such an + /// instruction in a loop a back edge re-enters from inside a selection + /// ([`quad_loop::settle`]). Elsewhere it states no mode and its reconvergence is guaranteed. + pub quad_loops: Option<(ReconvergenceMode, bool)>, /// In the `Emulated` tier, the words each lane publishes to the scratch in the widest /// exchange of the function; 0 when no operation exchanges values. pub exchange_words: u32, @@ -451,16 +465,6 @@ pub fn widest_pin(cx: &SelectCx<'_>, m: &mut Meter) -> Result { Ok(pressure::peak_words(cx.entry, cx.body, m)? > WIDEST_PIN_WORDS) } -/// The artifact's reconvergence: `ImplementationDefined` when the entry holds a tangled instruction -/// and the profile has no maximal reconvergence. -pub fn reconvergence(plan: &Plan) -> Reconvergence { - if plan.families.simd.implementation_defined { - Reconvergence::ImplementationDefined - } else { - Reconvergence::Guaranteed - } -} - /// `c` raised by operation classes `ops`: a cross-lane class with them added. The matrix class /// already implies cross-lane use. pub fn raise(c: SimdClass, ops: OpBits) -> SimdClass { @@ -541,12 +545,23 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { .into()); } } + // A fragment's derivatives, implicit levels and LOD queries depend on reconvergence only in a + // loop a back edge re-enters from inside a selection, which the emitted module shows + // (`quad_loop::settle`). let barriers = &cx.families.barrier; - if cx - .tangled - .iter() - .any(|&v| crate::lower::sync::barrier::reconverges(barriers, v)) - { + let fragment = cx.stage == Stage::Fragment; + let (mut others, mut derivatives) = (false, false); + for &v in &cx.tangled { + if !crate::lower::sync::barrier::reconverges(barriers, v) { + continue; + } + if fragment && cx.derivatives.contains(&v) { + derivatives = true; + } else { + others = true; + } + } + if others || derivatives { let model = &cx.profile.fields().subgroup; let (mode, defined) = if model.maximal_reconvergence { (ReconvergenceMode::Maximal, false) @@ -555,8 +570,12 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { } else { (ReconvergenceMode::None, true) }; - cx.families.simd.mode = mode; - cx.families.simd.implementation_defined = defined; + if others { + cx.families.simd.mode = mode; + cx.families.simd.implementation_defined = defined; + } else { + cx.families.simd.quad_loops = Some((mode, defined)); + } } Ok(()) } diff --git a/crates/metal2vulkan/src/lower/simd/quad_loop.rs b/crates/metal2vulkan/src/lower/simd/quad_loop.rs new file mode 100644 index 000000000..abdd08767 --- /dev/null +++ b/crates/metal2vulkan/src/lower/simd/quad_loop.rs @@ -0,0 +1,130 @@ +//! The reconvergence of a fragment entry whose only tangled instructions that depend on +//! reconvergence take derivatives (`SimdPlan::quad_loops`): `dfdx`, `dfdy` and `fwidth`, +//! implicit-LOD samples and LOD queries. +//! +//! Metal leaves derivatives undefined within nonuniform control flow (MSL 6.11.1.1), and an +//! implicit level or an LOD query is the derivative of its coordinate (MSL 6.12), so such an +//! instruction is Metal's only where the invocations reach it together. Without a reconvergence +//! mode SPIR-V reconverges invocations at the merge of a construct they entered together and all +//! leave by that merge (SPIR-V 2.2.5, "Uniform Control Flow"), which covers every place they +//! rejoin but one: a loop's continue target. Invocations that reach the continue target from +//! different blocks (a continue from inside a selection, or two latches) are not known to run the +//! next iteration together, where Metal's run it as uniform control flow; +//! `MaximallyReconvergesKHR` reconverges them there (`SPV_KHR_maximal_reconvergence`, +//! "Reconvergence"). So the entry takes the mode the profile gives a tangled entry, and its +//! `implementation_defined` (`PrecisionNote::DeviceReconvergence` where the profile has no maximal +//! reconvergence), only where its module holds such an instruction, itself or through a call, in +//! the construct of a loop whose continue target two or more blocks of the construct branch to +//! ([`reentered`]); elsewhere it states no mode and its reconvergence is guaranteed. + +use super::{ReconvergenceMode, SimdPlan}; +use crate::pipeline::artifact::Reconvergence; +use crate::spirv::error::BResult; +use crate::spirv::ids::BlockId; +use crate::spirv::ir::{Block, ExecMode, Inst, Merge, Terminator, TypedModule}; + +/// The entry's reconvergence once `module` is emitted, declaring the deferred mode of a fragment +/// entry whose derivatives lie in a re-entered loop ([`reentered`]). +pub fn settle(simd: &SimdPlan, module: &mut TypedModule) -> BResult { + let implementation_defined = match simd.quad_loops { + Some((mode, implementation_defined)) if reentered(module) => { + let mode = match mode { + ReconvergenceMode::None => None, + ReconvergenceMode::Maximal => Some(ExecMode::MaximallyReconverges), + ReconvergenceMode::UniformControlFlow => Some(ExecMode::SubgroupUniformControlFlow), + }; + if let Some(mode) = mode { + module.declare_modes(&[mode])?; + } + implementation_defined + } + _ => simd.implementation_defined, + }; + Ok(if implementation_defined { + Reconvergence::ImplementationDefined + } else { + Reconvergence::Guaranteed + }) +} + +/// Whether `inst` reads other lanes only to take a derivative: a derivative, an implicit-LOD +/// sample or an LOD query. +fn takes_derivatives(inst: &Inst) -> bool { + match inst { + Inst::ImageSample { form, .. } => form.implicit, + Inst::Derivative { .. } | Inst::ImageQueryLod { .. } => true, + _ => false, + } +} + +/// Whether `t` branches to `to`. +fn branches_to(t: &Terminator, to: BlockId) -> bool { + match t { + Terminator::Branch(x) => *x == to, + Terminator::CondBranch { t, f, .. } => *t == to || *f == to, + Terminator::Switch { default, cases, .. } => { + *default == to || cases.iter().any(|(_, b)| *b == to) + } + _ => false, + } +} + +/// Whether `module` holds a derivative, an implicit-LOD sample or an LOD query, itself or through +/// a call, in the construct of a loop whose continue target two or more blocks of the construct +/// branch to. A construct is the layout interval from its header to its merge, as the module's +/// verification holds it (`spirv::verify`). +pub fn reentered(module: &TypedModule) -> bool { + let blocks = module.blocks(); + let functions = module.functions(); + let block = |b: &BlockId| blocks.get(b.index()); + // The functions that take derivatives, themselves or through a call (a monotone fixpoint). + let mut holds = vec![false; functions.len()]; + let site = |b: &Block, holds: &[bool]| { + b.insts.iter().any(|n| match &n.inst { + Inst::Call { func, .. } => holds.get(func.index()).copied().unwrap_or(false), + inst => takes_derivatives(inst), + }) + }; + let mut changed = true; + while changed { + changed = false; + for (fi, f) in functions.iter().enumerate() { + if holds.get(fi).copied().unwrap_or(true) { + continue; + } + if f.blocks.iter().filter_map(block).any(|b| site(b, &holds)) { + if let Some(x) = holds.get_mut(fi) { + *x = true; + } + changed = true; + } + } + } + functions.iter().any(|f| { + // Each block's site, and the sites before each layout position. + let mut before = Vec::with_capacity(f.blocks.len() + 1); + before.push(0usize); + for b in &f.blocks { + let here = block(b).is_some_and(|b| site(b, &holds)); + before.push(before.last().copied().unwrap_or(0) + usize::from(here)); + } + f.blocks.iter().enumerate().any(|(start, h)| { + let Some(Merge::Loop { merge, cont }) = block(h).and_then(|b| b.merge) else { + return false; + }; + let Some(end) = f.blocks.iter().position(|b| *b == merge) else { + return false; + }; + let construct = f.blocks.get(start..end).unwrap_or(&[]); + let sites = + before.get(end).copied().unwrap_or(0) - before.get(start).copied().unwrap_or(0); + sites > 0 + && construct + .iter() + .filter_map(block) + .filter(|b| branches_to(&b.term, cont)) + .nth(1) + .is_some() + }) + }) +} diff --git a/crates/metal2vulkan/src/lower/sync/barrier.rs b/crates/metal2vulkan/src/lower/sync/barrier.rs index 63a85382e..85e920166 100644 --- a/crates/metal2vulkan/src/lower/sync/barrier.rs +++ b/crates/metal2vulkan/src/lower/sync/barrier.rs @@ -582,6 +582,7 @@ fn select_derivative( (DerivativeOp::Fwidth, false) => DerivOp::Fwidth, }; cx.tangled.insert(id); + cx.derivatives.insert(id); Ok(BarrierStrategy::Derivative(Deriv { op, value })) } diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 2f0eca72b..89b125de1 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -477,7 +477,9 @@ pub struct ComputePipelineMetalInfo { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] pub enum Reconvergence { - /// Maximal reconvergence (or no tangled operation depends on it). + /// Maximal reconvergence (or no tangled operation depends on it: among a fragment function's + /// derivatives, implicit-LOD samples and LOD queries, only one in a loop a back edge re-enters + /// from inside a selection does). Guaranteed, /// Reconvergence after divergence is implementation-defined on this profile. ImplementationDefined, @@ -1875,8 +1877,11 @@ pub enum PrecisionNote { /// which lanes run it together, where Metal's lanes reconverge maximally, so such an operation /// may see other lanes active than Metal's. Under subgroup-uniform control flow /// (`shaderSubgroupUniformControlFlow`) the lanes reconverge where control flow is uniform. - /// Static per stage: recorded for any tangled instruction in the entry, as the stage's - /// `reconvergence` is. + /// A fragment function's derivatives, implicit-LOD samples and LOD queries, which Metal + /// leaves undefined within nonuniform control flow, count only inside a loop that a back + /// edge re-enters from inside a selection (a `continue` there, or two latches), where SPIR-V + /// reconverges the quad for the next iteration only under maximal reconvergence. Static per + /// stage: recorded for any such instruction in the entry, as the stage's `reconvergence` is. /// /// Validation derives no tolerance from it: a difference stays a mismatch, which the note /// explains. diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index f3246e5e6..b31d76a5f 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -3137,6 +3137,9 @@ fn lower_bounded( let modes = crate::lower::arith::narrow::controlled_modes(p).unwrap_or_default(); module.declare_modes(&modes)?; } + // A fragment entry whose derivatives alone are tangled takes its reconvergence mode only where + // the module holds one of them in a loop a back edge re-enters from inside a selection. + let reconvergence = crate::lower::simd::quad_loop::settle(&plan.families.simd, &mut module)?; // Native half rounding and widening: a module that rounds through the device's quantize or // conversion, or widens a `half` by the device where that is not controlled to be Metal's, // records each kind, and requires no fact. @@ -3245,7 +3248,6 @@ fn lower_bounded( } // Implementation-defined where a tangled instruction runs without maximal reconvergence // (`lower::simd` chooses the entry's reconvergence mode), which the stage's note records. - let reconvergence = crate::lower::simd::reconvergence(&plan); if reconvergence == Reconvergence::ImplementationDefined && !precision.contains(&PrecisionNote::DeviceReconvergence) { diff --git a/crates/metal2vulkan/src/tests/engine_quad_loops.rs b/crates/metal2vulkan/src/tests/engine_quad_loops.rs new file mode 100644 index 000000000..752c1498b --- /dev/null +++ b/crates/metal2vulkan/src/tests/engine_quad_loops.rs @@ -0,0 +1,256 @@ +//! A fragment function whose only tangled instructions take derivatives (`dfdx`, implicit-LOD +//! samples, LOD queries) and its reconvergence (`lower::simd::quad_loop`): it states no mode and +//! records `Guaranteed` with no `DeviceReconvergence` on every committed profile, but where one of +//! them lies in a loop a back edge re-enters from inside a selection, where it takes the mode the +//! profile gives a tangled entry and, without maximal reconvergence, the note. A fragment +//! function with a quad operation keeps its mode. +//! +//! `llvm-as` assembles the fixtures; without it the tests skip visibly. + +use std::sync::atomic::{AtomicU64, Ordering}; + +use crate::device::profile::DeviceProfile; +use crate::pipeline::artifact::{PrecisionNote, Reconvergence}; +use crate::pipeline::testing::{ + compile, compile_kept, engine_dir, link_and_validate, llvm_assemble, AssembleError, +}; +use crate::spirv::testing::{committed_profiles, spirv_dis}; + +const HEADER: &str = "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\"\ntarget triple = \"air64_v28-apple-macosx26.0.0\"\n\n"; + +/// A constexpr sampler: magnify nearest, minify linear, repeat. +const SAMPLER_WORDS: u64 = 34901797601020050; + +fn assemble(name: &str, body: &str) -> Option> { + static NEXT: AtomicU64 = AtomicU64::new(0); + let dir = std::env::temp_dir().join(format!( + "m2v-quad-loops-{}-{}-{name}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + std::fs::create_dir_all(&dir).expect("scratch"); + let ll = dir.join("f.ll"); + std::fs::write(&ll, format!("{HEADER}{body}")).expect("write"); + let r = llvm_assemble(&ll); + let _ = std::fs::remove_dir_all(&dir); + match r { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {name}: {why}\n{body}"), + } +} + +fn fixture(stem: &str) -> Option> { + match llvm_assemble(&engine_dir().join(format!("{stem}.ll"))) { + Ok(b) => Some(b), + Err(AssembleError::Missing(why)) => { + eprintln!("SKIPPED: {why}"); + None + } + Err(AssembleError::Rejected(why)) => panic!("llvm-as rejected {stem}: {why}"), + } +} + +/// A fragment function `f` that, four trips, takes a value of its position and its trip number +/// that reads the quad (an implicit-LOD sample of texture slot 0, or `dfdx` where `derivative`) +/// and adds or subtracts it by its pixel column's parity. With `two_latches` each parity's block +/// branches back to the loop's header itself, so the loop is re-entered by back edges from +/// inside a selection; without, both join one latch first. +fn looped(two_latches: bool, derivative: bool) -> String { + let take = if derivative { + "%pv = fmul <4 x float> %pos, %s4\n %v = tail call fast <4 x float> @air.dfdx.v4f32(<4 x float> %pv)" + } else { + "%r = call { <4 x float>, i8 } @air.sample_texture_2d.v4f32(ptr addrspace(1) %t, ptr addrspace(2) @__air_sampler_state, <2 x float> %uv, i1 true, <2 x i32> zeroinitializer, i1 false, float 0.000000e+00, float 0.000000e+00, i32 0)\n %v = extractvalue { <4 x float>, i8 } %r, 0" + }; + let (incoming, arms, exit) = if two_latches { + ( + "[ %i1, %a ], [ %i1, %b ]", + "a:\n %acc1 = fadd <4 x float> %acc, %v\n br i1 %more, label %head, label %exit\n\n\ + b:\n %acc2 = fsub <4 x float> %acc, %v\n br i1 %more, label %head, label %exit\n", + "exit:\n %res = phi <4 x float> [ %acc1, %a ], [ %acc2, %b ]\n ret <4 x float> %res\n", + ) + } else { + ( + "[ %i1, %latch ]", + "a:\n %acc1 = fadd <4 x float> %acc, %v\n br label %latch\n\n\ + b:\n %acc2 = fsub <4 x float> %acc, %v\n br label %latch\n\n\ + latch:\n %acc3 = phi <4 x float> [ %acc1, %a ], [ %acc2, %b ]\n br i1 %more, label %head, label %exit\n", + "exit:\n ret <4 x float> %acc3\n", + ) + }; + let accs = if two_latches { + "[ %acc1, %a ], [ %acc2, %b ]" + } else { + "[ %acc3, %latch ]" + }; + format!( + r#"@__air_sampler_state = internal addrspace(2) constant [2 x i64] [i64 {SAMPLER_WORDS}, i64 0], align 8 + +define <4 x float> @f(<4 x float> %pos, ptr addrspace(1) %t) {{ +entry: + %xy = shufflevector <4 x float> %pos, <4 x float> poison, <2 x i32> + %x = extractelement <4 x float> %pos, i64 0 + %xi = fptoui float %x to i32 + %odd = and i32 %xi, 1 + %c = icmp eq i32 %odd, 0 + br label %head + +head: + %i = phi i32 [ 0, %entry ], {incoming} + %acc = phi <4 x float> [ zeroinitializer, %entry ], {accs} + %fi = uitofp i32 %i to float + %s1 = insertelement <2 x float> poison, float %fi, i64 0 + %s2 = shufflevector <2 x float> %s1, <2 x float> poison, <2 x i32> zeroinitializer + %s3 = insertelement <4 x float> poison, float %fi, i64 0 + %s4 = shufflevector <4 x float> %s3, <4 x float> poison, <4 x i32> zeroinitializer + %uv0 = fmul <2 x float> %xy, + %uv = fadd <2 x float> %uv0, %s2 + {take} + %i1 = add i32 %i, 1 + %more = icmp ult i32 %i1, 4 + br i1 %c, label %a, label %b + +{arms} +{exit}}} + +declare {{ <4 x float>, i8 }} @air.sample_texture_2d.v4f32(ptr addrspace(1), ptr addrspace(2), <2 x float>, i1, <2 x i32>, i1, float, float, i32) +declare <4 x float> @air.dfdx.v4f32(<4 x float>) + +!air.fragment = !{{!0}} +!air.sampler_states = !{{!6}} +!0 = !{{ptr @f, !1, !3}} +!1 = !{{!2}} +!2 = !{{!"air.render_target", i32 0, i32 0, !"air.arg_type_name", !"float4"}} +!3 = !{{!4, !5}} +!4 = !{{i32 0, !"air.position", !"air.center", !"air.no_perspective", !"air.arg_type_name", !"float4", !"air.arg_name", !"position"}} +!5 = !{{i32 1, !"air.texture", !"air.location_index", i32 0, i32 1, !"air.sample", !"air.arg_type_name", !"texture2d", !"air.arg_name", !"t"}} +!6 = !{{!"air.sampler_state", ptr addrspace(2) @__air_sampler_state}} +"# + ) +} + +/// The mode `entry` of `bc` states on `p`, its reconvergence, whether it records +/// `DeviceReconvergence`, and whether its module holds a quad-scoped instruction in a re-entered +/// loop; its words linked and validated (`spirv-val`). +fn reading( + bc: &[u8], + entry: &str, + stem: &str, + p: &DeviceProfile, +) -> (&'static str, Reconvergence, bool, bool) { + let (a, _, m) = compile_kept(bc, entry, p).unwrap_or_else(|e| panic!("{stem} {entry}: {e}")); + let (_, words) = link_and_validate(&a, p).unwrap_or_else(|e| panic!("{stem} {entry}: L3: {e}")); + let text = spirv_dis(&words); + let mode = match ( + text.contains("MaximallyReconvergesKHR"), + text.contains("SubgroupUniformControlFlowKHR"), + ) { + (true, false) => "maximal", + (false, true) => "ucf", + (false, false) => "none", + (true, true) => "both", + }; + let noted = a.precision.contains(&PrecisionNote::DeviceReconvergence); + ( + mode, + a.reconvergence, + noted, + crate::lower::simd::quad_loop::reentered(&m), + ) +} + +/// A fragment function's derivatives in selections, after a selection's merge, after a loop and +/// inside a loop one latch closes state no mode and record `Guaranteed` with no +/// `DeviceReconvergence`, on every committed profile, as no loop re-enters them. +#[test] +fn derivatives_outside_a_re_entered_loop_state_no_mode_and_no_note() { + let Some(tangle) = fixture("rch_helper_tangle") else { + return; + }; + let Some(one_latch) = assemble("one_latch", &looped(false, false)) else { + return; + }; + let Some(one_latch_dfdx) = assemble("one_latch_dfdx", &looped(false, true)) else { + return; + }; + let cases: [(&[u8], &str); 9] = [ + (&tangle, "rch_tangle_sample_after"), + (&tangle, "rch_tangle_dfdx_after"), + (&tangle, "rch_tangle_lod_after"), + (&tangle, "rch_tangle_sample_before"), + (&tangle, "rch_tangle_unread"), + (&tangle, "rch_tangle_merge_after"), + (&tangle, "rch_tangle_loop_after"), + (&one_latch, "f"), + (&one_latch_dfdx, "f"), + ]; + for (stem, p) in committed_profiles().expect("profiles") { + for (bc, entry) in cases { + let (mode, reconvergence, noted, reentered) = reading(bc, entry, &stem, &p); + assert_eq!( + (mode, reconvergence, noted, reentered), + ("none", Reconvergence::Guaranteed, false, false), + "{stem} {entry}" + ); + } + } +} + +/// A fragment function whose implicit-LOD sample or `dfdx` lies in a loop that two latches, +/// each inside an arm of a selection on the pixel's column, re-enter takes the profile's mode: +/// `MaximallyReconvergesKHR` and `Guaranteed` with maximal reconvergence; else +/// `SubgroupUniformControlFlowKHR` where offered, or no mode, with `ImplementationDefined` and +/// `DeviceReconvergence`. +#[test] +fn a_derivative_in_a_re_entered_loop_keeps_the_mode_and_the_note() { + let Some(sample) = assemble("two_latches", &looped(true, false)) else { + return; + }; + let Some(dfdx) = assemble("two_latches_dfdx", &looped(true, true)) else { + return; + }; + for (stem, p) in committed_profiles().expect("profiles") { + let sg = p.fields().subgroup; + let expected = if sg.maximal_reconvergence { + ("maximal", Reconvergence::Guaranteed, false, true) + } else if sg.uniform_control_flow { + ("ucf", Reconvergence::ImplementationDefined, true, true) + } else { + ("none", Reconvergence::ImplementationDefined, true, true) + }; + for bc in [&sample, &dfdx] { + assert_eq!(reading(bc, "f", &stem, &p), expected, "{stem}"); + } + } +} + +/// A fragment function with a quad operation keeps the mode wherever it compiles: its quad sum +/// reconverges, whatever its samples do. +#[test] +fn a_fragment_quad_operation_keeps_the_mode() { + let Some(tangle) = fixture("rch_helper_tangle") else { + return; + }; + let mut compiled = 0; + for (stem, p) in committed_profiles().expect("profiles") { + if !p.fields().subgroup.maximal_reconvergence { + continue; + } + for entry in ["rch_tangle_quad_after", "rch_tangle_quad_before"] { + if compile(&tangle, entry, &p).is_err() { + continue; + } + compiled += 1; + let (mode, reconvergence, noted, _) = reading(&tangle, entry, &stem, &p); + assert_eq!( + (mode, reconvergence, noted), + ("maximal", Reconvergence::Guaranteed, false), + "{stem} {entry}" + ); + } + } + assert!(compiled > 0, "no profile compiled a quad operation"); +} diff --git a/crates/metal2vulkan/src/tests/mod.rs b/crates/metal2vulkan/src/tests/mod.rs index 722f69a32..0f0460de3 100644 --- a/crates/metal2vulkan/src/tests/mod.rs +++ b/crates/metal2vulkan/src/tests/mod.rs @@ -129,6 +129,7 @@ mod engine_private_memory; mod engine_private_render_state; mod engine_profile_f; mod engine_pull_model; +mod engine_quad_loops; mod engine_quad_ops; mod engine_qualified_signature; mod engine_rate_map; diff --git a/docs/API.md b/docs/API.md index 0c7d49426..35fb5fe6d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1461,8 +1461,10 @@ runtime's `Error::basis` answers a translation error so. `precision_notes` (a `PrecisionNote`, each documenting its bound), and `reconvergence` says whether subgroup reconvergence after divergence matches Metal's -(`Reconvergence::ImplementationDefined` where the profile lacks maximal reconvergence). A note -that holds only under some bound values is in `specialized_notes`; +(`Reconvergence::ImplementationDefined` where the profile lacks maximal reconvergence and the +stage holds a group operation or barrier that depends on it, or a fragment function's derivative, +implicit-LOD sample or LOD query in a loop that a back edge re-enters from inside a selection). A +note that holds only under some bound values is in `specialized_notes`; `stage.precision_notes_bound(&specialization, &|key| bound(key))` gives the notes a pipeline created under `specialization` reaches where a draw or dispatch binds the values `bound` gives. Section 9 lists every note. @@ -1566,7 +1568,13 @@ bound. divergent control flow the device decides which lanes run it together, where Metal's lanes reconverge maximally, so such an operation may see other lanes active than Metal's. Under subgroup-uniform control flow (`shaderSubgroupUniformControlFlow`) the lanes reconverge where - control flow is uniform. Static per stage: recorded for any tangled instruction in the entry. + control flow is uniform. A fragment function's derivatives, implicit-LOD samples and LOD + queries count only inside a loop that a back edge re-enters from inside a selection (a + `continue` there, or two latches): Metal leaves derivatives undefined within nonuniform control + flow, SPIR-V reconverges the quad wherever it rejoins at a merge, and only maximal + reconvergence rejoins it at such a loop's next iteration. Elsewhere such an entry states no + reconvergence mode on any device and records no note. Static per stage: recorded for any such + instruction in the entry. - `metal2vulkan-degrade-simdgroup-access-order` (precision). `SimdgroupAccessOrder`: A kernel holds two accesses of threadgroup or device memory, at least one a write, that different threads of one SIMD-group may make to the same bytes between two barriers, and no barrier or atomic