SEMANTICS 2132 / RUNTIME 2413: Kernel constant buffers on the Iris: a uniform view and its storage twin

What: on a profile that takes DriverWorkaround::PushReadsLengthenThreadPayload (ANV on the Iris Xe of
RPL-P), a kernel's uniform view (a read-only constant buffer whose window fits maxUniformBufferRange)
also binds its range as a storage buffer, its storage twin (DescriptorView::UniformWithStorageTwin,
ResourceKind::StorageTwin, BindingSource::StorageTwin). Each load selects, on the slot's
RangeAtBindOffset key, the twin read at the bind offset alone (key 1: a bind at an offset the class
divides, inline bytes, or unbound) or the uniform view at its residual (key 0). Specialization folds
the selection. The binder writes the twin from the slot's own source with a second descriptor range
starting at the bind offset. A twin's kind sorts last, so link numbers put a stage's twins after its
other bindings (docs/API.md section 5). Render stages and every other profile are unchanged: no twin
is declared and translation output is the same.

Why: on the Iris (m3-max-34275, dispatch_chain, us a dispatch) reading a kernel's constant buffer
through a storage view at its bind offset measured binds 4 142.7 -> 102.1, fixed 143.2 -> 101.3, tex
119.6 -> 74.4; at a non-zero residual the storage view lost (moved 143.1 -> 154.0), so the uniform view
keeps the residual case. Creation makes the key and its general form together (RUNTIME 2410), so no
first-use making.

Also: the cache codec lists the new variants; the interpreter binds a twin with no buffer of its own
to its slot's buffer; the device-replay tests name the twin's symbol. Docs: API.md section 5, the
workaround, the DEFECTS row, residual.rs, views.rs.

Verified in the lane: m3-max-34780 (at 7a862493b8) clippy -D warnings, metal2vulkan, runtime and
validation, all targets and features; the metal2vulkan suite 3626 passed, 11 failed: golden_hashes
(re-blessed on development) and 10 fixed at fca91cb055. m3-max-34804 (at fca91cb055) clippy 0. Still
running when landed: nextest over the three crates (34804), the authored compile census on the Iris
profile base against tip (M3), the Iris device tests and dispatch_chain A/B (every arm against base,
the branch-free reference for the folding check).

API: adds DescriptorView::UniformWithStorageTwin, ResourceKind::StorageTwin, BindingSource::StorageTwin
and BufferForm::storage_twin (additive to the enums: a consumer matching them exhaustively must add the
arm; a consumer binding set 0 itself fills the twin as docs/API.md section 5 says).
This commit is contained in:
Anees Iqbal committed 2026-11-15 19:48:21 -08:00
1 parent bcd50aba9f
commit 765997d91f
30 files changed
+859 -73

No files matched your search

