identity: the emulated tier's barriers run only in a threadgroup of more than one thread

Under the identity domains, each workgroup barrier the emulated simdgroup tier emits for its
exchanges and votes (Emu::barrier, the emulated vote) opens a block that a branch on 1 < N
enters, N the threadgroup's threads: an OpSpecConstantOp ULessThan of the local-size constants,
so the specialization decides it and every invocation takes the same arm. A threadgroup of one
thread exchanges with itself alone, in program order, and executes none of those barriers.
The default domains (Device::new) emit the barriers unconditionally, as before. A Metal
simdgroup_barrier that the tier widens to a workgroup barrier is the kernel's own and stays.

SEMANTICS_VERSION 2156: the emulated modules of the identity domains change.
This commit is contained in:
Anees Iqbal committed 2026-11-17 11:25:09 -08:00
1 parent b206c48b2a
commit 03a3741772
4 files changed
+230 -17

No files matched your search

+1 -1
View File
@@ -61,7 +61,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 = 2155;
pub const SEMANTICS_VERSION: u32 = 2156;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
+11 -1
View File
@@ -277,6 +277,11 @@ pub struct SimdPlan {
/// 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,
/// In the `Emulated` tier under the identity domains, the tier's exchange and vote barriers
/// run under a workgroup-uniform branch on `1 < N`, the threadgroup's threads: a threadgroup
/// of one thread exchanges with itself alone, in program order, and executes none of them
/// (`workgroup::Declared::several`).
pub guarded_barriers: bool,
/// The predicated walk of a kernel with a synchronization outside workgroup-uniform control
/// flow: an emulated site or threadgroup barrier in the `Emulated` tier, a workgroup barrier in
/// every other tier.
@@ -648,7 +653,12 @@ pub fn declare(
return Ok(Declared {
lane: Some(lane),
size: None,
emu: Some(workgroup::declare(mb, plan.stage, simd.exchange_words)?),
emu: Some(workgroup::declare(
mb,
plan.stage,
simd.exchange_words,
simd.guarded_barriers,
)?),
vote: None,
});
}
+63 -13
View File
@@ -87,6 +87,7 @@ use crate::memory::arena::MIN_ARENA_BYTES;
use crate::memory::leaf::Coherence;
use crate::pipeline::facts::RuntimeFact;
use crate::pipeline::sym::{SpecKey, Stage};
use crate::spirv::builder::constructs::{ArmEnd, ArmFn};
use crate::spirv::builder::{FunctionBuilder, ModuleBuilder};
use crate::spirv::error::{BResult, BuildError, Dangling};
use crate::spirv::ids::{ConstId, DemoteTy, GlobalId, TypeId, Value as SValue};
@@ -419,6 +420,7 @@ pub fn check(
cx.families.simd.implementation_defined = false;
}
cx.families.simd.exchange_words = words;
cx.families.simd.guarded_barriers = crate::lower::access::identity(cx.profile);
cx.families.simd.predication = predication;
if let Some(fact) = fact {
cx.facts.insert(fact);
@@ -455,13 +457,18 @@ fn divergent_site(
None
}
/// The emulated tier's module-scope objects: the threadgroup's thread count and the scratch.
/// The emulated tier's module-scope objects: the threadgroup's thread count, the scratch, and the
/// condition its barriers run under.
#[derive(Clone, Copy, Debug)]
pub struct Declared {
/// `sx·sy·sz`, an `OpSpecConstantOp`.
pub threads: ConstId,
/// The scratch array, when the function exchanges values.
pub scratch: Option<GlobalId>,
/// `1 < sx·sy·sz`, an `OpSpecConstantOp`, where the plan guards the tier's barriers
/// (`SimdPlan::guarded_barriers`) and the function exchanges values: each exchange and vote
/// barrier runs only where it holds, a branch the specialization decides.
pub several: Option<ConstId>,
}
fn u32_ty(mb: &mut ModuleBuilder) -> BResult<TypeId> {
@@ -482,9 +489,15 @@ fn konst(mb: &mut ModuleBuilder, v: u32) -> BResult<ConstId> {
/// Declare the thread count and, for a function that exchanges `words` per lane, the scratch
/// in `Workgroup` memory: one slot per lane of `(N + 31) & ~31`, a `u32` or, for more than one
/// word, a `u32[words]`, so a word's pointer is one access chain at the lane and the constant
/// word with no slot arithmetic. The local-size constants are the dispatch family's for the `stage`
/// (`SpecKey::dispatch_keys`, default 1).
pub fn declare(mb: &mut ModuleBuilder, stage: Stage, words: u32) -> BResult<Declared> {
/// word with no slot arithmetic; with `guarded` the condition `1 < N` its barriers run under. The
/// local-size constants are the dispatch family's for the `stage` (`SpecKey::dispatch_keys`,
/// default 1).
pub fn declare(
mb: &mut ModuleBuilder,
stage: Stage,
words: u32,
guarded: bool,
) -> BResult<Declared> {
let u32_ = u32_ty(mb)?;
let [sx, sy, sz] = SpecKey::dispatch_keys(stage)
.local
@@ -495,8 +508,16 @@ pub fn declare(mb: &mut ModuleBuilder, stage: Stage, words: u32) -> BResult<Decl
return Ok(Declared {
threads,
scratch: None,
several: None,
});
}
let several = if guarded {
let one = konst(mb, 1)?;
let bool_ = mb.ty(Type::Bool)?;
Some(mb.spec_op(SpecOp::ULessThan, bool_, &[one, threads])?)
} else {
None
};
let up = konst(mb, SIMD_WIDTH - 1)?;
let mask = konst(mb, !(SIMD_WIDTH - 1))?;
let padded = mb.spec_op(SpecOp::IAdd, u32_, &[threads, up])?;
@@ -520,6 +541,7 @@ pub fn declare(mb: &mut ModuleBuilder, stage: Stage, words: u32) -> BResult<Decl
Ok(Declared {
threads,
scratch: Some(scratch),
several,
})
}
@@ -537,6 +559,8 @@ pub struct Emu {
/// exchange publishes after its values: a lane whose flag is clear is inactive. `None`: every
/// lane inside the threadgroup is active.
active: Option<SValue>,
/// `1 < N`, where the plan guards the tier's barriers ([`Declared::several`]).
several: Option<SValue>,
}
/// Words published by [`Emu::publish`]: each value's first word and type, and the index in
@@ -552,12 +576,17 @@ pub(super) fn emu(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<
return Err(cx.fail("the emulated simdgroup tier is not declared"));
};
let n = fb.module().const_value(d.threads)?;
let several = match d.several {
Some(c) => Some(fb.module().const_value(c)?),
None => None,
};
let flags = MemFlags {
threadgroup: true,
..MemFlags::default()
};
Ok(Emu {
n,
several,
scratch: d.scratch,
stride: cx.plan.families.simd.exchange_words,
coherence: memory_model::coherence(cx.plan),
@@ -590,26 +619,27 @@ pub fn vote(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, live: SValue) ->
let zero = k(fb, 0)?;
let one = k(fb, 1)?;
let p = fb.module().global_value(word)?;
return vote_at(fb, p, sem, live, (zero, one));
return vote_at(fb, p, (sem, None), live, (zero, one));
}
let e = emu(cx, fb)?;
let zero = k(fb, 0)?;
let one = k(fb, 1)?;
let p = e.word_ptr(fb, zero, 0)?;
vote_at(fb, p, e.sem, live, (zero, one))
vote_at(fb, p, (e.sem, e.several), live, (zero, one))
}
/// [`vote`] in the word at `p`, with workgroup barriers of semantics `sem`.
/// [`vote`] in the word at `p`, with workgroup barriers of semantics `sem`, each under `several`
/// where it is given ([`guarded_barrier`]).
fn vote_at(
fb: &mut FunctionBuilder<'_>,
p: SValue,
sem: Semantics,
(sem, several): (Semantics, Option<SValue>),
live: SValue,
(zero, one): (SValue, SValue),
) -> BResult<SValue> {
let relaxed = Semantics::RELAXED;
fb.atomic_store(p, Scope::Workgroup, relaxed, zero)?;
fb.control_barrier(Scope::Workgroup, Scope::Workgroup, sem)?;
guarded_barrier(fb, sem, several)?;
let bit = fb.select(live, one, zero)?;
fb.atomic(
crate::spirv::ir::AtomicOp::Or,
@@ -618,12 +648,31 @@ fn vote_at(
relaxed,
bit,
)?;
fb.control_barrier(Scope::Workgroup, Scope::Workgroup, sem)?;
guarded_barrier(fb, sem, several)?;
let x = fb.atomic_load(p, Scope::Workgroup, relaxed)?;
fb.control_barrier(Scope::Workgroup, Scope::Workgroup, sem)?;
guarded_barrier(fb, sem, several)?;
fb.binary(BinOp::INotEqual, x, zero)
}
/// A workgroup barrier of semantics `sem`, and with `several` (`1 < N`, a specialization
/// constant, so workgroup uniform) only where it holds: one thread orders its own accesses in
/// program order, and a threadgroup of one executes no barrier.
fn guarded_barrier(
fb: &mut FunctionBuilder<'_>,
sem: Semantics,
several: Option<SValue>,
) -> BResult<()> {
let Some(several) = several else {
return fb.control_barrier(Scope::Workgroup, Scope::Workgroup, sem);
};
let then: ArmFn<'_, ()> = Box::new(move |fb, _| {
fb.control_barrier(Scope::Workgroup, Scope::Workgroup, sem)?;
Ok(ArmEnd::FallThrough(Vec::new()))
});
fb.if_(&mut (), several, then, None)?;
Ok(())
}
/// Declare the workgroup word a predicated kernel outside the emulated tier votes in.
pub fn declare_vote(mb: &mut ModuleBuilder) -> BResult<GlobalId> {
let u32_ = u32_ty(mb)?;
@@ -631,9 +680,10 @@ pub fn declare_vote(mb: &mut ModuleBuilder) -> BResult<GlobalId> {
}
impl Emu {
/// A workgroup barrier over the scratch.
/// A workgroup barrier over the scratch, where the plan guards it only in a threadgroup of
/// more than one thread ([`guarded_barrier`]).
pub fn barrier(&self, fb: &mut FunctionBuilder<'_>) -> BResult<()> {
fb.control_barrier(Scope::Workgroup, Scope::Workgroup, self.sem)
guarded_barrier(fb, self.sem, self.several)
}
/// A pointer to word `i` of lane `lane`'s slot: the slot's element `i` ([`declare`]).
@@ -27,10 +27,14 @@
//! same elements, with no handle table and no descriptor.
//! - A kernel that samples a texture (`engine/a2_dynamic_texel_offset`) is still refused as
//! `Unsupported{IdentityDomains}`, not implemented, where the default domains compile it.
//! - A kernel's emulated-simdgroup variant (`engine/gsm2_simd_products`'s `simd_float_products`)
//! opens every barrier of its exchanges under a branch on `1 < N`, which the default domains do
//! not; on the CPU interpreter a threadgroup of one thread passes no barrier, and threadgroups of
//! one and of 80 threads (a partial simdgroup of 16) answer Metal's products.
//!
//! `llvm-as` assembles the kernels; without it the tests skip visibly.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::atomic::{AtomicU64, Ordering};
use crate::device::profile::{DeviceProfile, HandleDomain, PointerDomain};
@@ -51,7 +55,10 @@ use crate::pipeline::testing::{
compile, compile_kept, compile_with, engine_dir, link_and_validate, llvm_assemble, profile,
typed_module_with, AssembleError,
};
use crate::spirv::interp::{run, run_with_images, Buffer, Config, Image, Resources};
use crate::spirv::interp::{
run, run_with_images, BarrierRule, Buffer, Config, Image, Order, Resources,
};
use crate::spirv::testing::spirv_dis;
use crate::vk;
/// Profiles with `bufferDeviceAddress` and `shaderInt64`.
@@ -966,3 +973,149 @@ fn a_partial_threadgroups_variant_answers_the_edge_threadgroups_of_a_ragged_grid
assert_eq!(got.buffers[0], want, "{stem}");
}
}
/// The `OpControlBarrier`s of disassembly `text`: how many open a block that only a branch on
/// `1 < N` (an `OpSpecConstantOp ULessThan` of the constant 1) enters, and how many others.
fn barrier_guards(text: &str) -> (usize, usize) {
let mut conditions = BTreeSet::new();
let mut guarded = BTreeSet::new();
let mut block = "";
let mut first = false;
let (mut inside, mut outside) = (0, 0);
for line in text.lines() {
let words: Vec<&str> = line.split_whitespace().collect();
match words[..] {
[id, "=", "OpSpecConstantOp", "%bool", "ULessThan", "%uint_1", _] => {
conditions.insert(id);
}
[label, "=", "OpLabel"] => {
block = label;
first = true;
continue;
}
["OpBranchConditional", condition, then, _] if conditions.contains(condition) => {
guarded.insert(then);
}
["OpControlBarrier", ..] if first && guarded.contains(block) => inside += 1,
["OpControlBarrier", ..] => outside += 1,
_ => {}
}
first = false;
}
(inside, outside)
}
/// The input of thread `t` of the simdgroup products: 2, 0.5 and 1 in both signs, so every
/// product is exact in any order.
fn simd_input(t: u32) -> f32 {
let lane = t % 32;
let sign = if lane % 2 == 0 { 1.0 } else { -1.0 };
match lane {
0..8 => 2.0 * sign,
8..14 => 0.5 * sign,
_ if lane % 3 == 0 => -1.0,
_ => 1.0,
}
}
/// Under the identity domains the emulated tier's barriers run only in a threadgroup of more
/// than one thread: each opens a block a branch on `1 < N` enters, a threadgroup of one passes
/// none, and threadgroups of one and of 80 threads answer Metal's products, the last simdgroup of
/// 80 holding 16 threads. The default domains keep every barrier unconditional.
#[test]
fn the_emulated_tiers_barriers_run_only_in_a_threadgroup_of_several_threads() {
let Some(bc) = assemble("gsm2_simd_products") else {
return;
};
const ENTRY: &str = "simd_float_products";
const INPUT: u64 = 0x5_0000_0000;
let mut inputs = LowerInputs::new();
inputs.emulated_simdgroups = true;
for stem in PROFILES {
let plain = profile(stem, DevicePolicy::default()).unwrap_or_else(|e| panic!("{e}"));
let a = compile_with(&bc, ENTRY, &plain, &inputs).unwrap_or_else(|e| panic!("{stem}: {e}"));
let (_, words) = link_and_validate(&a, &plain).unwrap_or_else(|e| panic!("{stem}: {e}"));
let (inside, outside) = barrier_guards(&spirv_dis(&words));
assert!(
inside == 0 && outside > 0,
"{stem}: the default domains guard {inside} barriers and leave {outside}"
);
let p = profile(stem, identity()).unwrap_or_else(|e| panic!("{e}"));
let a = compile_with(&bc, ENTRY, &p, &inputs).unwrap_or_else(|e| panic!("{stem}: {e}"));
let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{stem}: L3: {e}"));
let text = spirv_dis(&words);
let (inside, outside) = barrier_guards(&text);
assert!(
inside > 0 && outside == 0,
"{stem}: {inside} barriers guarded, {outside} not\n{text}"
);
let (plan, module) =
typed_module_with(&bc, ENTRY, &p, &inputs).unwrap_or_else(|e| panic!("{stem}: {e}"));
for n in [1u32, 80] {
let input: Vec<u8> = (0..n).flat_map(|t| simd_input(t).to_le_bytes()).collect();
let mut want = Vec::new();
for t in 0..n {
let base = t - t % 32;
let group = (base..n.min(base + 32)).map(simd_input);
let product: f32 = group.clone().product();
let inclusive: f32 = group.clone().take((t - base + 1) as usize).product();
let exclusive: f32 = group.clone().take((t - base) as usize).product();
let negated: f32 = group.map(|x| -x).product();
want.extend([product, inclusive, exclusive, negated].map(f32::to_bits));
}
let region = region_bytes([0; 3], [n, 1, 1], [n, 1, 1]).expect("packs");
let mut push = vec![0u8; plan.push.push_range.map_or(0, |(_, end)| end as usize)];
for f in &plan.push.fields {
let PushLoc::Push { offset } = f.loc else {
panic!("{f:?} spilled");
};
let o = offset as usize;
match f.field {
PushField::SlotGuestBase(s) if s == slot(0) => {
push[o..o + 8].copy_from_slice(&INPUT.to_le_bytes())
}
PushField::SlotGuestBase(s) if s == slot(1) => {
push[o..o + 8].copy_from_slice(&OUT.to_le_bytes())
}
PushField::DispatchRegion => push[o..o + 32].copy_from_slice(&region),
_ => panic!("unexpected push field {f:?}"),
}
}
let res = Resources {
buffers: vec![
Buffer {
slot: None,
address: Some(INPUT),
bytes: input,
},
Buffer {
slot: None,
address: Some(OUT),
bytes: vec![0; 16 * n as usize],
},
],
push,
spec: local_size(n),
};
for order in [Order::Forward, Order::Reverse] {
let cfg = Config {
order,
barriers: BarrierRule::Vulkan,
..Config::default()
};
let got = run(&module, &cfg, res.clone())
.unwrap_or_else(|e| panic!("{stem} {n} {order:?}: {e}"));
let words: Vec<u32> = got.buffers[1]
.chunks(4)
.map(|w| u32::from_le_bytes(w.try_into().expect("a word")))
.collect();
assert_eq!(words, want, "{stem}: a threadgroup of {n} {order:?}");
let passed = got.invocations.iter().map(|i| i.barriers).max();
match n {
1 => assert_eq!(passed, Some(0), "{stem}: one thread passes no barrier"),
_ => assert!(passed > Some(0), "{stem}: {n} threads exchange"),
}
}
}
}
}