Fragment, mesh, memory: the dead driver variants' readers go

Since the fact tables went, Device::from_queries gives every device the same two workarounds
(ClippedCoverageNotMetals, TessellatorNotMetals), so every reader of another variant tested a
fact no profile carries. Deleted with their now unreachable forms, each changing what no device
emits:

- EarlyTestsDropMultisampledImageWrites (MoltenVK on Apple's GPU): the framebuffer fetch's
  per-sample refusal and its 'dropped' arm (fetch.rs), the imageblock's late-tests form and its
  two refusals (imageblock.rs, ImageblockPlan::late_tests), the input shadow's arm. The device
  test every_device_keeps_an_early_tests_fragments_texture_writes_at_four_samples (runtime,
  lost_writes) holds the defect's shape on every device.
- MemoryWritingFragmentsRunPerSample (MoltenVK): CoverageLoop::DriverRunsPerSample, the coverage
  plan's driver_runs and writes, its refusal, link's sample-shading exception, the codec tag and
  engine_coverage_loop's per_sample_defect. Held by
  every_device_runs_a_memory_writing_fragment_once_per_covered_sample.
- BothBarycentricFormsRejected: the stage interface's refusal of a second barycentric form.
- MeshIndexComponentStoresMisplaced (lavapipe before Mesa 26.2, below the floor): the staged
  index words, their declaration, stores, write-back and workgroup bytes
  (stage_workgroup_limit's staged argument).
- BufferAtomicsUncontained (SwiftShader, below the floor): contain::atomic_encoding and
  DeviceProfile::checks_atomics_in_shader, which validation's out-of-bounds contract read; an
  atomic is contained as every other access is.
- DiscardDropsSimdgroupStores (MoltenVK on Apple's GPU, SPIRV-Cross's optnone helpers): the
  deferred discards (discard.rs late_discards, Reach::FLOAT, the census name
  fragment.discard.deferred), spirv::helper_branches whole (its guard, fences and census
  entries), and the notes DiscardDropsSimdgroupStores and HelperBranchDropsSimdgroupStores with
  their codec tags, conformance degradations, validation allowances, API.md entries and the
  engine_fragment test of the uniform branch. The rch_helper_* fixtures stay, compiled as written
  everywhere, their README rows saying so. Held by
  every_device_keeps_the_texture_writes_beside_a_discard_after_a_texture_sample.

The three runtime device tests are in tests::lost_writes, passing on lavapipe (m3-max-59701).
This commit is contained in:
Anees Iqbal committed 2026-11-20 11:57:12 -08:00
1 parent 912bf785ce
commit fda94462c8
28 files changed
+66 -2594

No files matched your search

@@ -115,10 +115,6 @@ pub enum Degradation {
HalfOutputPrecision,
/// `metal2vulkan-degrade-extended-range-blend-source`.
ExtendedRangeBlendSource,
/// `metal2vulkan-degrade-discard-drops-simdgroup-stores`.
DiscardDropsSimdgroupStores,
/// `metal2vulkan-degrade-helper-branch-drops-simdgroup-stores`.
HelperBranchDropsSimdgroupStores,
/// `metal2vulkan-degrade-extended-range-float-blend-source`.
ExtendedRangeFloatBlendSource,
/// `metal2vulkan-degrade-anisotropic-filter`.
@@ -242,8 +238,6 @@ impl Degradation {
Degradation::ArgumentPixelSamplerScaling,
Degradation::HalfOutputPrecision,
Degradation::ExtendedRangeBlendSource,
Degradation::DiscardDropsSimdgroupStores,
Degradation::HelperBranchDropsSimdgroupStores,
Degradation::ExtendedRangeFloatBlendSource,
Degradation::AnisotropicFilter,
Degradation::DeviceAnisotropicFilter,
@@ -360,12 +354,6 @@ impl Degradation {
Degradation::ExtendedRangeBlendSource => {
"metal2vulkan-degrade-extended-range-blend-source"
}
Degradation::DiscardDropsSimdgroupStores => {
"metal2vulkan-degrade-discard-drops-simdgroup-stores"
}
Degradation::HelperBranchDropsSimdgroupStores => {
"metal2vulkan-degrade-helper-branch-drops-simdgroup-stores"
}
Degradation::ExtendedRangeFloatBlendSource => {
"metal2vulkan-degrade-extended-range-float-blend-source"
}
@@ -469,10 +457,6 @@ impl Degradation {
PrecisionNote::ArgumentPixelSamplerScaling => Degradation::ArgumentPixelSamplerScaling,
PrecisionNote::HalfOutputPrecision => Degradation::HalfOutputPrecision,
PrecisionNote::ExtendedRangeBlendSource => Degradation::ExtendedRangeBlendSource,
PrecisionNote::DiscardDropsSimdgroupStores => Degradation::DiscardDropsSimdgroupStores,
PrecisionNote::HelperBranchDropsSimdgroupStores => {
Degradation::HelperBranchDropsSimdgroupStores
}
PrecisionNote::ExtendedRangeFloatBlendSource => {
Degradation::ExtendedRangeFloatBlendSource
}
@@ -211,11 +211,11 @@ threadgroup's threads); an authored case that executes a loop declares it
| `rt6_render_state` | `rt6_full`, `rt6_flip`, `rt6_small`, `rt6_point`, `rt6_white`, `rt6_half` | the functions of a Metal probe on an M4 (macOS 27.0.1): Metal's fullscreen triangle at a depth `z + slope * x` from a buffer, the same triangle in the other winding, a small triangle (with a fourth vertex, a strip over a quad), one point of 4 pixels, and a white and a half-gray fragment | the texels Metal stored in that probe (no authored case) |
| `rt6_resolves` | `rt6_resolve_full`, `rt6_resolve_half`, `rt6_resolve_white`, `rt6_resolve_samples`, `rt6_resolve_sample_values`, `rt6_resolve_masked` | the functions of a Metal probe on an M4 (macOS 27.0.1): Metal's fullscreen triangle at a depth `z` from a buffer, half the target (its diagonal pixels half covered), white, two fragments whose values follow `[[sample_id]]`, and white on the samples of a mask from a buffer | the texels Metal resolved in that probe (no authored case) |
| `rdw_tile_kept` | `rdw_tile_kept_fill`, `rdw_tile_kept_dump`, `rdw_tile_kept_fill_dump` | tile functions over an explicit imageblock of one `uint4` a cell standing alone (after an `R32Uint` attachment, at byte 16): a fill of word `k` as `seed + k`, a dump of every word, and a fill a word at a dynamic index read back at once, run in passes of fewer imageblock bytes than the state's 32 | the words Metal's probes kept (below the pass's bytes rounded up to 8) and read as zero (no authored case) |
| `rch_guarded_effects` | `rch_guarded_vertex`, `rch_guarded_store`, `rch_guarded_atomic`, `rch_guarded_loop`, `rch_guarded_write`, `rch_guarded_copy`, `rch_guarded_simd` | fragment functions that sample an 8x8 texture repeated over the target, discard where the sampled alpha is below 0.5, and then make side effects: a store, an atomic whose old value picks the slot of a later store, a store in a loop, a texture write, a copy of a pair of vectors, and a store of a simdgroup sum; a vertex function drawing a triangle from three corners | where the discard is predicated (a device without demote; MoltenVK on an Apple GPU, whose store-dropping defect defers it), each side effect runs under `if !discarded` and the atomic's result is zero for a discarded invocation; the simdgroup sum keeps the demote on MoltenVK (`PrecisionNote::DiscardDropsSimdgroupStores`) and is refused needing demote where no whole-quad exit can be placed (`tests::engine_fragment`); every side effect lands at the kept pixels alone |
| `rch_helper_branch` | `rch_helper_branch`, `rch_helper_branch_late`, `rch_helper_branch_gradient`, `rch_helper_branch_unsampled`, `rch_helper_branch_loop` | fragment functions that read a coverage texture, round `half` values in a branch where the coverage is not 1 (where every covered pixel's coverage is 1, only the quad helpers past a primitive's edges take it) and write a buffer after it; they sample at LOD 0 before the branch, also at an implicit LOD after it at the pixel, at a coordinate the branch computes, not at all, or round in a loop as long as the coverage | on MoltenVK on an Apple GPU (`DriverWorkaround::DiscardDropsSimdgroupStores`) the branch's helper invocations take its empty arm where nothing they compute differently reaches a derivative (census `fragment.helper-guard`), and the gradient and loop functions record `PrecisionNote::HelperBranchDropsSimdgroupStores` (`tests::engine_fragment`); no other device changes them. Apple's compiler loses the live threads' texture writes of a simdgroup whose helpers alone call an `optnone` function there (measured on an M4) |
| `rch_helper_tangle` | `rch_tangle_vertex`, `rch_tangle_sample_after`, `rch_tangle_dfdx_after`, `rch_tangle_quad_after`, `rch_tangle_lod_after`, `rch_tangle_quad_before`, `rch_tangle_sample_before`, `rch_tangle_unread`, `rch_tangle_merge_after`, `rch_tangle_loop_after` | fragment functions that read a coverage texture, sample at LOD 0, round to `half` where only the quad helpers past a primitive's edges run (a branch where the coverage is not 1, or a loop only they repeat) beside a tangled instruction, and write a texture after it: the tangled instruction reads the rounded value after the rounding (in the arm an implicit-LOD sample at it, `dfdx`, `quad_sum`, the LOD query; a sample after the branch's merge; a sample after the loop), comes first reading none of it (`quad_sum`, an implicit-LOD sample), or comes after reading none of it; a vertex function drawing a triangle from three corners | On MoltenVK on an Apple GPU (`DriverWorkaround::DiscardDropsSimdgroupStores`) nothing is guarded; the `after` functions record no `PrecisionNote::HelperBranchDropsSimdgroupStores` and the others record it (`tests::engine_fragment`); no covered pixel's write is lost where no note is recorded |
| `rch_helper_select` | `rch_select_vertex`, `rch_select_arm`, `rch_select_and`, `rch_select_sampled`, `rch_select_uniform` | fragment functions without fast math (every float operation `NoContraction`, which SPIRV-Cross writes through its `optnone` `spvFAdd`) that read a coverage texture, sample at LOD 0 and pick a sum where the coverage is not 1 (only the quad helpers past a primitive's edges do), with no branch: the compiler writes a select, which SPIRV-Cross writes as a `?:` whose arm holds the call; the sum as a component, its comparison on the right of a `&&`, a coordinate an implicit-LOD sample reads after it, or on a constant block's flag; each writes a texture after it; a vertex function drawing a triangle from three corners | On MoltenVK on an Apple GPU (`DriverWorkaround::DiscardDropsSimdgroupStores`) nothing is guarded; `rch_select_arm` and `rch_select_and` are fenced (census `fragment.helper-fence`), or record `PrecisionNote::HelperBranchDropsSimdgroupStores` without a fragment shuffle, and the others are left as they are (`tests::engine_fragment`); no covered pixel's write is lost where no note is recorded |
| `rch_uniform_branch` | `rch_uniform_branch` | a fragment function that, where a constant block's flag says (a branch every invocation of a draw takes alike), divides a coordinate by a texture's size and takes the high word of a product (`mulhi`, an `OpUMulExtended`, which SPIRV-Cross writes through its `optnone` `spvMulExtended`), then samples the `half` texture through a runtime sampler at the coordinate and writes the sample and the product's lowest bit to a buffer. | On MoltenVK on an Apple GPU (`DriverWorkaround::DiscardDropsSimdgroupStores`): the module holds the product, and no `fragment.helper-guard` census and no `PrecisionNote::HelperBranchDropsSimdgroupStores`; L3 |
| `rch_guarded_effects` | `rch_guarded_vertex`, `rch_guarded_store`, `rch_guarded_atomic`, `rch_guarded_loop`, `rch_guarded_write`, `rch_guarded_copy`, `rch_guarded_simd` | fragment functions that sample an 8x8 texture repeated over the target, discard where the sampled alpha is below 0.5, and then make side effects: a store, an atomic whose old value picks the slot of a later store, a store in a loop, a texture write, a copy of a pair of vectors, and a store of a simdgroup sum; a vertex function drawing a triangle from three corners | where the discard is predicated (a device without demote), each side effect runs under `if !discarded` and the atomic's result is zero for a discarded invocation; the simdgroup sum is refused needing demote where no whole-quad exit can be placed (`tests::engine_fragment`); every side effect lands at the kept pixels alone |
| `rch_helper_branch` | `rch_helper_branch`, `rch_helper_branch_late`, `rch_helper_branch_gradient`, `rch_helper_branch_unsampled`, `rch_helper_branch_loop` | fragment functions that read a coverage texture, round `half` values in a branch where the coverage is not 1 (where every covered pixel's coverage is 1, only the quad helpers past a primitive's edges take it) and write a buffer after it; they sample at LOD 0 before the branch, also at an implicit LOD after it at the pixel, at a coordinate the branch computes, not at all, or round in a loop as long as the coverage | compiled as written on every device. Apple's compiler loses the live threads' texture writes of a simdgroup whose helpers alone call an `optnone` function there (measured on an M4, through SPIRV-Cross's MSL) |
| `rch_helper_tangle` | `rch_tangle_vertex`, `rch_tangle_sample_after`, `rch_tangle_dfdx_after`, `rch_tangle_quad_after`, `rch_tangle_lod_after`, `rch_tangle_quad_before`, `rch_tangle_sample_before`, `rch_tangle_unread`, `rch_tangle_merge_after`, `rch_tangle_loop_after` | fragment functions that read a coverage texture, sample at LOD 0, round to `half` where only the quad helpers past a primitive's edges run (a branch where the coverage is not 1, or a loop only they repeat) beside a tangled instruction, and write a texture after it: the tangled instruction reads the rounded value after the rounding (in the arm an implicit-LOD sample at it, `dfdx`, `quad_sum`, the LOD query; a sample after the branch's merge; a sample after the loop), comes first reading none of it (`quad_sum`, an implicit-LOD sample), or comes after reading none of it; a vertex function drawing a triangle from three corners | compiled as written on every device |
| `rch_helper_select` | `rch_select_vertex`, `rch_select_arm`, `rch_select_and`, `rch_select_sampled`, `rch_select_uniform` | fragment functions without fast math (every float operation `NoContraction`, which SPIRV-Cross writes through its `optnone` `spvFAdd`) that read a coverage texture, sample at LOD 0 and pick a sum where the coverage is not 1 (only the quad helpers past a primitive's edges do), with no branch: the compiler writes a select, which SPIRV-Cross writes as a `?:` whose arm holds the call; the sum as a component, its comparison on the right of a `&&`, a coordinate an implicit-LOD sample reads after it, or on a constant block's flag; each writes a texture after it; a vertex function drawing a triangle from three corners | compiled as written on every device |
| `rch_uniform_branch` | `rch_uniform_branch` | a fragment function that, where a constant block's flag says (a branch every invocation of a draw takes alike), divides a coordinate by a texture's size and takes the high word of a product (`mulhi`, an `OpUMulExtended`, which SPIRV-Cross writes through its `optnone` `spvMulExtended`), then samples the `half` texture through a runtime sampler at the coordinate and writes the sample and the product's lowest bit to a buffer. | the module holds the product; L3 |
| `sps2_residency_probes` | `sps2_residency_probes` | the residency word (`sparse_color::resident()`) and value of a texture's fetch, storage read, nearest and linear sample, and gather at authored coordinates (a probe buffer), on ordinary or sparse textures | `out[2i]` = probe `i`'s value bits, `out[2i + 1]` = `(resident, kind, i, 0x5A5)` |
| `spse_level_probes` | `spse_level_probes` | the residency word and value of a 2D texture's fetch at a level, nearest and linear sample at a level, and gather, at authored coordinates (a probe buffer) | `out[2i]` = probe `i`'s value bits, `out[2i + 1]` = `(resident, kind, i, 0x5A5)` |
| `spse_array_probes` | `spse_array_probes` | the same of a 2D array texture at a layer and level | `out[2i]` = probe `i`'s value bits, `out[2i + 1]` = `(resident, kind, i, 0x5A5)` |
@@ -443,8 +443,7 @@ impl HostClass {
/// fetches, past their buffer read or wrote the next buffer's bytes; texel buffer accesses
/// were contained. By user decision the product keeps the robust encoding there (no in-shader
/// check), as native Metal bounds none of these either. SwiftShader's robustness leaves a
/// storage buffer's atomics uncontained too, but the product checks them in the shader there
/// (`DriverWorkaround::BufferAtomicsUncontained`). Under `robustBufferAccess` its storage
/// storage buffer's atomics uncontained too, below the floor. Under `robustBufferAccess` its storage
/// buffer loads and stores and its storage texel buffer atomic add and store were measured
/// contained, and OB1's cases (storage, uniform, and texel buffers, and buffer atomics with the
/// check) matched. Its vertex-input fetches and index-buffer reads were not measured; like
@@ -447,13 +447,6 @@ pub fn containment(
) -> Result<Contained, String> {
let ModuleFacts { stage, slots, .. } = *module;
let robust = robust_check(profile)?;
// A descriptor view's atomic is checked in the shader where the driver's robustness leaves
// buffer atomics uncontained (`DeviceProfile::checks_atomics_in_shader`).
let atomic_check = if profile.checks_atomics_in_shader() {
Check::Shader
} else {
robust
};
let slot = |class, index| {
slots
.get(&SlotRef {
@@ -502,7 +495,7 @@ pub fn containment(
BufferForm::Descriptor(view) => {
let (form, check) = match view {
DescriptorView::Storage if atomic => {
(ContainmentForm::BufferAtomic, atomic_check)
(ContainmentForm::BufferAtomic, robust)
}
DescriptorView::Storage => (ContainmentForm::StorageBuffer, robust),
DescriptorView::UniformWords | DescriptorView::UniformVec4 => {
@@ -678,8 +671,8 @@ pub fn containment(
}
/// The check `profile`'s leg gives every access its compiled modules leave to the device's buffer
/// robustness (the two encodings): a descriptor view's loads and stores (and atomics, unless
/// `DeviceProfile::checks_atomics_in_shader`) and fixed-function vertex input.
/// robustness (the two encodings): a descriptor view's loads, stores and atomics and
/// fixed-function vertex input.
/// [`Check::Robust2`] under `robustBufferAccess2`, [`Check::Robust`] under `robustBufferAccess`
/// alone, and [`Check::Shader`] without buffer robustness; `Err` for a containment validation
/// never compiles (`Containment::UnsafeOff`) or does not know. The only source of
@@ -333,8 +333,6 @@ pub fn allowance(note: PrecisionNote) -> Allowance {
| N::NativeDot
| N::NativeMix
| N::DevicePackConversion
| N::DiscardDropsSimdgroupStores
| N::HelperBranchDropsSimdgroupStores
| N::UnorderedFetchWithinDraw
| N::NativeLogicOperation
| N::NativeFloat8
+6 -11
View File
@@ -2384,17 +2384,12 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
}
// The object function's arena with those lengths, within its stage's workgroup memory limit.
if let (Some((static_bytes, payload)), Some(regions)) = (object_arena, object_regions) {
crate::lower::mesh::stage_workgroup_limit(
Stage::Object,
profile,
payload.map(u64::from),
0,
)
.check(u64::from(static_bytes).saturating_add(regions))
.map_err(|e| match e {
crate::error::Error::Unsupported(u) => BindError::Unsupported(u),
other => internal(format!("an object function's threadgroup memory: {other}")),
})?;
crate::lower::mesh::stage_workgroup_limit(Stage::Object, profile, payload.map(u64::from))
.check(u64::from(static_bytes).saturating_add(regions))
.map_err(|e| match e {
crate::error::Error::Unsupported(u) => BindError::Unsupported(u),
other => internal(format!("an object function's threadgroup memory: {other}")),
})?;
}
record_specialized(&push, shape, &mut resources)?;
record_noted(&p.stages, shape, &mut resources, &heap_reach)?;
+1 -3
View File
@@ -1216,7 +1216,7 @@ codec_enum! {
}
IoInterpolation { Flat, Smooth { sampling, perspective } }
IoSampling { Center, Centroid, Sample, Interpolant { center, centroid, sample } }
CoverageLoop { NotNeeded, Looped, Unlooped, Refused(f0), DriverRunsPerSample }
CoverageLoop { NotNeeded, Looped, Unlooped, Refused(f0) }
ChannelWrite {
Unorm { bits }, Snorm { bits, blended }, Srgb, FloatTowardZero { mantissa, signed }, Device,
FloatNearestEven { mantissa, signed }, BlendedNearestEven { mantissa, signed },
@@ -1497,8 +1497,6 @@ codec_enum! {
ArgumentPixelSamplerScaling,
HalfOutputPrecision,
ExtendedRangeBlendSource,
DiscardDropsSimdgroupStores,
HelperBranchDropsSimdgroupStores,
ExtendedRangeFloatBlendSource,
AnisotropicFilter,
DeviceAnisotropicFilter,
@@ -194,13 +194,6 @@ impl DeviceProfile {
crate::memory::contain::encoding(self) == Check::InShader
}
/// Whether a module compiled for this profile checks a buffer atomic in the shader: as
/// [`DeviceProfile::checks_buffers_in_shader`], and also where the driver's robustness leaves a
/// storage buffer's atomics uncontained ([`DriverWorkaround::BufferAtomicsUncontained`]).
pub fn checks_atomics_in_shader(&self) -> bool {
crate::memory::contain::atomic_encoding(self) == Check::InShader
}
/// Whether this profile leaves an out-of-bounds read of an image (`texel_buffer`: of a texel
/// buffer) to the device, whose robustness answers Metal's out-of-bounds texel; elsewhere the
/// shader checks the read.
@@ -74,8 +74,8 @@
//! access, Mesa's RADV and ANV never showed a relaxed one a store that arrived after its first
//! read.
//!
//! **Containment** is the plain access's (`contain::atomic_encoding`): robust descriptors emit no
//! check, except on a driver whose robustness leaves buffer atomics uncontained; an in-shader check
//! **Containment** is the plain access's (`contain::encoding`): robust descriptors emit no
//! check; an in-shader check
//! guards a view's atomic with `if_(inb)` (its result is 0 out of bounds, where Metal's is
//! unmeasured); a device-address atomic out of bounds (a static slot's or a wide pointer's, checked
//! against the root entry's size) operates on the write-only sink and yields 0; an arena atomic
@@ -697,7 +697,7 @@ pub fn select(
}
} else {
let (mut targets, null) = static_roots(cx, r.ptr, m)?;
let check = contain::atomic_encoding(cx.profile);
let check = contain::encoding(cx.profile);
let fixed = super::fixed_offset(cx, r.ptr);
for t in &mut targets {
t.check = check;
@@ -57,15 +57,6 @@
//! pipeline that reads `[[sample_mask]]`, looped or not, or that reads a centroid varying and runs
//! once per pixel, records `PrecisionNote::ClippedCoverageSplit` on a device whose rasterizer is
//! not Apple's (`DriverWorkaround::ClippedCoverageNotMetals`).
//!
//! MoltenVK on Apple's GPU runs a shader that writes memory once per covered sample, as Metal
//! does, sample shading or not (`DriverWorkaround::MemoryWritingFragmentsRunPerSample`), so the
//! loop of a function that writes memory would repeat each pass there. Such a function is compiled
//! as written there instead (`CoverageLoop::DriverRunsPerSample`), each of the driver's runs
//! reading the pixel's coverage, its sample index and its sample-qualified varyings, with the
//! pipeline's sample shading off; except where MoltenVK's SPIRV-Cross masks the coverage with the
//! run's sample bit (a module with `SampleRateShading` that reads `FragCoord`), where it is refused
//! as the driver's defect.
use crate::air::abi::{
Builtin, Interpolation as AirInterp, ParamRole, Sampling as AirSampling, Stage as AirStage,
@@ -73,7 +64,7 @@ use crate::air::abi::{
use crate::air::ir::{ArgIdx, Body, Value};
use crate::device::requirements::VkFeature;
use crate::device::DriverWorkaround;
use crate::error::{Error, Feature, InternalError, InternalKind, Unsupported};
use crate::error::{Error, InternalError, InternalKind};
use crate::lower::arith::legal::form_on;
use crate::lower::emit::FamilyDecls;
use crate::lower::select::{Plan, SelectCx};
@@ -97,13 +88,6 @@ pub struct CoveragePlan {
/// Why the function cannot loop, as far as its interface shows before its body is selected:
/// its early tests, its attachments, or the device's interpolation functions.
pub refusal: Option<CoverageLoopRefusal>,
/// The function writes memory, which a driver with
/// `DriverWorkaround::MemoryWritingFragmentsRunPerSample` repeats per covered sample.
pub writes: bool,
/// Such a driver runs the function once per covered sample itself, each run reading the
/// pixel's coverage, so it is compiled as written, without the loop
/// (`CoverageLoop::DriverRunsPerSample`).
pub driver_runs: bool,
/// Where the looping function reads a sample-qualified varying: the most samples a pipeline of
/// the device may have, at each of which the entry reads every such varying before the loop.
pub samples_before_loop: Option<u32>,
@@ -213,15 +197,6 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> {
&& !p
.enabled
.portability_withholds(VkFeature::ShaderSampleRateInterpolationFunctions);
// A driver that runs a memory writer once per covered sample hands each run the pixel's
// coverage, unless its shader compiler masks the coverage with the run's sample bit: MoltenVK
// 1.4.1's SPIRV-Cross (`adec7acb`) does where the module declares `SampleRateShading` (it
// reads the sample index or a sample-qualified varying) and reads `FragCoord`.
let position = used(&|r| matches!(r, ParamRole::Builtin(Builtin::Position(_))));
let driver_runs = writes
&& p.workarounds
.contains(&DriverWorkaround::MemoryWritingFragmentsRunPerSample)
&& !((sample_id || sample_varying) && position);
let attachments = super::rog::declared(cx)
|| used(&|r| matches!(r, ParamRole::ColorInput { .. } | ParamRole::Imageblock(_)));
let refusal = if matches!(
@@ -233,12 +208,12 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> {
Some(CoverageLoopRefusal::EarlyFragmentTests)
} else if attachments {
Some(CoverageLoopRefusal::Attachments)
} else if sample_varying && !interpolation && !driver_runs {
} else if sample_varying && !interpolation {
Some(CoverageLoopRefusal::InterpolationFunctions)
} else {
None
};
let looped = cx.inputs.multisampled && refusal.is_none() && !driver_runs;
let looped = cx.inputs.multisampled && refusal.is_none();
// Each pass's outputs land on every sample the passes keep, the last pass's (the module docs).
if looped && !e.ep.outputs.is_empty() {
cx.precision.insert(PrecisionNote::LoopedSampleOutputs);
@@ -251,8 +226,6 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> {
cx.families.fragment.coverage = Some(CoveragePlan {
looped,
refusal,
writes,
driver_runs,
samples_before_loop,
});
Ok(())
@@ -279,10 +252,7 @@ fn most_samples(limits: &crate::device::Limits) -> u32 {
/// Complete the plan once every instruction is selected (`fragment::finish`): a discard, or a
/// derivative, implicit-LOD sample, quad or simdgroup operation, or barrier, refuses the loop. A
/// looping function is refused here; any other records in its interface how link treats it
/// (`StageIo::coverage_loop`). On a driver that runs such a shader once per covered sample
/// (`MemoryWritingFragmentsRunPerSample`) a function that writes memory runs as written, or, where
/// that driver would mask its coverage, is refused as its defect: the loop would repeat each pass
/// per covered sample there.
/// (`StageIo::coverage_loop`).
pub(super) fn finish(cx: &mut SelectCx<'_>) -> Result<bool, Error> {
let Some(plan) = cx.families.fragment.coverage else {
return Ok(false);
@@ -299,20 +269,11 @@ pub(super) fn finish(cx: &mut SelectCx<'_>) -> Result<bool, Error> {
} else {
None
};
if plan.looped {
if let Some(r) = late {
return Err(r.error());
}
let per_sample = DriverWorkaround::MemoryWritingFragmentsRunPerSample;
if plan.writes && cx.profile.fields().workarounds.contains(&per_sample) {
return Err(
Unsupported::driver_defect(Feature::PixelCoverageAtSampleRate, per_sample).into(),
);
}
if let (true, Some(r)) = (plan.looped, late) {
return Err(r.error());
}
cx.families.stage_io.interface.coverage_loop = match (plan.looped, plan.refusal.or(late)) {
(true, _) => CoverageLoop::Looped,
(false, None) if plan.driver_runs => CoverageLoop::DriverRunsPerSample,
(false, None) => CoverageLoop::Unlooped,
(false, Some(r)) => CoverageLoop::Refused(r),
};
@@ -43,37 +43,6 @@
//! operations. Demote needs no guard: Vulkan helper invocations have no memory side effects and
//! their outputs are discarded.
//!
//! **A discard before the storage writes, on Apple's compiler**. Where a fragment function discards
//! (`discard_fragment()`, which SPIRV-Cross writes for both a demote and a terminate), then writes
//! a texture, samples a texture through an argument buffer, and calls a `[[clang::optnone]]`
//! function (SPIRV-Cross's `spvFAdd` for an `OpFAdd` decorated `NoContraction`) in a branch only
//! discarded threads enter, Apple's compiler drops the texture writes of every live thread of a
//! simdgroup (8 by 4 pixels) holding a discarded thread: measured in plain Metal on an M4 with
//! macOS 27.0.1 (probes: MoltenVK's MSL of a storage-form fragment of our own lost its writes in
//! whole 8-by-4 blocks; without the sample, with the `optnone` call plain, in straight-line code or
//! in a branch live threads enter too, with direct binding, or with the discard recorded and taken
//! after the write, every write landed, and color outputs landed in every form). MoltenVK binds
//! through argument buffers, and on an Apple GPU it carries
//! `DriverWorkaround::DiscardDropsSimdgroupStores`. There a function meets the
//! defect ([`late_discards`]) where it samples (`sample` at any LOD, or `gather`), and after a site
//! that would discard at once (a demote; a terminate outside an interlock, since inside one it
//! records the discard and returns to the entry) it computes or returns a floating-point value (the
//! lowering may decorate such arithmetic `NoContraction`: `x + -0.0` rounds every narrowed value
//! and color write) and writes storage: a store, atomic or image write (buffer stores and atomics
//! are not measured, and are counted), or the storage images its entry writes at its returns (a
//! storage-form color, an imageblock, a shader-side stencil's shadow, an in-shader depth test's
//! stand-in). A function that writes colors alone keeps its forms. In such a function those sites
//! are predicated where predication holds (no store, atomic, image write or non-quad subgroup
//! operation after such a site): the discarded invocation runs on, as Metal's discarded thread
//! does, a lane of its quad, its outputs dropped and its storage writes at the returns skipped, and
//! it is killed once past them, after the critical section. Its census names its discards
//! `fragment.discard.deferred`. Where some such site cannot be predicated (the side-effect guard,
//! is not threaded through the access and texture emitters yet), the function keeps its forms and
//! records `PrecisionNote::DiscardDropsSimdgroupStores`: its storage writes may be lost as the
//! defect loses them. The defect needs no discard: the quad helpers past a primitive's edges meet
//! it alone, and the emitted module keeps every helper invocation, a demoted one included, out of
//! the branches that hold such a call where that is exact (`spirv::helper_branches`).
//!
//! **A quad of helpers alone**. Metal drops a quad whose every thread is discarded from the
//! simdgroup. Vulkan leaves that to the implementation: one whose four invocations are all helpers
//! "may" be terminated, and under `RequireFullQuadsKHR` lavapipe keeps such a quad a lane of a
@@ -96,7 +65,6 @@ use crate::air::ir::{
use crate::budget::Meter;
use crate::device::requirements::VkFeature;
use crate::device::subgroup::OpBits;
use crate::device::DriverWorkaround;
use crate::error::{Capability, Error, Feature, LowerFamily, Unsupported};
use crate::lower::select::SelectCx;
use crate::lower::simd::uniform::Uniformity;
@@ -127,9 +95,6 @@ impl Reach {
const TANGLED: u8 = 1;
const NON_QUAD: u8 = 2;
const SIDE_EFFECT: u8 = 4;
/// A floating-point value computed or returned: where the lowering may emit arithmetic
/// decorated `NoContraction` (`late_discards`).
const FLOAT: u8 = 8;
fn has(self, bit: u8) -> bool {
self.0 & bit != 0
@@ -159,30 +124,12 @@ fn is_thread_ptr(cx: &SelectCx<'_>, v: Value) -> bool {
})
}
/// Whether type `ty` holds a floating-point value (a scalar, or one in a vector, array or
/// struct).
fn floating(cx: &SelectCx<'_>, ty: TypeId) -> bool {
match cx.entry.module.types().get(ty) {
Some(Type::Half | Type::BFloat | Type::Float | Type::Double) => true,
Some(Type::Vector { elem, .. } | Type::Array { elem, .. }) => floating(cx, *elem),
Some(Type::Struct { fields, .. }) => fields.iter().any(|&f| floating(cx, f)),
_ => false,
}
}
/// What instruction `id` itself contributes.
fn contribution(cx: &SelectCx<'_>, id: InstId, inst: &Inst) -> Reach {
let mut r = 0u8;
if cx.values.inst(id).is_some_and(|v| cx.tangled.contains(&v)) {
r |= Reach::TANGLED;
}
let returned = match inst.kind {
InstKind::Ret(Some(v)) => cx.value_ty(v).is_some_and(|t| floating(cx, t)),
_ => false,
};
if returned || floating(cx, inst.ty) {
r |= Reach::FLOAT;
}
r |= match &inst.kind {
InstKind::Store { ptr, .. } if !is_thread_ptr(cx, *ptr) => Reach::SIDE_EFFECT,
InstKind::AtomicRmw { .. } | InstKind::CmpXchg { .. } => Reach::SIDE_EFFECT,
@@ -380,12 +327,6 @@ pub(super) struct DiscardPlan {
pub forms: BTreeMap<InstId, DiscardForm>,
pub quad_exits: BTreeSet<InstId>,
pub counted_before: bool,
/// The sites that would discard at once were predicated against the store-dropping defect
/// ([`late_discards`]).
pub deferred: bool,
/// The function meets the store-dropping defect and some such site could not be predicated:
/// it keeps its forms (`PrecisionNote::DiscardDropsSimdgroupStores`).
pub exposed: bool,
/// The side effects a predicated site reaches, each run only where the invocation was not
/// discarded ([`guarded`]).
pub guarded: BTreeSet<InstId>,
@@ -529,53 +470,6 @@ fn quad_exits_hold(
Ok(held)
}
/// Whether the function meets the store-dropping defect (the module docs): its driver has
/// `DriverWorkaround::DiscardDropsSimdgroupStores`; it samples; a floating-point value is
/// computed or returned after some site of `exposed` (each with what is reachable after it),
/// where the lowering may emit the `NoContraction` arithmetic the defect needs; and a storage
/// write follows such a site: a store, atomic or image write, or one the entry makes at its
/// returns ([`stores_at_return`]).
fn late_discards(cx: &SelectCx<'_>, body: &Body, exposed: &[(InstId, Reach)]) -> bool {
cx.profile
.fields()
.workarounds
.contains(&DriverWorkaround::DiscardDropsSimdgroupStores)
&& exposed.iter().any(|(_, r)| r.has(Reach::FLOAT))
&& (stores_at_return(cx) || exposed.iter().any(|(_, r)| r.has(Reach::SIDE_EFFECT)))
&& samples(body)
}
/// Whether the function writes storage images at its returns, past every discard site: a color
/// attachment it writes in the storage form, its imageblock, a shader-side stencil's shadow, or an
/// in-shader depth test's stand-in.
fn stores_at_return(cx: &SelectCx<'_>) -> bool {
let fp = &cx.families.fragment;
fp.fetch
.values()
.any(|c| c.writes && !c.view.stores_nothing())
|| fp.imageblock.is_some()
|| fp.stencil.is_some()
|| fp.depth_test.is_some()
}
/// Whether the function samples a texture through a sampler (`sample`, at any LOD or with
/// gradients, or `gather`), which the store-dropping defect needs ([`late_discards`]).
fn samples(body: &Body) -> bool {
body.insts.values().any(|inst| match &inst.kind {
InstKind::Call(call) => matches!(
&call.callee,
Callee::Air {
op: AirIntrinsic::Texture(t),
..
} if matches!(
t.op,
TexOp::Sample { .. } | TexOp::SampleGrad { .. } | TexOp::Gather { .. }
)
),
_ => false,
})
}
/// Decide the form of every discard site in `sites`, and where whole quads exit. `interlocked`: the
/// function runs inside an interlock.
pub(super) fn plan(
@@ -664,34 +558,6 @@ pub(super) fn plan(
}
planned.forms.insert(site, form);
}
// On a driver whose compiler drops a simdgroup's live threads' storage writes where one of
// them discards, a function that meets the defect discards no thread before those writes
// (the module docs): each site that would discard at once (a demote, or a terminate outside
// an interlock; inside one a terminate records the discard and returns to the entry) is
// predicated where that holds, and else the function keeps its forms, recorded.
let exposed: Vec<(InstId, Reach)> = placed
.iter()
.zip(&after)
.filter(|((site, _), _)| match planned.forms.get(site) {
Some(DiscardForm::Demote) => true,
Some(DiscardForm::Terminate) => !interlocked,
_ => false,
})
.map(|(&(site, _), &r)| (site, r))
.collect();
if late_discards(cx, body, &exposed) {
// A side effect after a site is guarded; a non-quad subgroup operation stops the
// predicate (the module docs).
let held = exposed.iter().all(|(_, r)| !r.has(Reach::NON_QUAD));
if held {
for (site, _) in exposed {
planned.forms.insert(site, DiscardForm::Predicate);
}
planned.deferred = true;
} else {
planned.exposed = true;
}
}
// Every side effect a predicated site reaches runs only where the invocation was not
// discarded. No such site reaches a non-quad subgroup operation here, so no asynchronous
// copy either.
@@ -127,14 +127,7 @@
//! (`StorageAttachmentUse::view`). Either needs `sampleRateShading`. The pixel interlock orders
//! every invocation covering the pixel, and so each sample's. A returned sample mask keeps an
//! invocation's write exactly when it sets the invocation's sample's bit (measured), so each write
//! is gated on that bit ([`sample_bit`]); at one sample on bit 0 (measured). A driver that drops
//! the image writes of an early-tests fragment shader in a multisampled pass
//! (`DriverWorkaround::EarlyTestsDropMultisampledImageWrites`: MoltenVK on Apple's GPU) refuses the
//! per-sample form's writes where the module declares early tests (`Needs::DriverDefect`). Where
//! only a depth or stencil attachment would have the module declare them, it declares none there:
//! it stores before the tests and states `TestedStorageWrites` without the early-tests variant, so
//! only a draw whose tests drop no fragment runs it; a function whose Metal source declares early
//! tests keeps the refusal.
//! is gated on that bit ([`sample_bit`]); at one sample on bit 0 (measured).
//!
//! **A write mask** short of the format's channels: Metal keeps the channels the mask leaves out.
//! The write reads the texel at the pixel first and writes those channels back as it read them
@@ -316,7 +309,6 @@ use std::collections::{BTreeMap, BTreeSet};
use crate::air::abi::{AbiInt, OutputRole, ParamRole};
use crate::air::intrinsics::{AirIntrinsic, Fragment, PackDir, PackFormat};
use crate::air::ir::{Callee, InstKind, Type as AirType, TypeId as AirTypeId, Value};
use crate::device::profile::DriverWorkaround;
use crate::device::requirements::{FormatUsage, VkFeature};
use crate::device::DeviceProfile;
use crate::error::{
@@ -1198,16 +1190,6 @@ pub(crate) fn storage_form(
}
let kept = crate::metal::state::color_write_mask(kept)?;
let f = p.fields();
// The per-sample form's writes are storage image writes of the fragment shader; where it
// declares early tests, a driver that drops such writes in a pass of more than one sample
// would lose every one.
let defect = DriverWorkaround::EarlyTestsDropMultisampledImageWrites;
if multisampled && writes && use_.early_tests && f.workarounds.contains(&defect) {
return Ok(Err(Unsupported::driver_defect(
Feature::FramebufferFetch,
defect,
)));
}
// What the form needs whatever view it takes, and what the view's own route lacks.
let mut common = Vec::new();
let mut route = Vec::new();
@@ -1397,25 +1379,23 @@ struct StoredBeforeTests {
/// Only its discard keeps the function from early tests: its stores are Metal's where a
/// draw's tests drop no fragment, and under early tests where they write and count nothing.
tested: bool,
/// It writes other memory, or returns depth, stencil, or a sample mask, or early tests would
/// lose its writes (`dropped`): its stores are Metal's only where a draw's tests drop no
/// fragment.
/// It writes other memory, or returns depth, stencil, or a sample mask: its stores are Metal's
/// only where a draw's tests drop no fragment.
untested: bool,
}
/// [`StoredBeforeTests`] of a function whose body holds `body`, that Metal runs under early tests
/// where `declared_early` and returns depth, stencil, or a sample mask where `exports`, in a
/// pipeline with a depth or stencil attachment where `depth_or_stencil`, where early tests would
/// drop its storage writes where `dropped`.
/// pipeline with a depth or stencil attachment where `depth_or_stencil`.
fn stored_before_tests(
body: &BodyFacts,
(declared_early, exports): (bool, bool),
(depth_or_stencil, dropped): (bool, bool),
depth_or_stencil: bool,
) -> StoredBeforeTests {
let testable = depth_or_stencil && !(exports || body.side_effects);
StoredBeforeTests {
tested: !declared_early && testable && body.discards,
untested: !declared_early && depth_or_stencil && (exports || body.side_effects || dropped),
untested: !declared_early && depth_or_stencil && (exports || body.side_effects),
}
}
@@ -1601,48 +1581,18 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> {
// declaration would change nothing, and it is left out: Apple's GPU drops the image writes
// of an early-tests fragment shader in a pass of more than one sample.
let testable = inputs.depth_or_stencil && !(exports || body.side_effects);
// A driver that drops the image writes of an early-tests fragment shader in a pass of more
// than one sample would lose every storage write of a function that writes a fetched color
// beside a depth or stencil attachment under early tests: such a function declares none (unless
// Metal's does), and stores before the tests, Metal's where its draws' tests drop no fragment;
// it has no early-tests variant. (its form checks the driver's defect itself, and the device
// blends it where that blocks it)
let writes_read = read.iter().any(|&color| {
outputs.iter().any(|o| {
matches!(
o.role,
OutputRole::RenderTarget {
attachment: AbiInt::Const(a),
index: 0,
..
} if a == color
)
})
});
let dropped = cx.inputs.multisampled
&& inputs.depth_or_stencil
&& writes_read
&& cx
.profile
.fields()
.workarounds
.contains(&DriverWorkaround::EarlyTestsDropMultisampledImageWrites);
// A function that only its discard keeps from early tests, on a device that requires ordered
// fetch (`tested`): its storage writes are Metal's where its draws' tests drop no fragment,
// before the tests, and where they write neither attachment and count no visibility result,
// under early tests (`LoweringInputs::read_only_tests`), which then drop no fragment Metal's
// later tests keep and leave the attachments as Metal's do; the plan of each draw checks
// which (`RuntimeFact::TestedStorageWrites`). One that writes other memory, or returns depth,
// stencil, or a sample mask, beside a depth or stencil attachment, or whose driver would drop
// its writes under early tests (`untested`): Metal runs its memory writes for every fragment,
// stencil, or a sample mask, beside a depth or stencil attachment (`untested`): Metal runs its memory writes for every fragment,
// those its tests then drop included, and tests what it returns (measured on Apple's M4), which
// early tests would not, so its storage writes before the tests are Metal's where its draws'
// tests drop no fragment, which the plan of each draw checks; it has no early-tests variant.
let StoredBeforeTests { tested, untested } = stored_before_tests(
&body,
(declared_early, exports),
(inputs.depth_or_stencil, dropped),
);
let StoredBeforeTests { tested, untested } =
stored_before_tests(&body, (declared_early, exports), inputs.depth_or_stencil);
let early_tests = declared_early
|| (testable && !body.discards && !untested)
|| (tested && cx.inputs.read_only_tests && !untested);
@@ -64,7 +64,6 @@ use crate::air::abi::{ImageblockArg, ImageblockKind, Member, OutputRole, StructI
use crate::air::container::Hash256;
use crate::air::ir::{ArgIdx, Type, TypeId as AirTypeId, Value};
use crate::device::requirements::VkFeature;
use crate::device::DriverWorkaround;
use crate::error::{Capability, Error, Feature, Unsupported};
use crate::lower::emit::EmitCx;
use crate::lower::select::SelectCx;
@@ -150,10 +149,6 @@ pub struct ImageblockPlan {
/// The module declares early fragment tests, which the function does not, so that a depth or
/// stencil test the fragment fails drops its write as Metal's does ([`plan_tests`]).
pub early_tests: bool,
/// The module declares no early fragment tests, which the function does: its draws test
/// before its write as each one's plan chooses, on a driver that would drop its writes under
/// early tests ([`plan_tests`]).
pub late_tests: bool,
}
/// An upper estimate of the words one view's members add (each leaf read or written, and a
@@ -522,16 +517,8 @@ fn declared_early(cx: &SelectCx<'_>) -> bool {
/// early tests (where only a discard kept them away, `early_variant`), and one whose depth test
/// acts the variant that runs the draw's depth test itself, before the write
/// (`depth_test`), and its stencil test too where that acts (`bind::graphics`).
///
/// A driver that drops every image write of an early-tests fragment shader in a pass of more than
/// one sample (`DriverWorkaround::EarlyTestsDropMultisampledImageWrites`, MoltenVK on Apple's
/// GPU) takes no early tests at more than one sample: the function's draws test in the shader
/// there, and one that declares early tests itself is refused as that defect.
fn plan_tests(cx: &mut SelectCx<'_>) -> Result<bool, Error> {
let defect = DriverWorkaround::EarlyTestsDropMultisampledImageWrites;
let drops = cx.inputs.multisampled && cx.profile.fields().workarounds.contains(&defect);
let declared = declared_early(cx);
if declared && !drops {
if declared_early(cx) {
return Ok(false);
}
let outputs = &cx.entry.ep.outputs;
@@ -545,20 +532,6 @@ fn plan_tests(cx: &mut SelectCx<'_>) -> Result<bool, Error> {
let exported = exports.depth.is_some() || exports.stencil.is_some() || exports.mask.is_some();
let body = super::fetch::body_facts(cx);
let only_outputs = !exported && !body.side_effects;
if declared {
// Metal tests such a function early. One whose only effects are its outputs and its
// write, which does not discard, leaves the attachments under late tests as under early
// ones, so where the driver's defect would drop its writes the module declares none and
// its draws test before the write as below. Another (a discard, an export, or other
// memory writes after its early tests) has no form here.
if !only_outputs || body.discards {
return Err(Unsupported::driver_defect(Feature::Imageblocks, defect).into());
}
if let Some(plan) = cx.families.fragment.imageblock.as_mut() {
plan.late_tests = true;
}
}
let only_outputs = only_outputs && !drops;
let fp = &cx.families.fragment;
// A framebuffer fetch's storage form that declares early tests holds the function to them,
// which keeps the write Metal's: it declares them only where the function would here.
@@ -572,21 +545,13 @@ fn plan_tests(cx: &mut SelectCx<'_>) -> Result<bool, Error> {
RuntimeFact::TestedStorageWrites { early_variant, .. } => Some(early_variant),
_ => None,
});
match stated {
// The storage form's early-tests variant (whose function writes no other memory and
// exports nothing) would lose this write to the driver's defect.
Some(true) if drops => {
return Err(Unsupported::driver_defect(Feature::Imageblocks, defect).into());
}
Some(_) => {}
None => {
cx.facts.insert(RuntimeFact::TestedStorageWrites {
early_tests: only_outputs && cx.inputs.read_only_tests,
early_variant: only_outputs,
});
if cx.inputs.shader_tests && cx.families.fragment.depth_test.is_none() {
super::depth_test::plan(cx, exports)?;
}
if stated.is_none() {
cx.facts.insert(RuntimeFact::TestedStorageWrites {
early_tests: only_outputs && cx.inputs.read_only_tests,
early_variant: only_outputs,
});
if cx.inputs.shader_tests && cx.families.fragment.depth_test.is_none() {
super::depth_test::plan(cx, exports)?;
}
}
Ok(stated.is_none() && only_outputs && cx.inputs.read_only_tests)
@@ -36,7 +36,6 @@
use std::collections::BTreeMap;
use crate::air::abi::{AbiInt, OutputRole, Stage as AbiStage};
use crate::device::profile::DriverWorkaround;
use crate::device::requirements::{FormatUsage, VkFeature};
use crate::device::DeviceProfile;
use crate::error::{Attachment, Capability, Error, Feature, RuntimeInput, Unsupported};
@@ -209,13 +208,7 @@ pub(super) fn plan(cx: &mut SelectCx<'_>) -> Result<(), Error> {
// tests (see the module docs).
let stores = planned.values().any(InputShadow::stores);
if inputs.depth_or_stencil && stores && !declared_early {
let dropped = multisampled
&& cx
.profile
.fields()
.workarounds
.contains(&DriverWorkaround::EarlyTestsDropMultisampledImageWrites);
if exports || body.discards || body.side_effects || dropped {
if exports || body.discards || body.side_effects {
let color = planned.keys().next().copied().unwrap_or_default();
return Err(refused(color));
}
@@ -156,9 +156,6 @@ pub enum FragmentStrategy {
impl FamilyStrategy for FragmentStrategy {
fn name(&self, plans: &FamilyPlans) -> Cow<'static, str> {
Cow::Borrowed(match self {
FragmentStrategy::Discard if plans.fragment.deferred_discards => {
"fragment.discard.deferred"
}
FragmentStrategy::Discard => "fragment.discard",
FragmentStrategy::NumSamples(_) => "fragment.num_samples",
FragmentStrategy::IsHelperThread => "fragment.is_helper_thread",
@@ -191,10 +188,6 @@ pub struct FragmentPlan {
/// or a helper exits, as Metal drops such a quad from the simdgroup: every site is then
/// predicated, or, where a side effect follows one, every site demotes. Filled by [`finish`].
pub quad_exits: BTreeSet<InstId>,
/// The sites that would discard at once are predicated against the driver's store-dropping
/// defect (`DriverWorkaround::DiscardDropsSimdgroupStores`), so the census names the
/// function's discards `fragment.discard.deferred`. Filled by [`finish`].
pub deferred_discards: bool,
/// The stores, atomics, image writes and copies a predicated site reaches: each runs only
/// where the invocation was not discarded ([`not_discarded`]). Filled by [`finish`].
pub guarded: BTreeSet<InstId>,
@@ -387,18 +380,12 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> {
forms,
quad_exits,
counted_before,
deferred,
exposed,
guarded,
} = discard::plan(cx, &sites, interlock.is_some(), m)?;
if counted_before {
cx.precision
.insert(PrecisionNote::QuadsCountedBeforeDiscard);
}
if exposed {
cx.precision
.insert(PrecisionNote::DiscardDropsSimdgroupStores);
}
if !quad_exits.is_empty() {
// The exits' quad swaps are quad operations of the simd family's class.
let simd = &mut cx.families.simd;
@@ -457,7 +444,6 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> {
let fp = &mut cx.families.fragment;
fp.discards = forms;
fp.quad_exits = quad_exits;
fp.deferred_discards = deferred;
fp.guarded = guarded;
fp.terminate_invocation = terminate;
fp.interlock = interlock;
@@ -515,10 +501,6 @@ pub fn declare(
if fp.fetch_early_tests || imageblock_early {
modes.push(ExecMode::EarlyFragmentTests);
}
// The function's own early tests, where the imageblock's write tests late instead.
if fp.imageblock.as_ref().is_some_and(|p| p.late_tests) {
modes.retain(|m| *m != ExecMode::EarlyFragmentTests);
}
if fp.records_discards() {
let bool_ = mb.ty(SType::Bool)?;
let no = mb.constant(Constant::Scalar {
+8 -113
View File
@@ -53,14 +53,8 @@
//! A point mesh whose vertex type has no `point_size` culls every primitive (Metal draws none);
//! it still writes `PointSize = 1.0` for each vertex, which a point topology needs.
//!
//! **Staged indices.** On a driver that misplaces a store into one component of an index vector
//! (`DriverWorkaround::MeshIndexComponentStoresMisplaced`: lavapipe before Mesa 26.2), a line or
//! triangle mesh keeps its indices in workgroup words, one per index ([`Declared::staged`]): the
//! wrapper zeroes them where it would zero the indices, `set_index` and `set_indices` store into
//! them, and after the body each invocation writes its slots' indices whole, one vector per
//! primitive. They count among the wrapper's workgroup words ([`workgroup_limit`]). The wrapper's
//! words (the grid, the count, the staged indices) take the function's coherence of shared
//! memory (`NonPrivatePointer` under the Vulkan model), so its barriers order them.
//! The wrapper's words (the grid, the count) take the function's coherence of shared memory
//! (`NonPrivatePointer` under the Vulkan model), so its barriers order them.
//!
//! Each `set_*` writes straight to its output array: `set_position`, `set_point_size`,
//! `set_clip_distance` and `set_vertex_data` at their vertex, `set_primitive_culled`,
@@ -120,7 +114,6 @@ use crate::air::intrinsics::{AirIntrinsic, Elem, MemFlags, Mesh as MeshOp, NumTy
use crate::air::ir::{Callee, Const, Inst, InstId, InstKind, Value};
use crate::air::Entry;
use crate::bind::mesh_arguments::{METAL_MESH_GRID_AXIS, METAL_MESH_GRID_TOTAL};
use crate::device::profile::DriverWorkaround;
use crate::device::requirements::{VkExtension, VkFeature, VkLimit};
use crate::device::DeviceProfile;
use crate::error::{Capability, Error, Feature, LowerFamily, Unsupported};
@@ -251,10 +244,6 @@ pub struct MeshPlan {
pub outputs: Vec<Output>,
/// A point mesh whose vertex type has no `point_size`: it draws nothing (the module docs).
pub unsized_points: bool,
/// A line or triangle mesh on a driver that misplaces a store into one component of an
/// index vector (`DriverWorkaround::MeshIndexComponentStoresMisplaced`): its indices are
/// workgroup words ([`Declared::staged`]) that the wrapper writes to the indices whole.
pub staged_indices: bool,
/// An object or mesh function on a device without `VK_EXT_mesh_shader`: a `GLCompute`
/// entry, an object function writing its grid and payload to its slot of the draw's work
/// buffer and a mesh function its outputs as records ([`records`], the module docs).
@@ -441,21 +430,14 @@ pub fn payload_extent(cx: &SelectCx<'_>) -> Option<u64> {
Some(own.max(object))
}
/// The workgroup memory limit of the entry ([`stage_workgroup_limit`] of its stage, payload and
/// staged indices).
/// The workgroup memory limit of the entry ([`stage_workgroup_limit`] of its stage and payload).
pub fn workgroup_limit(cx: &SelectCx<'_>) -> WorkgroupLimit {
stage_workgroup_limit(
cx.stage,
cx.profile,
payload_extent(cx),
staged_index_bytes(cx),
)
stage_workgroup_limit(cx.stage, cx.profile, payload_extent(cx))
}
/// The workgroup memory limit of a `stage` entry on `profile` ([`arena::workgroup_limit`]), with
/// its payload arena's bytes where it has a payload of `payload` bytes (`arena::payload_bytes`):
/// an object or mesh entry's workgroup memory and payload share a limit. `staged` is a mesh
/// entry's staged index words' bytes ([`staged_index_bytes`]). An emulated object or mesh
/// an object or mesh entry's workgroup memory and payload share a limit. An emulated object or mesh
/// function's is the compute stage's, with its grid or count words and its payload. The binder
/// checks an object function's arena with the encoder's lengths against it
/// (`RuntimeFact::ObjectThreadgroupArena`).
@@ -463,7 +445,6 @@ pub fn stage_workgroup_limit(
stage: Stage,
profile: &DeviceProfile,
payload: Option<u64>,
staged: u64,
) -> WorkgroupLimit {
let limits = &profile.fields().limits;
// An emulated entry's: the compute stage's, with its wrapper's words (an object function's
@@ -478,38 +459,12 @@ pub fn stage_workgroup_limit(
};
}
let w = arena::workgroup_limit(stage, limits);
let w = WorkgroupLimit {
wrapper: w.wrapper.saturating_add(staged),
..w
};
match payload {
Some(size) => w.with_payload(arena::payload_bytes(size)),
None => w,
}
}
/// The bytes of the workgroup words a mesh entry keeps its indices in on a driver that misplaces
/// a store into one component of an index vector
/// (`DriverWorkaround::MeshIndexComponentStoresMisplaced`, [`MeshPlan::staged_indices`]): a word
/// per index of a line or triangle mesh there, and none elsewhere.
fn staged_index_bytes(cx: &SelectCx<'_>) -> u64 {
let defect = DriverWorkaround::MeshIndexComponentStoresMisplaced;
if cx.stage != Stage::Mesh || !cx.profile.fields().workarounds.contains(&defect) {
return 0;
}
let Some(out) = mesh_outputs(cx) else {
return 0;
};
let k: u64 = match out.topology {
MeshTopology::Point => return 0,
MeshTopology::Line => 2,
MeshTopology::Triangle => 3,
};
u64::from(out.max_primitives)
.saturating_mul(k)
.saturating_mul(4)
}
/// The check of a payload of `size` bytes: its arena within `maxTaskPayloadSize`, and, with the
/// wrapper's workgroup words, within the stage's limit on its workgroup memory and payload together
/// (the function's own workgroup memory joins that check where it is planned).
@@ -648,15 +603,8 @@ pub fn plan_entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
if point_size && shape.topology == MeshTopology::Point {
crate::lower::stage_io::note_device_point_size(cx);
}
// Staged indices are the wrapper's workgroup words, held to the stage's limit whether or not
// the function has threadgroup memory of its own.
let staged = !emulated && staged_index_bytes(cx) > 0;
if staged {
workgroup_limit(cx).check(0)?;
}
let plan = &mut cx.families.mesh;
plan.mesh = Some(shape);
plan.staged_indices = staged;
plan.emulated = emulated;
plan.payload_words = if emulated { payload_words } else { 0 };
plan.unsized_points = shape.topology == MeshTopology::Point && !point_size;
@@ -1058,9 +1006,6 @@ pub struct Declared {
pub count: Option<GlobalId>,
/// The object function's mesh grid, a workgroup `uvec3`.
pub grid: Option<GlobalId>,
/// A mesh function's staged indices ([`MeshPlan::staged_indices`]): a workgroup `uint` per
/// index.
pub staged: Option<GlobalId>,
/// An emulated mesh function's records buffer (`SyntheticBinding::MeshRecords`).
pub records: Option<GlobalId>,
/// An emulated mesh function's first word of its threadgroup's records: a private `uint`
@@ -1312,11 +1257,6 @@ pub fn declare(
let ty = array(mb, index, shape.primitives)?;
d.indices = Some(mb.builtin(b, IoDir::Output, ty)?);
d.count = Some(mb.plain_global(StorageClass::Workgroup, u32_, None)?);
if mp.staged_indices {
let n = shape.primitives.saturating_mul(shape.per_primitive());
let words = array(mb, u32_, n)?;
d.staged = Some(mb.plain_global(StorageClass::Workgroup, words, None)?);
}
Ok(d)
}
@@ -1366,7 +1306,7 @@ fn k32(fb: &mut FunctionBuilder<'_>, n: u32) -> BResult<SValue> {
}
/// The memory operands of a load or (`store`) a store of one of the wrapper's workgroup words
/// (the grid, the count, the staged indices), which other invocations read after a barrier: the
/// (the grid, the count), which other invocations read after a barrier: the
/// function's coherence of shared memory (`NonPrivatePointer` under the Vulkan model).
fn word_access(
coherence: Coherence,
@@ -1691,18 +1631,6 @@ fn store_index(
if k == 1 {
return store_element(cx, fb, g, len, at, None, value);
}
if let Some(w) = cx.decl.families.mesh.staged {
// The index's own workgroup word, which the wrapper writes to the indices whole.
let coherence = coherence(cx.plan);
let n = k32(fb, len)?;
let inside = fb.binary(BinOp::ULessThan, at, n)?;
return when(fb, cx, inside, move |fb, _| {
let base = fb.module().global_value(w)?;
let ptr = fb.access_chain(base, &[at])?;
let access = word_access(coherence, fb, true)?;
fb.store(ptr, value, access)
});
}
let n = k32(fb, len)?;
let inside = fb.binary(BinOp::ULessThan, at, n)?;
let kk = k32(fb, k)?;
@@ -2019,29 +1947,13 @@ pub fn wrap_entry(cx: &mut EmitCx<'_>, mb: &mut ModuleBuilder, body: FuncId) ->
};
let none = fb.module().constant(Constant::Null { ty: index_ty })?;
let none = fb.module().const_value(none)?;
// Staged indices are zeroed in their words and written to the indices after the body; the
// others are zeroed in place.
let staged = d.staged;
let k = shape.per_primitive();
let kk = k32(&mut fb, k)?;
// The indices are zeroed in place.
strided(cx, &mut fb, (lin, n), shape.primitives, move |fb, _, p| {
let unstaged = staged.is_none().then_some((indices, none));
for (g, v) in unstaged.into_iter().chain([(culled, no), (ids, p)]) {
for (g, v) in [(indices, none), (culled, no), (ids, p)] {
let base = fb.module().global_value(g)?;
let ptr = fb.access_chain(base, &[p])?;
fb.store(ptr, v, MemAccess::default())?;
}
if let Some(w) = staged {
let at = fb.binary(BinOp::IMul, p, kk)?;
for j in 0..k {
let off = k32(fb, j)?;
let at = fb.binary(BinOp::IAdd, at, off)?;
let base = fb.module().global_value(w)?;
let ptr = fb.access_chain(base, &[at])?;
let access = word_access(coherence, fb, true)?;
fb.store(ptr, zero, access)?;
}
}
Ok(())
})?;
if let Some(g) = sizes {
@@ -2070,23 +1982,6 @@ pub fn wrap_entry(cx: &mut EmitCx<'_>, mb: &mut ModuleBuilder, body: FuncId) ->
fb.load(p, access)?
};
strided(cx, &mut fb, (lin, n), shape.primitives, move |fb, cx, p| {
if let Some(w) = staged {
// The primitive's staged indices, written whole.
let at = fb.binary(BinOp::IMul, p, kk)?;
let mut words = Vec::new();
for j in 0..k {
let off = k32(fb, j)?;
let at = fb.binary(BinOp::IAdd, at, off)?;
let base = fb.module().global_value(w)?;
let ptr = fb.access_chain(base, &[at])?;
let access = word_access(coherence, fb, false)?;
words.push(fb.load(ptr, access)?);
}
let whole = fb.composite_construct(index_ty, &words)?;
let base = fb.module().global_value(indices)?;
let ptr = fb.access_chain(base, &[p])?;
fb.store(ptr, whole, MemAccess::default())?;
}
let past = fb.binary(BinOp::UGreaterThanEqual, p, drawn)?;
when(fb, cx, past, move |fb, _| {
let base = fb.module().global_value(culled)?;
@@ -2194,16 +2194,6 @@ fn input_builtin(
if !frag.barycentric {
return Err(cx.invariant("a barycentric builtin without the feature"));
}
// A driver that rejects a shader reading both forms refuses the second.
let defect = DriverWorkaround::BothBarycentricFormsRejected;
let other = StageBuiltin::BaryCoord {
perspective: !perspective,
};
if cx.families.stage_io.interface.builtins.contains(&other)
&& cx.profile.fields().workarounds.contains(&defect)
{
return Err(Unsupported::driver_defect(Feature::Barycentrics, defect).into());
}
let b = if perspective {
B::BaryCoordKHR
} else {
+1 -21
View File
@@ -9,9 +9,6 @@
//! - **In shader**: loads read at `select(inb, off, 0)` and yield `select(inb, v, 0)`; stores and
//! atomics sit in a builder-closed `if_(inb)`.
//!
//! An atomic takes [`atomic_encoding`]: the in-shader check also where a driver workaround says
//! its robustness leaves buffer atomics uncontained.
//!
//! An image or texel buffer is contained by the texture family: its reads by
//! [`device_reads_texels`], its writes by [`device_drops_texel_writes`], each in the shader where
//! the device's robustness does not give Metal's answer. Validation labels its runs by the same two
@@ -22,7 +19,7 @@
//! relative to the containment domain's base, so a wrapped GEP result is a huge offset and fails
//! the check.
use crate::device::profile::{Containment, DriverWorkaround, Robustness};
use crate::device::profile::{Containment, Robustness};
use crate::device::DeviceProfile;
use crate::spirv::builder::FunctionBuilder;
use crate::spirv::error::BResult;
@@ -49,23 +46,6 @@ pub fn encoding(p: &DeviceProfile) -> Check {
}
}
/// The descriptor-view encoding of an atomic on `p`: [`encoding`], except that where it relies on
/// buffer robustness and the driver's robustness leaves a storage buffer's atomics uncontained
/// (`DriverWorkaround::BufferAtomicsUncontained`), the atomic is checked in the shader.
pub fn atomic_encoding(p: &DeviceProfile) -> Check {
let fields = p.fields();
match (encoding(p), fields.containment) {
(Check::None, Containment::On { .. })
if fields
.workarounds
.contains(&DriverWorkaround::BufferAtomicsUncontained) =>
{
Check::InShader
}
(check, _) => check,
}
}
/// Whether the device's robustness on `p` returns Metal's out-of-bounds texel for a read of an
/// image (`buffer`: a texel buffer), so the read is left to it: `robustImageAccess2`
/// (`robustBufferAccess2` for a texel buffer), under containment. Elsewhere the shader checks the
@@ -1427,47 +1427,6 @@ pub enum PrecisionNote {
/// Validation derives no tolerance and no explanation from it: a difference stays a
/// mismatch for review.
ExtendedRangeBlendSource,
/// A fragment function meets the store-dropping defect of
/// [`DriverWorkaround::DiscardDropsSimdgroupStores`] (MoltenVK on an Apple GPU: Apple's
/// compiler drops the texture writes of every live thread of a simdgroup holding a discarded
/// thread, where the function discards, then writes storage, samples, and calls
/// SPIRV-Cross's `optnone` arithmetic helpers), and a discard site that would discard at
/// once cannot wait until after the writes: a store, atomic, image write or non-quad
/// subgroup operation follows it, which a predicated discard does not yet guard
/// (`lower::fragment::discard`). The module keeps its forms, so the live fragments of a
/// simdgroup (8 by 4 pixels) that holds a discarded one may lose their texture writes (and,
/// not measured, their buffer stores and atomics); color outputs are not affected.
///
/// Validation derives no tolerance and no explanation from it: a difference stays a
/// mismatch for review, deferred in C3 until an exact path exists.
///
/// [`DriverWorkaround::DiscardDropsSimdgroupStores`]: crate::device::DriverWorkaround::DiscardDropsSimdgroupStores
DiscardDropsSimdgroupStores,
/// A fragment function meets the store-dropping defect of
/// [`DriverWorkaround::DiscardDropsSimdgroupStores`] without a discard: SPIRV-Cross writes an
/// operation of the module as an `optnone` call (a sum, difference or product decorated
/// `NoContraction`, among others) where only helper invocations (the quad helpers past a
/// primitive's edges, or demoted invocations) may run it before a storage write (not in a
/// selection on a value every invocation of a draw computes alike), and keeping them out would
/// not be exact (`spirv::helper_branches`): a derivative or subgroup operation reads what they
/// compute there or after, an arm leaves its selection otherwise than at its merge, the call is
/// in a loop whose helper invocations may iterate alone, or it is in no branch at all but
/// SPIRV-Cross writes it in one (a `?:` arm, the right side of a `&&` or `||`, or a
/// selection's arm, where its value is read once). Only where a path from the call
/// ends without a tangled instruction (an implicit-LOD sample, an LOD query, a derivative, a
/// subgroup operation) that reads what it computes: one after it keeps the writes. And only
/// where no identity shuffle of the call's result can follow it, which the module places
/// elsewhere to keep the writes: the device has no fragment-stage subgroup shuffle, or the
/// result is a 64-bit or `bool` lane, or an 8- or 16-bit one without
/// `shaderSubgroupExtendedTypes`. The live fragments of a simdgroup (8 by 4 pixels) whose
/// helpers make the call alone may lose their texture writes (and, not measured, their buffer
/// stores and atomics); color outputs are not affected.
///
/// Validation derives no tolerance and no explanation from it: a difference stays a
/// mismatch for review, deferred in C3 until an exact path exists.
///
/// [`DriverWorkaround::DiscardDropsSimdgroupStores`]: crate::device::DriverWorkaround::DiscardDropsSimdgroupStores
HelperBranchDropsSimdgroupStores,
/// [`PrecisionNote::ExtendedRangeBlendSource`] for a `float` color output (a scalar or vector
/// of AIR's `float`): blended into an extended-range or padded 10-bit attachment in the shader
/// in the device's arithmetic, which the device's compiler may contract and regroup, where
+1 -42
View File
@@ -3285,10 +3285,6 @@ fn lower_bounded<K>(
},
crate::lower::emit::Emitted { mut module, merged },
) = stage_bound::emit(r, p, (word_cap, bounds), m)?;
// On a driver whose compiler loses a simdgroup's storage writes after an `optnone` call only
// its helper invocations make, those invocations take another arm where that is exact, and
// each such call left is fenced once every analysis below has read the module.
let (helper_guard, fences) = crate::spirv::helper_branches::guard_for(&mut module, p, m)?;
let function_tables = spec.function_tables.clone();
let reaches_command_buffers = spec.may_encode_indirect_commands();
let command_writes = spec.command_writes();
@@ -3429,10 +3425,6 @@ fn lower_bounded<K>(
precision.sort_unstable();
}
}
if helper_guard.exposed {
precision.push(PrecisionNote::HelperBranchDropsSimdgroupStores);
precision.sort_unstable();
}
if numbering_differs {
precision.push(PrecisionNote::LinkedSamplerNumbering);
precision.sort_unstable();
@@ -3449,8 +3441,6 @@ fn lower_bounded<K>(
precision.push(PrecisionNote::DeviceSampling);
precision.sort_unstable();
}
// The fences are identities, which the analyses above would read as moves between lanes.
fences.apply(&mut module)?;
let stats = crate::spirv::verify::verify(&module, p, m)?;
let kept = keep(&module);
let mut symbols =
@@ -3653,7 +3643,7 @@ fn lower_bounded<K>(
subgroup: plan.subgroup,
reconvergence,
precision,
strategies: emitted_census(&plan, helper_guard),
strategies: census(&plan),
stats,
// The module's own blob (the identity domains) is in its words: the artifact carries a
// bound blob's bytes alone.
@@ -3735,37 +3725,6 @@ fn census(plan: &Plan) -> StrategyCensus {
c
}
/// [`census`] of the emitted module: the plan's, the selections whose helper invocations take
/// another arm (`spirv::helper_branches`), each with its helper query and one or two logical
/// operations (about 12 words), and the `optnone` calls an identity shuffle follows, each with
/// its lane's load and its shuffle (about 10 words; a structure's two members and their
/// construction about 30).
fn emitted_census(
plan: &Plan,
helper_guard: crate::spirv::helper_branches::Guarded,
) -> StrategyCensus {
let mut c = census(plan);
if helper_guard.selections > 0 {
c.entries.insert(
crate::spirv::helper_branches::STRATEGY.to_owned(),
StrategyUse {
uses: helper_guard.selections,
words: u64::from(helper_guard.selections) * 12,
},
);
}
if helper_guard.fences > 0 {
c.entries.insert(
crate::spirv::helper_branches::FENCE_STRATEGY.to_owned(),
StrategyUse {
uses: helper_guard.fences,
words: u64::from(helper_guard.fences) * 30,
},
);
}
c
}
/// The stage interface the artifact carries: the slots, the push placement, the module's link
/// contract (every descriptor binding and specialization constant it declares), and whether it
/// writes memory. A buffer slot's access is the function's, with what the accesses through loaded
@@ -100,10 +100,7 @@
//! sample from a loop over the coverage (`StageIo::coverage_loop`), its outputs the last pass's
//! (`PrecisionNote::LoopedSampleOutputs`); compiled without `multisampled` it is
//! `NeedsInput(Multisampled)`, and one the loop does not fit is refused for the reason its
//! interface records (`CoverageLoopRefusal`). On a driver that runs a
//! memory-writing function once per covered sample itself (`CoverageLoop::DriverRunsPerSample`,
//! MoltenVK on Apple's GPU) the function runs as written, without sample shading, and its other
//! reads are checked as below. A per-sample function reads the pixel values Vulkan has no pixel
//! interface records (`CoverageLoopRefusal`). A per-sample function reads the pixel values Vulkan has no pixel
//! form for where Vulkan evaluates them, as a pixel-rate function does: `[[position]]`'s z and w
//! (the interpolated depth and `1/w`, at a position Vulkan does not state), `[[point_coord]]`
//! ("the fragment center, or the location of a sample"), `[[barycentric_coord]]`, and a centroid
@@ -973,11 +970,7 @@ fn sample_invocations(
// pixel's sample invocations: a quad holds one sample index, and no subgroup is promised to
// hold the rest. The function runs once per pixel instead, compiled for the pipeline, and its
// body once per covered sample, without sample shading; one the loop does not fit is refused
// for the reason its interface records. A driver that runs a
// memory-writing function once per covered sample whatever the pipeline's sample shading hands
// each run the pixel's coverage itself, as Metal does: the function's other reads are checked
// as any per-sample function's, and the pipeline enables no sample shading, under which that
// driver would mask the coverage.
// for the reason its interface records.
if io.builtins.contains(&StageBuiltin::SampleMaskIn) {
match io.coverage_loop {
CoverageLoop::Looped => return Ok(false),
@@ -988,10 +981,8 @@ fn sample_invocations(
Unsupported::not_representable(Feature::PixelCoverageAtSampleRate).into(),
)
}
CoverageLoop::DriverRunsPerSample => {}
}
}
let sample_shading = sample_shading && io.coverage_loop != CoverageLoop::DriverRunsPerSample;
if sample_shading && !rate {
return Err(refused());
}
@@ -455,13 +455,6 @@ pub enum CoverageLoop {
/// The function cannot loop over its covered samples: link refuses it in a pipeline of more
/// than one sample for this reason.
Refused(CoverageLoopRefusal),
/// The driver runs the function, which writes memory, once per covered sample whatever the
/// pipeline's sample shading, each run reading the pixel's coverage, as Metal does
/// (`DriverWorkaround::MemoryWritingFragmentsRunPerSample`): it is compiled as written, without
/// the loop, its `[[sample_id]]` and sample-qualified varyings read per sample, and link
/// enables no sample shading, under which the driver would hand each run only its own sample's
/// bit of the coverage.
DriverRunsPerSample,
}
/// Why a fragment function that reads `[[sample_mask]]` and runs once per sample on Metal has no
@@ -407,8 +407,6 @@ fn typed_module_of(
crate::lower::emit::emit_module(&spec, &plan, m)?;
crate::spirv::roll::roll_entry(&mut module, m)?;
crate::spirv::hoist::hoist_uniform_loads(&mut module, p.containment(), m)?;
let (_, fences) = crate::spirv::helper_branches::guard_for(&mut module, p, m)?;
fences.apply(&mut module)?;
crate::spirv::verify::verify(&module, p, m)?;
if walked(&plan) {
let words = crate::spirv::serialize::serialize(module.clone())?.words;
File diff suppressed because it is too large. Load diff
-1
View File
@@ -8,7 +8,6 @@ pub mod builder;
pub mod dead;
pub mod error;
pub mod half_hold;
pub mod helper_branches;
pub mod hoist;
pub mod ids;
// The CPU interpreter: test support for the crate's own tests.
@@ -32,7 +32,7 @@
use std::path::Path;
use crate::budget::Budget;
use crate::device::{Device, DeviceDescription, DevicePolicy, DriverWorkaround};
use crate::device::{Device, DeviceDescription, DevicePolicy};
use crate::error::{Error, Feature, Needs, RuntimeInput, Unsupported};
use crate::library::Library;
use crate::metal::PixelFormat;
@@ -111,17 +111,6 @@ fn device(stem: &str) -> Device {
Device::from_queries(description(stem), DevicePolicy::default()).expect("device")
}
/// The refusal of a memory writer on a driver that runs it once per covered sample where that
/// driver would mask its coverage, where `dev`'s profile carries that workaround.
fn per_sample_defect(dev: &Device) -> Option<Error> {
let defect = DriverWorkaround::MemoryWritingFragmentsRunPerSample;
dev.profile()
.fields()
.workarounds
.contains(&defect)
.then(|| Unsupported::driver_defect(Feature::PixelCoverageAtSampleRate, defect).into())
}
/// Every committed profile's stem, sorted.
fn stems() -> Vec<String> {
let dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("../metal2vulkan-validation/profiles");
@@ -256,10 +245,9 @@ fn a_coverage_reading_memory_writer_loops_over_its_covered_samples() {
for samples in [2, 4] {
let what = format!("{stem} at {samples}");
let d = render(&lib, function(&lib, COVERAGE), samples, false);
let driver_runs = per_sample_defect(&dev).is_some();
match dev.compile_render_pipeline(&d, &Budget::standard()) {
Ok(p) => {
looped += usize::from(!driver_runs);
looped += 1;
assert!(!p.graphics.sample_shading, "{what}");
assert_eq!(
Shape {
@@ -268,8 +256,8 @@ fn a_coverage_reading_memory_writer_loops_over_its_covered_samples() {
},
Shape {
sample_mask: true,
loops: !driver_runs,
find_lsb: !driver_runs,
loops: true,
find_lsb: true,
..Shape::default()
},
"{what}"
@@ -513,9 +501,8 @@ fn l3(dev: &Device, p: &RenderPipeline, what: &str) {
/// made), and the sample-qualified varying loops, read at each
/// pass's sample through `InterpolateAtSample` with no `Sample` decoration, or is refused as
/// needing the interpolation functions on a device that withholds them. A device that does not
/// make the memory writers refuses them for what it lacks, never for the loop, except a driver
/// that runs a memory writer once per covered sample (MoltenVK on Apple's GPU), which refuses them,
/// and the varying, as its defect, and every other function by its reason.
/// make the memory writers refuses them for what it lacks, never for the loop, and every other
/// function by its reason.
#[test]
fn the_loop_refuses_each_function_it_does_not_fit_by_its_reason() {
let Some(lib) = library("coverage_loop") else {
@@ -531,12 +518,7 @@ fn the_loop_refuses_each_function_it_does_not_fit_by_its_reason() {
for stem in stems() {
let dev = device(&stem);
let fits = COV_FITS.map(|f| coverage_loop_pipeline(&dev, &lib, COV_COVER, f));
let defect = per_sample_defect(&dev);
if let Some(defect) = &defect {
for (f, made) in COV_FITS.iter().zip(&fits) {
assert_eq!(made.as_ref().map(|_| ()), Err(defect), "{f} on {stem}");
}
} else if fits.iter().any(Result::is_err) {
if fits.iter().any(Result::is_err) {
for (f, made) in COV_FITS.iter().zip(&fits) {
match made {
Ok(_) => {}
@@ -207,7 +207,7 @@ fn simd_after_discard(bc: &[u8], entry: &str, stem: &str, p: &DeviceProfile) {
/// The `if !discarded` selections of `m`: conditional branches on the negation of a load of a
/// `Private` variable, as the guard of a side effect a predicated site reaches is written.
fn discard_guards(m: &TypedModule) -> usize {
use crate::spirv::ir::{BinOp, StorageClass, UnOp, ValueOrigin};
use crate::spirv::ir::{StorageClass, UnOp, ValueOrigin};
let defs: std::collections::HashMap<_, _> = m
.blocks()
.iter()
@@ -224,16 +224,9 @@ fn discard_guards(m: &TypedModule) -> usize {
let loaded = |v| matches!(defs.get(&v), Some(Inst::Load { ptr, .. }) if private(*ptr));
let not_discarded =
|v| matches!(defs.get(&v), Some(Inst::Unary { op: UnOp::LogicalNot, a }) if loaded(*a));
// Or the predicate and'ed with "not a helper" (`spirv::helper_branches`), which a guard takes
// on MoltenVK where its arm calls a routine SPIRV-Cross writes `optnone` code in.
m.blocks()
.iter()
.filter(|b| {
matches!(&b.term, Terminator::CondBranch { cond, .. }
if not_discarded(*cond)
|| matches!(defs.get(cond), Some(Inst::Binary { op: BinOp::LogicalAnd, a, .. })
if not_discarded(*a)))
})
.filter(|b| matches!(&b.term, Terminator::CondBranch { cond, .. } if not_discarded(*cond)))
.count()
}
@@ -278,17 +271,14 @@ fn predication_guards_the_side_effects_after_a_site() {
/// demote, as no whole-quad exit can be placed on a profile without fragment quad operations. A
/// device that demotes (`moltenvk-m3`, `intel-arl-anv`) demotes each and guards nothing; the
/// simdgroup sum, which counts the helpers Metal runs, is refused needing `shaderQuadControl`
/// where the device lacks it (`moltenvk-m3`), as only full quads give those helpers. No module
/// defers a discard (`fragment.discard.deferred`) or records
/// `PrecisionNote::DiscardDropsSimdgroupStores`. Every module passes L3.
/// where the device lacks it (`moltenvk-m3`), as only full quads give those helpers. Every module
/// passes L3.
#[test]
fn a_predicated_discard_guards_each_later_store_atomic_and_image_write() {
use crate::spirv::ir::ValueOrigin;
let Some(bc) = fixture("rch_guarded_effects") else {
return;
};
let noted = PrecisionNote::DiscardDropsSimdgroupStores;
let deferred = "fragment.discard.deferred";
// (entry, its side effects after the discard)
let cases = [
("rch_guarded_store", 1),
@@ -363,12 +353,6 @@ fn a_predicated_discard_guards_each_later_store_atomic_and_image_write() {
assert!(zero_merged, "{what}: no merge of the atomic's result");
}
let a = compile(&bc, entry, &p).unwrap_or_else(|e| panic!("{what}: {e}"));
assert!(
!a.strategies.entries.contains_key(deferred),
"{what}: {:?}",
a.strategies.entries.keys().collect::<Vec<_>>()
);
assert!(!a.precision.contains(&noted), "{what}: the note");
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
}
}
@@ -5341,93 +5325,6 @@ fn a_blended_extended_range_output_records_its_blend_note() {
assert!(checked > 0, "no interlock profile made the storage form");
}
/// The selection headers of `m` whose condition or selector asks whether the invocation is a
/// helper, as `spirv::helper_branches` writes it: the condition or'ed with
/// `OpIsHelperInvocationEXT`, and'ed with its negation, or a selector chosen by it.
fn helper_guards(m: &TypedModule) -> usize {
use crate::spirv::ir::{BinOp, UnOp};
let defs: std::collections::HashMap<_, _> = m
.blocks()
.iter()
.flat_map(|b| &b.insts)
.filter_map(|n| n.result.map(|r| (r, &n.inst)))
.collect();
let helper = |v| matches!(defs.get(&v), Some(Inst::IsHelperInvocation));
let not_helper =
|v| matches!(defs.get(&v), Some(Inst::Unary { op: UnOp::LogicalNot, a }) if helper(*a));
m.blocks()
.iter()
.filter(|b| match &b.term {
Terminator::CondBranch { cond, .. } => match defs.get(cond) {
Some(Inst::Binary {
op: BinOp::LogicalOr,
b: x,
..
}) => helper(*x),
Some(Inst::Binary {
op: BinOp::LogicalAnd,
b: x,
..
}) => not_helper(*x),
_ => false,
},
Terminator::Switch { sel, .. } => {
matches!(defs.get(sel), Some(Inst::Select { cond, .. }) if helper(*cond))
}
_ => false,
})
.count()
}
/// A selection whose condition every invocation of a draw computes alike (a constant block's flag)
/// holds no branch only helper invocations take, so an `optnone` call in its arm is neither guarded
/// nor noted. The owned fixture `rch_uniform_branch` divides a coordinate by a texture's size and
/// takes the high word of a product (`mulhi`, an `OpUMulExtended`, which SPIRV-Cross writes
/// through its `optnone` `spvMulExtended`) in a branch on a constant block's flag, then samples
/// the texture at the coordinate and writes the sample and the product to a buffer. On
/// `moltenvk-m3` the module holds the product, and no helper census entry, no guard, no
/// `HelperBranchDropsSimdgroupStores`, and L3.
#[test]
fn a_branch_every_invocation_takes_alike_leaves_no_helper_alone() {
use crate::spirv::ir::BinOp;
let Some(bc) = fixture("rch_uniform_branch") else {
return;
};
let p = profile("moltenvk-m3", DevicePolicy::default()).expect("profile");
let noted = PrecisionNote::HelperBranchDropsSimdgroupStores;
let what = "rch_uniform_branch on moltenvk-m3";
let inputs = LoweringInputs::new();
let (_, m) = typed_module_with(&bc, "rch_uniform_branch", &p, &inputs)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let a = compile_with(&bc, "rch_uniform_branch", &p, &inputs)
.unwrap_or_else(|e| panic!("{what}: {e}"));
let helper: Vec<_> = a
.strategies
.entries
.keys()
.filter(|k| k.starts_with("fragment.helper"))
.collect();
let products = m
.blocks()
.iter()
.flat_map(|b| &b.insts)
.filter(|n| {
matches!(
n.inst,
Inst::Binary {
op: BinOp::UMulExtended,
..
}
)
})
.count();
assert_eq!(products, 1, "{what}: the products");
assert!(helper.is_empty(), "{what}: {helper:?}");
assert_eq!(helper_guards(&m), 0, "{what}");
assert!(!a.precision.contains(&noted), "{what}: the note");
link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}"));
}
/// The opcodes of every instruction in `words`, and the capabilities it declares.
fn opcodes_and_capabilities(words: &[u32]) -> (Vec<u32>, Vec<u32>) {
let (mut ops, mut caps) = (Vec::new(), Vec::new());
-6
View File
@@ -2405,12 +2405,6 @@ bound.
steepest, in the conformance suite's extended-range and padded blend cases; and where the
device's compiler regroups a padded format's blend, an infinite second source stores the end code
its sign picks where Metal's sum is NaN, stored as code 0.
- `metal2vulkan-degrade-discard-drops-simdgroup-stores` (precision).
`PrecisionNote::DiscardDropsSimdgroupStores`: Recorded by no device: its condition,
`DriverWorkaround::DiscardDropsSimdgroupStores`, is one no profile takes.
- `metal2vulkan-degrade-helper-branch-drops-simdgroup-stores` (precision).
`PrecisionNote::HelperBranchDropsSimdgroupStores`: Recorded by no device: its condition,
`DriverWorkaround::DiscardDropsSimdgroupStores`, is one no profile takes.
- `metal2vulkan-degrade-extended-range-float-blend-source` (precision).
`PrecisionNote::ExtendedRangeFloatBlendSource`: `PrecisionNote::ExtendedRangeBlendSource` for a
`float` color output (a scalar or vector of AIR's `float`): blended into an extended-range or