@@ -62,7 +62,9 @@
//! specializations and the dispatches' regions take that form before any key is looked up
//! (`RenderVariant::plan`, `Variant::keyed_regions`): off that profile a state's creation makes
//! the one pipeline its draws at every bind offset take, and on it the two the module's
//! **Made at creation, both forms** names. The shapes and plans stay every device's
//! **Made at creation, both forms** names. A kernel's uniform view there has a storage twin
//! (`DescriptorView::UniformWithStorageTwin`), whose key the plan keeps too: at 1 it reads the
//! twin at its bind offset alone, not the uniform view. The shapes and plans stay every device's
//! (`argument_table::AtBindViews`): a bind offset the view base alignment divides still makes a
//! shape and a plan of its own, whose key's uniform views alone take their residual form.
//! - **Only GPU time moves.** Until the key's making lands, its draws' uniform reads take the
@@ -225,10 +227,11 @@ pub(crate) fn residual_form<'a>(
/// `specialization` with each `SpecKey::RangeAtBindOffset` constant of `constants` (a pipeline's
/// stages') whose slot `interface` (the pipeline's) reads through a uniform view at 0, the key a
/// plan takes where the device reads its uniform views at their residuals (the module docs);
/// `None` where every one of them is 0 there already. A storage view's constant, which only a
/// profile taking `DriverWorkaround::PushReadsLengthenThreadPayload` declares, keeps its value: its
/// bind at offset 0 reads no residual word there. Where no storage view declares the key this is
/// [`residual_form`].
/// `None` where every one of them is 0 there already. A storage view's constant, and a uniform
/// view's with a storage twin (`DescriptorView::UniformWithStorageTwin`), which only a profile
/// taking `DriverWorkaround::PushReadsLengthenThreadPayload` declares, keep their values: at its
/// bind offset alone the first reads no residual word there, and the second reads its twin, not
/// its uniform view. Where neither declares the key this is [`residual_form`].
pub(crate) fn uniform_residual_form<'a>(
constants: impl Iterator<Item = &'a SpecConstant> + Clone,
interface: &PipelineInterface,
@@ -236,7 +239,7 @@ pub(crate) fn uniform_residual_form<'a>(
) -> Option<SpecializationKey> {
let uniform = |slot| {
matches!(interface.slots.get(&slot),
Some(SlotInterface::Buffer(b)) if b.form.uniform_view())
Some(SlotInterface::Buffer(b)) if b.form.uniform_view() && !b.form.storage_twin())
};
let constants = constants.map(|constant| (constant.id, constant.key));
residual_form_of(constants, uniform, specialization)
@@ -17,6 +17,8 @@
//! bound to nothing as one bound at offset 0, and makes that key and its residual form both
//! ([`storage_views_keyed`]): `ubo_offsets_kernel`'s output, bound at offset 0, takes the
//! creation's key, and a draw binding a storage view elsewhere takes the residual form at once.
//! There a kernel's constants also have a storage twin, read where their key holds, which a
//! dispatch at an aligned offset or of inline bytes takes, the creation's key.
//!
//! A device test: compiled only under the validation crate's GPU safety cfgs (`m2v_gpu`,
//! `m2v_cpu_icd`), on the kind of device the cfg selects. The functions are those of the owned
@@ -960,6 +962,96 @@ fn kernel_constants_read_at_every_bind_offset() {
}
}
/// A kernel's constants bound at offsets the view base alignment divides (0 and 128, a multiple
/// of every device's) and as inline bytes take the key its creation predicted and made, and make
/// nothing; on a profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload` that key
/// reads them through their storage twin (`DescriptorView::UniformWithStorageTwin`) at their bind
/// offset. Bound then at offset 4, which no alignment divides, they are read through the uniform
/// view at their residual: there a key of its own (the output still read at its bind offset 0),
/// taken through the creation's residual form at once while it is made on the pool, one
/// pipeline; elsewhere the creation's. With the device's pool held, each dispatch reads its bytes.
#[test]
fn kernel_constants_at_aligned_offsets_take_the_creations_key() {
let scratch = Scratch::new("uniform-twin-kernel");
let device = device(&scratch.0);
let queue = device.new_command_queue().unwrap();
let function = library(&device)
.new_function_with_name("ubo_offsets_kernel")
.unwrap();
let keyed = u64::from(storage_views_keyed(&device));
let state = kernel_state(&device, &function);
let created = idle(&device);
let [width, height, depth] = PREDICTED_THREADS;
let threads = Size::new(u64::from(width), u64::from(height), u64::from(depth));
let data = constants();
let constants = device
.new_buffer_with_bytes(&data, ResourceOptions::shared())
.unwrap();
// `None`: inline bytes from offset 8.
let offsets = [Some(0), Some(128), None, Some(4)];
let outputs: Vec<Buffer> = offsets
.iter()
.map(|_| device.new_buffer(16, ResourceOptions::shared()).unwrap())
.collect();
let took = |from: &crate::WorkCounts, to: &crate::WorkCounts| {
(
to.residual_form_draws - from.residual_form_draws,
to.dispatch_pipelines_pooled - from.dispatch_pipelines_pooled,
to.variant_pipelines_made - from.variant_pipelines_made,
)
};
let hold = crate::pipeline::pool::held::hold();
let command_buffer = queue.command_buffer().unwrap();
let mut encoder = command_buffer.compute_command_encoder().unwrap();
encoder.set_compute_pipeline_state(&state).unwrap();
let mut counts = vec![device.work_counts()];
for (offset, output) in offsets.iter().zip(&outputs) {
match offset {
Some(at) => encoder.set_buffer(Some(&constants), *at, 0).unwrap(),
None => encoder.set_bytes(&data[8..24], 0).unwrap(),
}
encoder.set_buffer(Some(output), 0, 1).unwrap();
encoder
.dispatch_threadgroups(Size::new(1, 1, 1), threads)
.unwrap();
counts.push(device.work_counts());
}
encoder.end_encoding().unwrap();
command_buffer.commit().unwrap();
command_buffer
.wait_until_completed_for(WAIT)
.expect("the dispatches' command buffer waits for no making");
assert_eq!(command_buffer.error(), None);
drop(hold);
assert_eq!(
took(&counts[0], &counts[3]),
(0, 0, 0),
"dispatches at 0 and 128 and of inline bytes: residual-form dispatches, regions pooled, \
pipelines made"
);
assert_eq!(
took(&counts[3], &counts[4]),
(keyed, keyed, 0),
"a dispatch at 4: residual-form dispatches, regions pooled, pipelines made"
);
assert_eq!(
idle(&device).variant_pipelines_made - created.variant_pipelines_made,
keyed,
"pipelines made once the pool ran"
);
for (offset, output) in offsets.iter().zip(&outputs) {
let at = offset.unwrap_or(8) as usize / 4;
let words = bytes_of(output);
let read = |w: usize| f32::from_le_bytes(words[w * 4..w * 4 + 4].try_into().unwrap());
let want = |i: usize| i as f32 / 255.0;
assert_eq!(
[read(0), read(1)],
[want(at), want(at + 2)],
"offset {offset:?}"
);
}
}
/// A kernel reads a `device` buffer through a storage view at bind offset 0, then at offsets past
/// it and at 0 again (`engine/buffer_end_byte_load.ll`: `out[0] = in[5]`), and each dispatch reads
/// the bound bytes, whichever form its key takes. On a device whose profile takes
@@ -556,7 +556,10 @@ pub fn containment(
(ContainmentForm::BufferAtomic, atomic_check)
}
DescriptorView::Storage => (ContainmentForm::StorageBuffer, robust),
DescriptorView::UniformWords | DescriptorView::UniformVec4 => {
// A storage twin reads the same range under the same robustness.
DescriptorView::UniformWords
| DescriptorView::UniformVec4
| DescriptorView::UniformWithStorageTwin => {
(ContainmentForm::UniformBuffer, robust)
}
_ => return unknown(),
@@ -650,7 +653,8 @@ pub fn containment(
BufferForm::Descriptor(
DescriptorView::Storage
| DescriptorView::UniformWords
| DescriptorView::UniformVec4,
| DescriptorView::UniformVec4
| DescriptorView::UniformWithStorageTwin,
) => made(target.form, Medium::DescriptorView, robust, false),
_ => unknown(),
},
@@ -84,6 +84,7 @@ fn template() -> ComputeTemplate {
length_class: crate::bind::state::length_class(4096),
},
disjoint: false,
twin: None,
}],
spec: vec![
spec(0, SpecKey::LocalSize(Axis::X)),
+8 -6
View File
@@ -331,7 +331,7 @@ use crate::bind::neutral::{zero_buffer_bytes, NeutralResource};
use crate::bind::plan::compute::{internal, not_implemented, spec_key, tile_memory};
use crate::bind::plan::resources::{separate_samplers, ResourcePlanner};
use crate::bind::plan::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_uses, check_slots,
check_sparse_textures, cross_variant, cubic_variant, heap_raw, heap_ycbcr_writes,
large_view_candidates, mark_disjoint, plan_buffer, psb_variant, range_variant, record_noted,
record_specialized, snapshot_forms, srgb_variant, storage_view_variant,
@@ -2018,7 +2018,8 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
)));
}
let source = match b.source {
BindingSource::Buffer(slot) => {
// A uniform view's storage twin binds the slot's own buffer, at its own range.
BindingSource::Buffer(slot) | BindingSource::StorageTwin(slot) => {
let pb = planned(slot).ok_or_else(|| {
internal(format!("binding of {slot:?} without an interface slot"))
})?;
@@ -2502,7 +2503,7 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
let mut uses: Vec<ResourceUse> = buffers
.iter()
.filter(|b| matches!(b.bound, BoundKind::Buffer { .. }))
.map(|b| buffer_use(b, stage_flags(b.slot.stage)))
.flat_map(|b| buffer_uses(b, stage_flags(b.slot.stage)))
.collect();
// The factors: the control stage's, or an emulated pipeline's scan's.
if factor_binding.is_some()
@@ -5143,8 +5144,8 @@ fn rebinds_into(t: &GraphicsTemplate, slots: &[SlotRef], into: &mut SlotRebinds)
into.vertex.clear();
let changed = |slot: SlotRef| slot.class == SlotClass::Buffer && slots.contains(&slot);
// What the slots decide some other way than below: a stage's argument or root table, a mesh
// or patch draw's own reads, a de-indexed draw's layout, and a uniform view a written slot
// may alias.
// or patch draw's own reads, a de-indexed draw's layout, a uniform view a written slot may
// alias, and a uniform view's storage twin, a second range of its slot.
let other_reads = t
.stages
.iter()
@@ -5152,7 +5153,8 @@ fn rebinds_into(t: &GraphicsTemplate, slots: &[SlotRef], into: &mut SlotRebinds)
|| t.mesh.is_some()
|| t.tessellation.is_some()
|| t.deindexed.is_some()
|| (t.buffers.iter().any(|b| b.disjoint) && t.buffers.iter().any(|b| b.access.write));
|| (t.buffers.iter().any(|b| b.disjoint) && t.buffers.iter().any(|b| b.access.write))
|| t.buffers.iter().any(|b| b.twin.is_some());
// A texture slot's texels a texture buffer's range bounds, which the commands hold.
let texel_range = |slot: &SlotRef| t.resources.texel_buffers.iter().any(|pt| pt.slot == *slot);
let texels = slots
@@ -821,6 +821,7 @@ fn draws_bind_vertex_buffers_at_aligned_offsets_with_their_windows() {
length_class: length_class(4096),
},
disjoint: false,
twin: None,
}],
stages: Vec::new(),
vertex_buffers: vertex_buffers(),
+14 -2
View File
@@ -615,7 +615,9 @@ pub(crate) fn shared_range(
/// offset 0 (`SpecKey::RangeAtBindOffset`, where its profile declares the key, set only where
/// [`starts_at_bind`] holds there, which leaves that range's residual 0), and a uniform view of
/// one where `views_at_residual` (no function reads it at its bind offset alone), take
/// [`shared_range`]'s, where it holds the window;
/// [`shared_range`]'s, where it holds the window; not a uniform view with a storage twin
/// (`DescriptorView::UniformWithStorageTwin`), whose key reads the twin at its bind offset alone
/// whatever `views_at_residual` says;
/// - every other slot takes [`descriptor_range`]'s, which starts at the bind offset aligned down
/// to the descriptor base alignment: a uniform view's key may read it at its bind offset alone,
/// where its residual is 0.
@@ -633,7 +635,8 @@ pub(crate) fn planned_range(
&& end <= pb.max_range
&& end <= 1 << 32;
if !from_start {
let shared = (storage || (views_at_residual && pb.form.uniform_view()))
let at_residual = views_at_residual && !pb.form.storage_twin();
let shared = (storage || (at_residual && pb.form.uniform_view()))
.then(|| shared_range(bind_offset, length, pb.window, pb.alignment, pb.max_range))
.flatten();
return match shared {
@@ -813,6 +816,15 @@ pub(crate) fn bind_buffers(
element: 0,
range,
});
// A uniform view's storage twin binds the same range.
if let Some((set, binding)) = pb.twin {
descriptor_ranges.push(DescriptorRange {
set,
binding,
element: 0,
range,
});
}
out.residuals.push(pb.slot, residual);
}
(BufferForm::Psb, _) => {
@@ -208,6 +208,7 @@ fn planned(window: Window, view: DescriptorView, alignment: u64, max_range: u64)
length_class: crate::bind::state::length_class(1 << 12),
},
disjoint: false,
twin: None,
}
}
@@ -484,6 +485,59 @@ fn bounded_slots_read_at_their_residual_share_one_range_along_a_buffer() {
}
}
/// A uniform view with a storage twin binds its range from its bind offset, its residual 0, also
/// where the consumer reads every uniform view at its residual: its key reads the twin at its
/// bind offset alone. A plain uniform view there shares one range from the buffer's start, the
/// negative control. `bind_buffers` writes the twin's binding with the uniform binding's range.
#[test]
fn a_uniform_view_with_a_storage_twin_binds_its_range_from_its_bind_offset() {
use crate::bind::state::{BindState, BoundBuffer, StageTable};
const CHUNK: u64 = 64 * 1024;
let bounded = Window::Bounded { start: 0, len: 16 };
let mut twin = planned(bounded, DescriptorView::UniformWithStorageTwin, 64, CHUNK);
let plain = planned(bounded, DescriptorView::UniformWords, 64, CHUNK);
for bind_offset in (0..CHUNK).step_by(256) {
for at_residual in [false, true] {
let (range, residual) = planned_range(&twin, bind_offset, CHUNK, at_residual).unwrap();
assert_eq!(
(range.offset, residual),
(bind_offset, 0),
"{bind_offset} {at_residual}"
);
}
let (range, residual) = planned_range(&plain, bind_offset, CHUNK, true).unwrap();
assert_eq!(
(range.offset, u64::from(residual)),
(0, bind_offset),
"{bind_offset}"
);
}
twin.twin = Some((0, 3));
let mut table = StageTable::default();
table.buffers.insert(
twin.slot.index,
BoundBuffer::Buffer {
gpu_address: 0x1_0000,
// `planned`'s length class.
length: 1 << 12,
offset: 256,
device_address: None,
attribute_stride: None,
},
);
let mut state = BindState::default();
state.stages.insert(twin.slot.stage, table);
state.uniform_views_at_residual = true;
let slot = twin.slot;
let (mut ranges, mut extents) = (Vec::new(), Vec::new());
let bound = bind_buffers(&[twin], &state, &mut ranges, &mut extents).unwrap();
let keys: Vec<_> = ranges.iter().map(|r| (r.set, r.binding)).collect();
assert_eq!(keys, [(0, 0), (0, 3)]);
assert_eq!(ranges[0].range, ranges[1].range);
assert_eq!(ranges[0].range.offset, 256);
assert_eq!(bound.residuals.of(slot), Some(0));
}
fn entry(host: u64, guest: u64, size: u64) -> RootEntry {
RootEntry {
host,
+4
View File
@@ -561,6 +561,10 @@ pub(crate) struct PlannedBuffer {
/// its window (`RuntimeFact::UniformViewAliasing`).
#[cfg_attr(feature = "serde", serde(default))]
pub disjoint: bool,
/// `(set, binding)` of the slot's storage twin (`DescriptorView::UniformWithStorageTwin`),
/// written with the slot's own buffer and range.
#[cfg_attr(feature = "serde", serde(default))]
pub twin: Option<(u32, u32)>,
}
/// What a shape binds at a buffer slot.
+4 -3
View File
@@ -61,7 +61,7 @@
use super::resources::{separate_samplers, ResourcePlanner};
use super::slots::{
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_use, check_slots,
address_map_variant, anisotropic_variant, bindings, bound_value, buffer_uses, check_slots,
check_sparse_textures, cross_variant, cubic_variant, heap_raw, heap_ycbcr_writes,
mark_disjoint, plan_buffer, psb_variant, record_noted, record_specialized, srgb_variant,
storage_view_variant, texel_buffer_parts_variant, used_uses, ycbcr_in_place_variant,
@@ -574,7 +574,8 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
)));
}
let source = match b.source {
BindingSource::Buffer(slot) => {
// A uniform view's storage twin binds the slot's own buffer, at its own range.
BindingSource::Buffer(slot) | BindingSource::StorageTwin(slot) => {
let pb = planned(slot).ok_or_else(|| {
internal(format!("binding of {slot:?} without an interface slot"))
})?;
@@ -828,7 +829,7 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
let mut uses: Vec<ResourceUse> = buffers
.iter()
.filter(|b| matches!(b.bound, BoundKind::Buffer { .. }))
.map(|b| buffer_use(b, compute_stage))
.flat_map(|b| buffer_uses(b, compute_stage))
.collect();
uses.extend(used_uses(
&shape.used,
+44 -23
View File
@@ -155,6 +155,15 @@ pub(crate) fn plan_buffer(
None
}
};
let twin = match b.form.storage_twin() {
true => Some(
bindings
.get(&BindingSource::StorageTwin(slot))
.copied()
.ok_or_else(|| internal(format!("slot {slot:?} has no storage twin binding")))?,
),
false => None,
};
Ok(PlannedBuffer {
slot,
window: b.window,
@@ -165,6 +174,7 @@ pub(crate) fn plan_buffer(
max_range,
bound,
disjoint: false,
twin,
})
}
@@ -182,8 +192,9 @@ pub(crate) fn plan_buffer(
/// nothing has the residual 0 (`instantiate::slot_field`), so either form reads the Metal offset
/// alone of the same descriptor: a uniform view's takes false, the form that reads at the
/// residual, which keeps the key of a draw that leaves the slot unbound the key that reads every
/// such slot at its residual; a storage view's takes what a bind at offset 0 takes, the
/// commonest bind, so that a plan of nothing bound, which a consumer makes before any draw binds
/// such slot at its residual; a storage view's, and a uniform view's with a storage twin
/// (`DescriptorView::UniformWithStorageTwin`), whose key reads the twin, take what a bind at
/// offset 0 takes, the commonest bind, so that a plan of nothing bound, which a consumer makes before any draw binds
/// the slot (the runtime's creation, `pipeline/predicted.rs` and `pipeline/dispatch_making.rs`,
/// and a warm pass's replay of a dispatch, `pipeline/dispatch_record.rs`), names the key of the
/// draw that binds it there.
@@ -207,7 +218,7 @@ pub(crate) fn range_at_bind_offset(
offset_alignment, ..
}) => u64::from(offset_alignment),
Some(BufferShape::Bytes { .. }) => 0,
None if !b.form.uniform_view() => 0,
None if !b.form.uniform_view() || b.form.storage_twin() => 0,
None => return false,
};
let alignment = crate::memory::views::base_alignment(min);
@@ -999,27 +1010,37 @@ pub(crate) fn range_variant(slot: SlotRef, bound: BoundKind, profile: &DevicePro
&& matches!(bound, BoundKind::Buffer { length_class, .. } if !class_fits(length_class, storage))
}
/// The `uses` entry of a bound buffer slot: its proven access, `Uniform` for a uniform view and
/// The `uses` entries of a bound buffer slot: its proven access, `Uniform` for a uniform view and
/// `Storage` otherwise, `stages`, and the window as a range when it starts at or after the bind
/// offset.
pub(crate) fn buffer_use(b: &PlannedBuffer, stages: vk::PipelineStageFlags2) -> ResourceUse {
ResourceUse {
resource: UseTarget::Slot(b.slot),
access: b.access,
class: if b.form.uniform_view() {
AccessClass::Uniform
} else {
AccessClass::Storage
},
stages,
range: match b.window {
Window::Bounded { start, len } if start >= 0 => Some(ByteRange {
offset: start as u64,
len,
}),
_ => None,
},
}
/// offset; a uniform view's storage twin (`DescriptorView::UniformWithStorageTwin`) reads the
/// same bytes as a storage buffer, a `Storage` use of them beside the `Uniform` one.
pub(crate) fn buffer_uses(
b: &PlannedBuffer,
stages: vk::PipelineStageFlags2,
) -> impl Iterator<Item = ResourceUse> {
let class = if b.form.uniform_view() {
AccessClass::Uniform
} else {
AccessClass::Storage
};
let twin = b.form.storage_twin().then_some(AccessClass::Storage);
let (slot, access) = (b.slot, b.access);
let range = match b.window {
Window::Bounded { start, len } if start >= 0 => Some(ByteRange {
offset: start as u64,
len,
}),
_ => None,
};
std::iter::once(class)
.chain(twin)
.map(move |class| ResourceUse {
resource: UseTarget::Slot(slot),
access,
class,
stages,
range,
})
}
/// The `uses` of the used resources a pipeline can reach (the handback): buffers and heaps when a
@@ -66,6 +66,7 @@ fn planned(index: u32, bound: BoundKind, form: BufferForm) -> PlannedBuffer {
max_range: 0,
bound,
disjoint: false,
twin: None,
}
}
@@ -708,6 +709,97 @@ fn a_storage_range_starts_at_the_bind_offset_only_at_offset_0() {
}
}
/// A uniform view with a storage twin (`DescriptorView::UniformWithStorageTwin`) takes a uniform
/// view's `RangeAtBindOffset` wherever its slot is bound (a buffer at each offset class, inline
/// bytes), on every committed profile and under each window, and bound to nothing what a bind at
/// offset 0 takes, where a plain uniform view takes false. Its plan names the twin's binding, and
/// a plan of the layout without one is refused.
#[test]
fn a_storage_twin_takes_a_uniform_views_key_and_offset_0_s_unbound() {
for (stem, p) in committed_profiles().expect("profiles") {
let limits = &p.fields().limits;
let alignment =
crate::memory::views::base_alignment(limits.min_uniform_buffer_offset_alignment);
for window in [
Window::Bounded { start: 0, len: 64 },
Window::Bounded { start: 4, len: 28 },
Window::Bounded { start: -8, len: 40 },
] {
let slot_of = |view| BufferSlot {
access: AccessSet::READ,
window,
form: BufferForm::Descriptor(view),
kind: BufferKind::Buffer,
};
let (twin, plain) = (
slot_of(DescriptorView::UniformWithStorageTwin),
slot_of(DescriptorView::UniformWords),
);
let what = format!("{stem} {window:?}");
for bind_offset in [0, 4, 16, 20, 64, 260, 1024] {
let shape = BoundBuffer::Buffer {
gpu_address: 0x1_0000,
length: 4096,
offset: bind_offset,
device_address: None,
attribute_stride: None,
}
.shape(alignment as u32);
assert_eq!(
range_at_bind_offset(&twin, Some(&shape), limits),
range_at_bind_offset(&plain, Some(&shape), limits),
"{what} {bind_offset}"
);
}
let bytes = BufferShape::Bytes {
attribute_stride: None,
};
assert_eq!(
range_at_bind_offset(&twin, Some(&bytes), limits),
range_at_bind_offset(&plain, Some(&bytes), limits),
"{what} bytes"
);
let at_0 = BoundBuffer::Buffer {
gpu_address: 0x1_0000,
length: 4096,
offset: 0,
device_address: None,
attribute_stride: None,
}
.shape(alignment as u32);
assert_eq!(
range_at_bind_offset(&twin, None, limits),
range_at_bind_offset(&twin, Some(&at_0), limits),
"{what} unbound"
);
assert!(
!range_at_bind_offset(&plain, None, limits),
"{what} unbound"
);
let both = [
(BindingSource::Buffer(slot(0)), (0, 0)),
(BindingSource::StorageTwin(slot(0)), (0, 3)),
]
.into();
let pb = plan_buffer((slot(0), &twin, Some(&at_0)), false, limits, &both)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(
(pb.binding, pb.twin),
(Some((0, 0)), Some((0, 3))),
"{what}"
);
let pb = plan_buffer((slot(0), &plain, Some(&at_0)), false, limits, &both)
.unwrap_or_else(|e| panic!("{what}: {e:?}"));
assert_eq!(pb.twin, None, "{what}");
let alone = [(BindingSource::Buffer(slot(0)), (0, 0))].into();
assert!(
plan_buffer((slot(0), &twin, Some(&at_0)), false, limits, &alone).is_err(),
"{what}: no twin binding"
);
}
}
}
/// A slot whose function observes residency (`RuntimeFact::SparseTexture`) binds a texture that is
/// not sparse (or nothing) on every profile, and a sparse one where the module has the sparse arm
/// or the tile-map arm; without either a sparse texture is refused, naming
+3 -1
View File
@@ -873,6 +873,7 @@ codec_enum! {
SnapshotTexels(f0),
YCbCrPlanes(f0),
SamplerArray { compare, integer },
StorageTwin,
}
AccelerationStructureLevel { Primitive, Instance }
SamplerRef { Slot(f0), Constexpr(f0) }
@@ -1201,7 +1202,7 @@ codec_enum! {
Window { Bounded { start, len }, Whole }
BufferForm { Descriptor(f0), Psb }
BufferKind { Buffer, VisibleFunctionTable, IntersectionFunctionTable }
DescriptorView { Storage, UniformWords, UniformVec4 }
DescriptorView { Storage, UniformWords, UniformVec4, UniformWithStorageTwin }
PushLoc { Push { offset }, ArgumentTable { offset } }
IoRole {
Attribute { index }, Varying { user, interpolation },
@@ -1534,6 +1535,7 @@ codec_enum! {
SnapshotTexels(f0),
YCbCrPlanes(f0),
SamplerArray { stage, compare, integer },
StorageTwin(f0),
}
VertexStride { Static(f0), PerBind }
}
+2 -2
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 = 2131;
pub const SEMANTICS_VERSION: u32 = 2132;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -94,7 +94,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 523;
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
/// keeps no history.
pub const RUNTIME_VERSION: u32 = 2412;
pub const RUNTIME_VERSION: u32 = 2413;
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
@@ -894,7 +894,9 @@ const fn moltenvk_on_apple<F>(fact: F) -> Measured<F> {
/// reads its storage views at their bind offsets, which a command binding them at offset 0, the
/// commonest bind, takes, and its general form, which one binding a storage view elsewhere takes
/// at once; with the general form alone, every state's first command at offset 0 made a second
/// pipeline.
/// pipeline. There a kernel's uniform view also binds a storage twin of its range, which it
/// reads at its bind offset alone where its key holds (`DescriptorView::UniformWithStorageTwin`;
/// the workaround's own documentation holds the figures).
pub(crate) const DEFECTS: &[Measured<DriverWorkaround>] = &[
Measured {
fact: DriverWorkaround::BothBarycentricFormsRejected,
+10 -6
View File
@@ -1585,12 +1585,16 @@ pub enum DriverWorkaround {
/// The runtime's creation of a state makes that key and, beside it and at the same time, its
/// general form, every view read at its residual, which a command binding a storage view
/// elsewhere takes at once while its own key is made: otherwise one of the two would be a
/// second pipeline made at the state's first command. It reads
/// a uniform view at its residual there, as on every device without
/// `DriverFact::ConstantOffsetUniformReadsPreloaded`: a kernel of three storage views at offset
/// 0 and inline bytes ran in 161.8 us a dispatch with the bytes' uniform view read at its bind
/// offset and in 142.8 us with it read at its residual (job m3-max-34275). It changes no
/// answer.
/// second pipeline made at the state's first command. A uniform view read at its bind offset
/// alone is no faster there: a kernel of three storage views at offset 0 and inline bytes ran
/// in 161.8 us a dispatch with the bytes' uniform view read so and in 142.8 us with it read at
/// its residual, and in 102.1 us with the bytes read through a storage view at their bind
/// offset (job m3-max-34275). So a kernel's uniform view there also has a storage twin
/// (`DescriptorView::UniformWithStorageTwin`, `lower::access`): a storage
/// buffer of the uniform view's own range, which the kernel reads instead where the slot's
/// key holds (a bind offset the view base alignment divides, inline bytes, nothing bound), and
/// elsewhere the uniform view at its residual, as on every device without
/// `DriverFact::ConstantOffsetUniformReadsPreloaded`. It changes no answer.
PushReadsLengthenThreadPayload,
}
@@ -1120,8 +1120,9 @@ fn on_target(fb: &mut FunctionBuilder<'_>, p: Prepared, o: Op) -> BResult<Option
let addr = m.word_address(fb, word)?;
device_ptr(fb, addr, pointee)?
}
// Selection moved every slot of a typed atomic to its device address.
(Mem::View(_), Some(_)) => return Err(dangling()),
// Selection moved every slot of a typed atomic to its device address, and gives a slot
// with a storage twin, a uniform view's, none.
(Mem::View(_), Some(_)) | (Mem::Twin(_), _) => return Err(dangling()),
};
let at = At {
p: ptr,
+125 -10
View File
@@ -144,10 +144,99 @@ fn storage_ptr(fb: &mut FunctionBuilder<'_>, view: View, word: SValue) -> BResul
}
}
/// The word memory of one target: a descriptor view or a device address.
/// The word memory of a slot read through a uniform view and its storage twin
/// (`DescriptorView::UniformWithStorageTwin`): the binder binds both to one range, so one offset
/// names the same byte in each, and each read loads both and selects the twin's where the slot's
/// `RangeAtBindOffset` (`at_bind`) holds. Specialization fixes the constant, so a driver folds the
/// selection and drops the other load. Read-only: selection gives a uniform view no store or
/// atomic. Its units are the uniform view's, which the twin has too (`views::declare_twin`).
#[derive(Clone, Copy, Debug)]
pub(super) struct TwinMem {
uniform: ViewMem,
twin: ViewMem,
at_bind: SValue,
}
impl TwinMem {
fn stored(&self) -> crate::spirv::error::BuildError {
self.uniform.missing()
}
}
impl WordMem for TwinMem {
fn read(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult<SValue> {
let twin = self.twin.read(fb, word)?;
let uniform = self.uniform.read(fb, word)?;
fb.select(self.at_bind, twin, uniform)
}
fn write(&mut self, _: &mut FunctionBuilder<'_>, _: SValue, _: SValue) -> BResult<()> {
Err(self.stored())
}
fn write_bits(
&mut self,
_: &mut FunctionBuilder<'_>,
_: SValue,
_: SValue,
_: SValue,
) -> BResult<()> {
Err(self.stored())
}
fn units(&self) -> Units {
self.uniform.units()
}
fn read_unit(
&mut self,
fb: &mut FunctionBuilder<'_>,
bytes: u32,
index: SValue,
) -> BResult<SValue> {
let twin = self.twin.read_unit(fb, bytes, index)?;
let uniform = self.uniform.read_unit(fb, bytes, index)?;
fb.select(self.at_bind, twin, uniform)
}
fn write_unit(
&mut self,
_: &mut FunctionBuilder<'_>,
_: u32,
_: SValue,
_: SValue,
) -> BResult<()> {
Err(self.stored())
}
fn read_vec(
&mut self,
fb: &mut FunctionBuilder<'_>,
lanes: u32,
index: SValue,
) -> BResult<SValue> {
let twin = self.twin.read_vec(fb, lanes, index)?;
let uniform = self.uniform.read_vec(fb, lanes, index)?;
fb.select(self.at_bind, twin, uniform)
}
fn write_vec(
&mut self,
_: &mut FunctionBuilder<'_>,
_: u32,
_: SValue,
_: SValue,
) -> BResult<()> {
Err(self.stored())
}
}
/// The word memory of one target: a descriptor view, a uniform view and its storage twin, or a
/// device address.
#[derive(Clone, Copy, Debug)]
pub(super) enum Mem {
View(ViewMem),
Twin(TwinMem),
Psb(PsbMem),
}
@@ -156,6 +245,15 @@ impl Mem {
pub(super) fn with(self, ops: WordOps) -> Mem {
match self {
Mem::View(ViewMem(view, _, units)) => Mem::View(ViewMem(view, ops, units)),
Mem::Twin(TwinMem {
uniform: ViewMem(uniform, _, uniform_units),
twin: ViewMem(twin, _, twin_units),
at_bind,
}) => Mem::Twin(TwinMem {
uniform: ViewMem(uniform, ops, uniform_units),
twin: ViewMem(twin, ops, twin_units),
at_bind,
}),
Mem::Psb(m) => Mem::Psb(m.with(ops)),
}
}
@@ -165,6 +263,7 @@ impl WordMem for Mem {
fn read(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue) -> BResult<SValue> {
match self {
Mem::View(m) => m.read(fb, word),
Mem::Twin(m) => m.read(fb, word),
Mem::Psb(m) => m.read(fb, word),
}
}
@@ -172,6 +271,7 @@ impl WordMem for Mem {
fn write(&mut self, fb: &mut FunctionBuilder<'_>, word: SValue, value: SValue) -> BResult<()> {
match self {
Mem::View(m) => m.write(fb, word, value),
Mem::Twin(m) => m.write(fb, word, value),
Mem::Psb(m) => m.write(fb, word, value),
}
}
@@ -185,6 +285,7 @@ impl WordMem for Mem {
) -> BResult<()> {
match self {
Mem::View(m) => m.write_bits(fb, word, mask, bits),
Mem::Twin(m) => m.write_bits(fb, word, mask, bits),
Mem::Psb(m) => m.write_bits(fb, word, mask, bits),
}
}
@@ -192,6 +293,7 @@ impl WordMem for Mem {
fn units(&self) -> Units {
match self {
Mem::View(m) => m.units(),
Mem::Twin(m) => m.units(),
Mem::Psb(m) => m.units(),
}
}
@@ -204,6 +306,7 @@ impl WordMem for Mem {
) -> BResult<SValue> {
match self {
Mem::View(m) => m.read_vec(fb, lanes, index),
Mem::Twin(m) => m.read_vec(fb, lanes, index),
Mem::Psb(m) => m.read_vec(fb, lanes, index),
}
}
@@ -217,6 +320,7 @@ impl WordMem for Mem {
) -> BResult<()> {
match self {
Mem::View(m) => m.write_vec(fb, lanes, index, value),
Mem::Twin(m) => m.write_vec(fb, lanes, index, value),
Mem::Psb(m) => m.write_vec(fb, lanes, index, value),
}
}
@@ -229,6 +333,7 @@ impl WordMem for Mem {
) -> BResult<SValue> {
match self {
Mem::View(m) => m.read_unit(fb, bytes, index),
Mem::Twin(m) => m.read_unit(fb, bytes, index),
Mem::Psb(m) => m.read_unit(fb, bytes, index),
}
}
@@ -242,6 +347,7 @@ impl WordMem for Mem {
) -> BResult<()> {
match self {
Mem::View(m) => m.write_unit(fb, bytes, index, value),
Mem::Twin(m) => m.write_unit(fb, bytes, index, value),
Mem::Psb(m) => m.write_unit(fb, bytes, index, value),
}
}
@@ -292,15 +398,10 @@ pub(super) fn prepare(
// Where the binder starts a view's range at the bind offset (`RangeAtBindOffset`: a uniform
// view's, or a storage view's where the plan declares it), the residual is 0: the offset alone,
// a constant for a constant member, which a driver can push, and no push word read.
let off = match cx
.decl
.families
.access
.at_bind
.get(t.slot)
let at_bind = (cx.decl.families.access.at_bind.get(t.slot))
.copied()
.flatten()
{
.flatten();
let off = match at_bind {
Some(at_bind) => fb.select(at_bind, m, shifted)?,
None => shifted,
};
@@ -332,8 +433,22 @@ pub(super) fn prepare(
.get(t.slot)
.copied()
.unwrap_or(UnitViews::NONE);
let mem = ViewMem(view, ops, units);
// A uniform view's storage twin is read where its key holds, at the same offset.
let twin = (cx.decl.families.access.twins.get(t.slot))
.copied()
.flatten();
let mem = match (twin, at_bind) {
(Some((twin, twin_units)), Some(at_bind)) => Mem::Twin(TwinMem {
uniform: mem,
twin: ViewMem(twin, ops, twin_units),
at_bind,
}),
(Some(_), None) => return Err(cx.fail("a storage twin without its key")),
(None, _) => Mem::View(mem),
};
Ok(Prepared {
mem: Mem::View(ViewMem(view, ops, units)),
mem,
off,
inb,
guard_store,
+87 -3
View File
@@ -702,6 +702,10 @@ pub struct AccessPlan {
/// the slot at its bind offset alone, which reads no push word, is worth the key
/// ([`Declared::at_bind`]).
pub storage_at_bind: bool,
/// The memory-plan slots read through a uniform view and its storage twin
/// (`DescriptorView::UniformWithStorageTwin`, [`storage_twins`]): each read selects the twin's
/// load where the slot's `RangeAtBindOffset` holds ([`Declared::twins`]).
pub twins: BTreeSet<usize>,
/// The arenas the function uses.
pub local: local::LocalPlan,
/// The function's index extensions ([`index`]): planned before any instruction is selected
@@ -890,6 +894,9 @@ pub struct Declared {
/// by memory-plan slot index: where it holds, an access reads the view at the Metal offset
/// alone ([`range_at_bind_offset`]).
pub at_bind: Vec<Option<SValue>>,
/// The storage twin of each slot the plan gives one (`AccessPlan::twins`), its word view and
/// unit views (`views::declare_twin`), by memory-plan slot index.
pub twins: Vec<Option<(View, views::UnitViews)>>,
}
/// Slot `slot`'s `RangeAtBindOffset` specialization: a `bool`, false by default, fixed at pipeline
@@ -1149,6 +1156,8 @@ const SLOT_WORK_BYTES: usize = std::mem::size_of::<Option<SlotLowering>>()
struct Census {
storage: u32,
uniform: u32,
/// The uniform views' storage twins ([`storage_twins`]), storage buffers too.
twins: u32,
fields: BTreeSet<PushField>,
}
@@ -1164,6 +1173,7 @@ impl Census {
let mut c = Census {
storage: 0,
uniform: 0,
twins: 0,
fields: push.clone(),
};
let mut psb = dynamic;
@@ -1190,7 +1200,7 @@ impl Census {
DescriptorCounts {
uniform_buffers: u32::from(table::spills(stage, &self.fields))
.saturating_add(self.uniform),
storage_buffers: self.storage,
storage_buffers: self.storage.saturating_add(self.twins),
..DescriptorCounts::default()
}
}
@@ -1495,18 +1505,28 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
}
}
}
let twins = storage_twins(cx, (&lowering, &windows, &viewed), &census);
census.twins = u32::try_from(twins.len()).unwrap_or(u32::MAX);
let mut slots = Vec::with_capacity(memory.slots.len());
let addressed_slot = |cx: &mut SelectCx<'_>, slot: SlotRef| {
cx.facts.insert(RuntimeFact::DeviceAddresses { slot });
cx.push.remove(&PushField::SlotBindOffset(slot));
cx.push.insert(PushField::RootTableAddress);
};
for (plan, (l, w)) in memory.slots.iter().zip(lowering.iter().zip(&windows)) {
for (i, (plan, (l, w))) in memory
.slots
.iter()
.zip(lowering.iter().zip(&windows))
.enumerate()
{
let (Some(l), Some(window)) = (l, w) else {
slots.push(None);
continue;
};
let form = match l {
SlotLowering::View(_) if twins.contains(&i) => {
BufferForm::Descriptor(DescriptorView::UniformWithStorageTwin)
}
SlotLowering::View(kind) => BufferForm::Descriptor(descriptor_view(*kind)),
SlotLowering::Psb { .. } => {
addressed_slot(cx, plan.slot);
@@ -1563,9 +1583,66 @@ fn place_slots(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<Vec<Option<SlotCh
cx.families.access.storage_at_bind = p
.workarounds()
.contains(&DriverWorkaround::PushReadsLengthenThreadPayload);
cx.families.access.twins = twins;
Ok(slots)
}
/// The memory-plan slots of a kernel on a profile that takes
/// `DriverWorkaround::PushReadsLengthenThreadPayload` whose uniform view also binds its range as a
/// storage buffer, a storage twin (`DescriptorView::UniformWithStorageTwin`): every slot whose
/// form `lowering` makes a uniform view by its own window, not the per-stage storage-buffer
/// fallback (`viewed`), and whose uniform range (`windows`) fits `maxStorageBufferRange`; none
/// where their storage buffers, beside the slots' forms (`census`) and the stage's other
/// descriptors, would pass a per-stage descriptor limit or `maxDescriptorSetStorageBuffers`.
///
/// On that profile a light kernel that reads a pushed word was measured at about 2.2 times the
/// time of one that reads none, and one that reads a uniform view at its bind offset alone took
/// the constant cache's block read, slower than the uniform view at its residual: the twin, read
/// at its bind offset alone where the slot's `RangeAtBindOffset` holds, reads neither. Elsewhere
/// the slot reads its uniform view at its residual.
fn storage_twins(
cx: &SelectCx<'_>,
(lowering, windows, viewed): (&[Option<SlotLowering>], &[Option<Window>], &[bool]),
census: &Census,
) -> BTreeSet<usize> {
let p = cx.profile;
let limits = &p.fields().limits;
let takes = cx.stage == crate::pipeline::sym::Stage::Kernel
&& p.workarounds()
.contains(&DriverWorkaround::PushReadsLengthenThreadPayload);
if !takes {
return BTreeSet::new();
}
let twins: BTreeSet<usize> = lowering
.iter()
.zip(windows)
.enumerate()
.filter_map(|(i, (l, w))| {
let uniform = matches!(
l,
Some(SlotLowering::View(
ViewKind::UniformWords { .. } | ViewKind::UniformVec4 { .. }
))
);
let fits = w
.and_then(|w| uniform_bytes(w, limits))
.is_some_and(|r| r <= limits.max_storage_buffer_range);
let fallback = viewed.get(i).copied().unwrap_or(false);
(uniform && fits && !fallback).then_some(i)
})
.collect();
let mut counts = census.counts(cx.stage);
let n = u32::try_from(twins.len()).unwrap_or(u32::MAX);
counts.storage_buffers = counts.storage_buffers.saturating_add(n);
let total = cx.descriptors.plus(&counts);
match total.exceeded(limits).is_none()
&& total.storage_buffers <= limits.max_descriptor_set_storage_buffers
{
true => twins,
false => BTreeSet::new(),
}
}
/// The string attribute by which Metal's compiler declares that a buffer argument's memory is
/// reached through no other argument: every buffer argument of the AIR it emits carries it.
const BUFFER_NO_ALIAS: &[u8] = b"air-buffer-no-alias";
@@ -1873,9 +1950,16 @@ pub fn declare(
.get(&i)
.copied()
.unwrap_or(Units::NONE);
d.units.push(match (s, view) {
let unit_views = match (s, view) {
(Some(c), Some(view)) => views::UnitViews::declare(mb, c.slot, view, units)?,
_ => views::UnitViews::NONE,
};
d.units.push(unit_views);
d.twins.push(match s {
Some(c) if plan.families.access.twins.contains(&i) => {
Some(views::declare_twin(mb, c.slot, unit_views.units())?)
}
_ => None,
});
}
Ok(d)
+51 -1
View File
@@ -28,6 +28,14 @@
//! alignment of 1 or 2 to the unit index, and the word view's `OpArrayLength` still contains every
//! access.
//!
//! A uniform slot of a kernel on a profile that takes
//! `DriverWorkaround::PushReadsLengthenThreadPayload` may also have a **storage twin**
//! ([`declare_twin`]): a storage word view, and its `uvec4` view where the uniform view has one,
//! at a binding of its own (`ResourceKind::StorageTwin`) that the binder writes with the uniform
//! binding's buffer and range, so one offset reads the same byte through either. Each read loads
//! both and selects the twin's where the slot's `SpecKey::RangeAtBindOffset` holds
//! (`lower::access`): specialization fixes the constant, and the driver drops the other load.
//!
//! A storage or uniform slot may also have a **`uvec4` view** ([`VecView`]): `StorageBuffer {
//! uvec4[] }` or `Uniform { uvec4[N] }` at the slot's binding, declared where an access of the slot
//! moves a 16-byte leaf whose AIR alignment is at least 16 at an offset `residual + m` proven a
@@ -114,6 +122,39 @@ pub fn binding_symbol(slot: SlotRef) -> ResourceSlot {
}
}
/// The `StorageTwin` descriptor binding symbol of `slot`, which its storage twin is declared at
/// ([`declare_twin`]).
pub fn twin_symbol(slot: SlotRef) -> ResourceSlot {
ResourceSlot {
stage: slot.stage,
kind: ResourceKind::StorageTwin,
index: slot.index,
}
}
/// Declare the storage twin of `slot`, a slot read through a uniform view whose unit views are
/// `units` (`DescriptorView::UniformWithStorageTwin`): a storage word view at the slot's
/// `StorageTwin` binding ([`twin_symbol`]), and beside it a `StorageBuffer { uvec4[] }` view where
/// the uniform view has its `uvec4` view, so every read of the uniform view's has the twin's
/// counterpart of the same units. No store goes through the twin.
pub fn declare_twin(
mb: &mut ModuleBuilder,
slot: SlotRef,
units: crate::memory::leaf::Units,
) -> BResult<(View, UnitViews)> {
let sym = twin_symbol(slot);
let view = declare_at(mb, sym, ViewKind::Storage)?;
let vec4 = match units.vec4 {
true => Some(declare_vec_at(mb, sym, view, 4)?),
false => None,
};
let units = UnitViews {
vec4,
..UnitViews::NONE
};
Ok((view, units))
}
/// Declare the view of `slot` (its `Buffer` descriptor binding symbol).
pub fn declare(mb: &mut ModuleBuilder, slot: SlotRef, kind: ViewKind) -> BResult<View> {
declare_at(mb, binding_symbol(slot), kind)
@@ -339,7 +380,16 @@ pub fn declare_vec(
view: View,
lanes: u32,
) -> BResult<VecView> {
let sym = binding_symbol(slot);
declare_vec_at(mb, binding_symbol(slot), view, lanes)
}
/// [`declare_vec`] at binding symbol `sym`, whose word view is `view`.
fn declare_vec_at(
mb: &mut ModuleBuilder,
sym: ResourceSlot,
view: View,
lanes: u32,
) -> BResult<VecView> {
let u32_ty = u32_type(mb)?;
let len = u8::try_from(lanes)
.ok()
+21 -1
View File
@@ -243,9 +243,19 @@ impl BufferForm {
pub fn uniform_view(self) -> bool {
matches!(
self,
BufferForm::Descriptor(DescriptorView::UniformWords | DescriptorView::UniformVec4)
BufferForm::Descriptor(
DescriptorView::UniformWords
| DescriptorView::UniformVec4
| DescriptorView::UniformWithStorageTwin
)
)
}
/// Whether the form reads through a uniform view and its storage twin
/// ([`DescriptorView::UniformWithStorageTwin`]).
pub fn storage_twin(self) -> bool {
self == BufferForm::Descriptor(DescriptorView::UniformWithStorageTwin)
}
}
/// The descriptor view kind of a descriptor-form slot.
@@ -259,6 +269,16 @@ pub enum DescriptorView {
UniformWords,
/// A uniform buffer viewed as a `uvec4` array (std140-valid everywhere).
UniformVec4,
/// A uniform buffer (viewed as `UniformWords` or `UniformVec4` is) and its storage twin: a
/// second set-0 binding of the slot (`ResourceKind::StorageTwin`,
/// `BindingSource::StorageTwin`), a storage buffer written with the uniform binding's own
/// buffer and descriptor range, which the function reads instead where the slot's
/// `SpecKey::RangeAtBindOffset` holds. A uniform view as the other two are
/// ([`BufferForm::uniform_view`]): its descriptor base alignment, range limit and key are a
/// uniform view's, but for a slot bound to nothing, whose key is a bind at offset 0's. Only a
/// kernel on a profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload` reads a
/// slot so, and only where the twins fit the stage's descriptor limits.
UniformWithStorageTwin,
}
/// How a compiled function fetches one attribute it reads
@@ -152,6 +152,10 @@ pub enum BindingSource {
compare: bool,
integer: bool,
},
/// The storage twin of a Metal `[[buffer(n)]]` slot read through a uniform view
/// (`ResourceKind::StorageTwin`, `DescriptorView::UniformWithStorageTwin`): a storage buffer
/// written with the slot's own buffer and descriptor range, its uniform binding's.
StorageTwin(SlotRef),
}
/// One push-constant range of a [`PipelineLayout`]: a stage's fixed window (vertex `[0, 64)`,
+1
View File
@@ -836,6 +836,7 @@ fn binding_source(slot: ResourceSlot) -> BindingSource {
},
ResourceKind::TileAttachment(color) => BindingSource::TileAttachment(color),
ResourceKind::TileMap => BindingSource::TileMap(metal(SlotClass::Texture)),
ResourceKind::StorageTwin => BindingSource::StorageTwin(metal(SlotClass::Buffer)),
ResourceKind::SeparateTexture(sampler) => {
// The use is above the texture slot in the index (`ResourceSlot::separate_texture`).
let (texture, sampler) = ResourceSlot::separate_texture_parts(sampler, slot.index);
+5
View File
@@ -450,6 +450,11 @@ pub enum ResourceKind {
compare: bool,
integer: bool,
},
/// The storage twin of the stage's `[[buffer(n)]]` slot `ResourceSlot::index`, which the
/// function also reads through a uniform view (`DescriptorView::UniformWithStorageTwin`): a
/// read-only storage buffer of the same descriptor range, which the function reads instead
/// where the slot's `SpecKey::RangeAtBindOffset` holds.
StorageTwin,
}
/// What a bound acceleration structure holds: the binder binds a top-level structure, so a
+2 -1
View File
@@ -348,7 +348,8 @@ impl Default for Config {
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Buffer {
/// The `StorageBuffer`/`Uniform` binding this buffer backs. The elements of a descriptor
/// array of buffers are the slot's consecutive buffers, in element order.
/// array of buffers are the slot's consecutive buffers, in element order. A storage twin's
/// binding (`ResourceKind::StorageTwin`) with no buffer of its own reads its slot's.
pub slot: Option<ResourceSlot>,
/// The device address of byte 0, for `PhysicalStorageBuffer` accesses.
pub address: Option<u64>,
+16 -2
View File
@@ -20,7 +20,7 @@ use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::ops::Range;
use crate::pipeline::sym::{SpecKey, VaryingKey};
use crate::pipeline::sym::{ResourceKind, ResourceSlot, SpecKey, VaryingKey};
use crate::spirv::ids::{BlockId, ConstId, FuncId, GlobalId, TypeId, Value, VarId};
use crate::spirv::ir::{
ExecMode, ExecModel, GlobalKind, Inst, InstNode, Scope, StorageClass, Terminator, TypedModule,
@@ -143,7 +143,21 @@ impl<'m> Prog<'m> {
// buffers, element `e` the `e`th; `OpAccessChain` selects one and traps past
// them (and a sized array needs all of its elements bound).
GlobalKind::Resource(slot) => {
let first = res.buffers.iter().position(|b| b.slot == Some(*slot));
// A storage twin's binding holds the slot's own buffer, as the binder
// writes it (`DescriptorView::UniformWithStorageTwin`), unless a buffer
// of its own is bound there.
let own = |slot: ResourceSlot| {
res.buffers.iter().position(|b| b.slot == Some(slot))
};
let read = match (slot.kind, own(*slot)) {
(ResourceKind::StorageTwin, None) => ResourceSlot {
kind: ResourceKind::Buffer,
..*slot
},
_ => *slot,
};
let slot = &read;
let first = own(*slot);
let bound = |k: usize| {
res.buffers
.iter()
@@ -529,6 +529,167 @@ fn a_storage_view_reads_its_residual_without_the_row() {
}
}
/// The storage twin binding symbol of kernel buffer slot `index`.
fn twin_slot(index: u32) -> ResourceSlot {
ResourceSlot {
stage: Stage::Kernel,
kind: ResourceKind::StorageTwin,
index,
}
}
/// The form of buffer slot `index` of `a`.
fn form_of(a: &crate::library::FunctionArtifact, index: u32) -> BufferForm {
match a.interface.slots.get(&sref(index)) {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("slot {index}: {other:?}"),
}
}
/// On the profile that takes `DriverWorkaround::PushReadsLengthenThreadPayload`, a kernel's
/// uniform view has a storage twin (`DescriptorView::UniformWithStorageTwin`), with
/// `uniformBufferStandardLayout` (`u32[]`) and without (`uvec4[]`): a `StorageTwin` binding that
/// link numbers after every buffer binding of the stage, beside the slot's uniform one. At
/// `RangeAtBindOffset` 1 a load reads the twin at the Metal offset alone, and no value the slot's
/// `SlotBindOffset` word reaches is read once the key is folded ([`reads_push_word`]); at 0, the
/// negative control, it reads the uniform view at the residual plus the offset. The interpreter
/// binds the two to different bytes, so the value read names the view read.
#[test]
fn a_kernel_uniform_view_reads_its_storage_twin_at_its_bind_offset() {
let entry = "buffer_end_byte_load_constant";
let Some(bc) = assemble_file(entry) else {
return;
};
let key = SpecKey::RangeAtBindOffset(sref(0));
let field = PushField::SlotBindOffset(sref(0));
for standard in [true, false] {
let what = format!("standard={standard}");
let p = profile_with(AT_BIND_PROFILE, true, standard);
let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e}"));
assert_eq!(
form_of(&a, 0),
BufferForm::Descriptor(DescriptorView::UniformWithStorageTwin),
"{what}"
);
assert_eq!(
form_of(&a, 1),
BufferForm::Descriptor(DescriptorView::Storage),
"{what}"
);
assert!(a.interface.read_keys().contains(&key), "{what}");
let (table, _) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
let twin = table.bindings.get(&twin_slot(0)).copied();
let buffers = [kslot(0), kslot(1)].map(|s| table.bindings.get(&s).copied());
assert_eq!(
(buffers, twin),
([Some((0, 0)), Some((0, 1))], Some((0, 2))),
"{what}"
);
let (plan, m) = typed_module(&bc, entry, &p).expect("module");
assert!(!reads_push_word(&m, field, (key, true)), "{what} at 1");
assert!(reads_push_word(&m, field, (key, false)), "{what} at 0");
// A residual of 8 pushed: byte 5 of the twin when the key holds, byte 13 of the uniform
// view (its padding) when it does not.
let uniform_bytes = [9u8, 8, 7, 6, 5, 0xC3];
let twin_bytes = [1u8, 2, 3, 4, 5, 0x5A];
for (at_bind, want) in [(1u64, 0x5Au8), (0, 0x44)] {
let mut ubo = bound(0, 0, &uniform_bytes, 0x44);
ubo.bytes.resize(512, 0x44);
let mut ssbo = bound(0, 0, &twin_bytes, 0x77);
ssbo.slot = Some(twin_slot(0));
ssbo.bytes.resize(512, 0x77);
let res = Resources {
buffers: vec![ubo, ssbo, bound(1, 0, &[0; 4], 0)],
push: push_bytes(&plan, &[(0, 8)]),
spec: [(key, at_bind)].into(),
};
let out = run(&m, &Config::default(), res).expect("run");
assert_eq!(
out.buffers[2][..4],
[want, 0, 0, 0],
"{what} at_bind={at_bind}"
);
}
}
}
/// A storage twin is a kernel's alone, on the profile that takes
/// `DriverWorkaround::PushReadsLengthenThreadPayload` alone, and only where the twins fit the
/// stage's limits: a fragment function's uniform view on that profile, and a kernel's on every
/// other tested profile (the same driver's on another GPU among them, `intel-irisxe-anv`), keep
/// the plain uniform view and declare no `StorageTwin` binding; and on that profile with
/// `maxPerStageDescriptorStorageBuffers` lowered to the kernel's one storage view, the twin, a
/// storage buffer more, does not fit, so the plan declares none, where one more lets it.
#[test]
fn a_storage_twin_is_a_kernels_on_its_profile_within_the_limits() {
let entry = "buffer_end_byte_load_constant";
let Some(bc) = assemble_file(entry) else {
return;
};
let plain = |a: &crate::library::FunctionArtifact, p: &DeviceProfile, what: &str| {
let form = match a.interface.slots.values().next() {
Some(SlotInterface::Buffer(b)) => b.form,
other => panic!("{what}: {other:?}"),
};
assert!(
matches!(
form,
BufferForm::Descriptor(DescriptorView::UniformWords | DescriptorView::UniformVec4)
),
"{what}: {form:?}"
);
let (table, _) = link_and_validate(a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
assert!(
!table
.bindings
.keys()
.any(|s| s.kind == ResourceKind::StorageTwin),
"{what}"
);
};
for stem in PROFILES.into_iter().chain(["intel-irisxe-anv"]) {
let p = profile_with(stem, true, true);
let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{stem}: {e}"));
assert_ne!(
form_of(&a, 0),
BufferForm::Descriptor(DescriptorView::UniformWithStorageTwin)
);
plain(&a, &p, stem);
}
let fragment = assemble_file("a2c_coverage");
if let Some(fragment) = fragment {
let p = profile_with(AT_BIND_PROFILE, true, true);
let a = compile(&fragment, "a2c_color", &p).unwrap_or_else(|e| panic!("a2c_color: {e}"));
plain(&a, &p, "a2c_color");
}
let limited = |storage: u32| {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../metal2vulkan-validation/profiles")
.join(format!("{AT_BIND_PROFILE}.json"));
let text = std::fs::read_to_string(path).expect("profile");
let mut desc = DeviceDescription::from_khronos_json(&text, None).expect("description");
desc.limits.max_per_stage_descriptor_storage_buffers = storage;
Device::new(desc, policy())
.expect("device")
.profile()
.clone()
};
let p = limited(1);
let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("limited: {e}"));
assert_eq!(
form_of(&a, 0),
BufferForm::Descriptor(DescriptorView::UniformWords)
);
plain(&a, &p, "limited");
let p = limited(2);
let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("room: {e}"));
assert_eq!(
form_of(&a, 0),
BufferForm::Descriptor(DescriptorView::UniformWithStorageTwin)
);
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("room: L3: {e}"));
}
/// A `constant` struct of 6 bytes whose first and last bytes are read: its window starts at 0.
const CONSTANT_ENDS: &str = r#"define void @constant_ends(ptr addrspace(2) noundef "air-buffer-no-alias" %0, ptr addrspace(1) noundef "air-buffer-no-alias" %1) {
entry:
@@ -300,6 +300,11 @@ fn symbol(source: BindingSource) -> ResourceSlot {
kind: ResourceKind::Synthetic(binding),
index: 0,
},
BindingSource::StorageTwin(slot) => ResourceSlot {
stage: slot.stage,
kind: ResourceKind::StorageTwin,
index: slot.index,
},
other => panic!("a compute binding {other:?}"),
}
}
@@ -1122,7 +1127,12 @@ fn host_replay(
.range;
let guest = slots[&slot.index];
let (o, n) = (r.offset as usize, r.range as usize);
(memory[&guest][o..o + n].to_vec(), Some((guest, o)))
// A storage twin is only read: nothing of it returns.
let returns = sym.kind != ResourceKind::StorageTwin;
(
memory[&guest][o..o + n].to_vec(),
returns.then_some((guest, o)),
)
}
WriteSource::Neutral(_) => (vec![0; 4096], None),
WriteSource::ArgumentTable { .. } => (
@@ -10123,6 +10123,7 @@ method metal2vulkan::pipeline::AmplificationDraws::new pub fn new(layered: bool,
method metal2vulkan::pipeline::BandPrimitive::patch_control_points pub fn patch_control_points(self) -> u32
method metal2vulkan::pipeline::BlendEquation::of pub fn of(c: &crate::pipeline::descriptor::ColorAttachmentDescriptor) -> Option<BlendEquation>
method metal2vulkan::pipeline::BlendState::reads_second_output pub fn reads_second_output(&self) -> bool
method metal2vulkan::pipeline::BufferForm::storage_twin pub fn storage_twin(self) -> bool
method metal2vulkan::pipeline::BufferForm::uniform_view pub fn uniform_view(self) -> bool
method metal2vulkan::pipeline::ColorAttachmentDescriptor::new pub fn new(pixel_format: metal::PixelFormat) -> ColorAttachmentDescriptor
method metal2vulkan::pipeline::ColorAttachmentDescriptor::specialized #[must_use] pub fn specialized(&self) -> ColorAttachmentDescriptor
@@ -14988,6 +14989,7 @@ variant metal2vulkan::pipeline::BindingSource::SamplerArray SamplerArray { stage
variant metal2vulkan::pipeline::BindingSource::SeparateSampler SeparateSampler { stage: Stage, sampler: CombinedSampler }
variant metal2vulkan::pipeline::BindingSource::SeparateTexture SeparateTexture { texture: SlotRef, sampler: CombinedSampler }
variant metal2vulkan::pipeline::BindingSource::SnapshotTexels SnapshotTexels(u32)
variant metal2vulkan::pipeline::BindingSource::StorageTwin StorageTwin(SlotRef)
variant metal2vulkan::pipeline::BindingSource::Synthetic Synthetic { stage: Stage, binding: SyntheticBinding }
variant metal2vulkan::pipeline::BindingSource::Texture Texture(SlotRef)
variant metal2vulkan::pipeline::BindingSource::TileAttachment TileAttachment(u32)
@@ -15008,6 +15010,7 @@ variant metal2vulkan::pipeline::ChannelWrite::Srgb Srgb
variant metal2vulkan::pipeline::ChannelWrite::Unorm Unorm { bits: u8 }
variant metal2vulkan::pipeline::DescriptorView::Storage Storage
variant metal2vulkan::pipeline::DescriptorView::UniformVec4 UniformVec4
variant metal2vulkan::pipeline::DescriptorView::UniformWithStorageTwin UniformWithStorageTwin
variant metal2vulkan::pipeline::DescriptorView::UniformWords UniformWords
variant metal2vulkan::pipeline::EntryMath::Fast Fast
variant metal2vulkan::pipeline::EntryMath::Precise Precise
@@ -15204,6 +15207,7 @@ variant metal2vulkan::pipeline::ResourceKind::SamplerArray SamplerArray { compar
variant metal2vulkan::pipeline::ResourceKind::SeparateSampler SeparateSampler(SamplerRef)
variant metal2vulkan::pipeline::ResourceKind::SeparateTexture SeparateTexture(SamplerRef)
variant metal2vulkan::pipeline::ResourceKind::SnapshotTexels SnapshotTexels(u32)
variant metal2vulkan::pipeline::ResourceKind::StorageTwin StorageTwin
variant metal2vulkan::pipeline::ResourceKind::Synthetic Synthetic(SyntheticBinding)
variant metal2vulkan::pipeline::ResourceKind::Texture Texture
variant metal2vulkan::pipeline::ResourceKind::TileAttachment TileAttachment(u32)
Can't render this file because it is too large.
+21
View File
@@ -1495,6 +1495,27 @@ for dependency in &pipeline.dependencies {
the same limits), so commands over buffers of many sizes keep one shape and one plan: on a device
whose two limits are both 4 GiB, every buffer below 4 GiB. The default tells every class apart.
The runtime sets them on every table it reads.
- On that profile a kernel's uniform view also has a **storage twin**, where the twins fit the
stage's descriptor limits (`maxPerStageDescriptorStorageBuffers`, `maxPerStageResources` and
`maxDescriptorSetStorageBuffers`; past one, no slot of the stage has one). Its slot's form is
`DescriptorView::UniformWithStorageTwin`, a uniform view (`BufferForm::uniform_view`) whose
`BufferForm::storage_twin` holds, and its layout has a second set-0 binding for it
(`ResourceKind::StorageTwin`, `BindingSource::StorageTwin`): a storage buffer. Link numbers set 0
in `ResourceSlot` order, whose kind comes before its index, so a stage's twins follow every
other binding of the stage, in buffer index order. Write the twin with the uniform binding's own
buffer, offset and range, from the same bind offset: a plan writes both from the slot's own
source (`WriteSource::Buffer`, `InlineBytes` or `Neutral`), an instance's `DescriptorRange`s
give both bindings one range, and the plan's `uses` hold a `Storage` read of the slot beside the
`Uniform` one. Where the
slot's `RangeAtBindOffset` holds, the kernel reads the twin at its bind offset alone; elsewhere
the uniform view at its residual, so the same specialization and range serve either. The key is
a uniform view's (a bind offset the view base alignment divides, at a slot whose table tells it
apart; inline bytes) but for a slot bound to nothing, which takes a bind at offset 0's value as a
storage view does, and the runtime keeps it where it takes the uniform views' residual form.
`state.uniform_views_at_residual` shares no twin's range: it starts at its bind offset. There
a kernel of three storage views at offset 0 and inline bytes ran in 102.1 us a dispatch with the
bytes read through a storage view at their bind offset (job m3-max-34275), against the 142.8 us
above.
- A two-plane YCbCr texture whose planes a function may read in place states them in its facts
(`TextureFacts::ycbcr_in_place`, a `YCbCrInPlace` of its planes; the runtime states one on a
device whose memory is the host's, `DeviceProfile::reads_ycbcr_planes_in_place`: an integrated