Translator: a vertex function under the depth range fold folds the range into its position

Under LoweringInputs::depth_range_fold, a vertex (or post-tessellation
vertex) function that stores its position does three things at each
return:
- it stores the position's z as znear * w + (zfar - znear) * z, reading
  [znear, zfar - znear] from PushField::DepthRangeFold;
- it stores z and w - z, of the z it returned, as two clip distances
  after its own;
- it records PrecisionNote::DeviceArithmetic.

Drawn with the viewport's depths [0, 1] and depth clamping enabled, this
maps a viewport depth range past [0, 1] as Metal maps it (the M3 Max, jobs
m3-max-85541 and m3-max-85617): [[position]].z reads znear + z / w *
(zfar - znear) unclamped; the depth stored and tested is that, clamped to
[0, 1] by the clamp; and the clip distances keep Metal's 0 <= z <= w where
the clamp leaves z unclipped.

Planning:
- The function's own ClipDistance array is declared two longer, with its
  own elements stored as before.
- A function with none declares ClipDistance of 2 (shaderClipDistance).
- Under the fold the declared count must fit maxClipDistances and
  maxCombinedClipAndCullDistances, else Unsupported names
  Feature::ClipDistance and the limit.
- The usual path's check (maxClipDistances alone) is unchanged.
- A function that stores no position, and any other stage, compiles as
  without it.

docs/API.md's DeviceArithmetic entry says the fold records it on every
such compile and why. SEMANTICS_VERSION 2377 and ARTIFACT_FORMAT_VERSION
611 (a new push field and fact). runtime-sources.sha256
takes the translator's new sources, including the commit before's.

Verified: see the twin's READY job lines (the red tests at the commit
before fail, pass here).
This commit is contained in:
Anees Iqbal committed 2026-12-03 16:18:19 -08:00
1 parent 96167b3f8d
commit f7c56cd4d2
5 files changed
+147 -16

No files matched your search

+2 -2
View File
@@ -60,7 +60,7 @@ mod tests;
/// unchanged version, and its bless records the version. Independent of the crate's version and of
/// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no
/// history.
pub const SEMANTICS_VERSION: u32 = 2376;
pub const SEMANTICS_VERSION: u32 = 2377;
/// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the
/// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another
@@ -70,7 +70,7 @@ pub const SEMANTICS_VERSION: u32 = 2376;
/// re-typed in an encoded type, its `codec` body or its `envelope`. A variant removed while its tag
/// stays unused needs no bump: an entry holding it fails to decode, which is a miss. The commit that
/// bumps it says what changed; this comment keeps no history.
pub const ARTIFACT_FORMAT_VERSION: u32 = 610;
pub const ARTIFACT_FORMAT_VERSION: u32 = 611;
/// The version of what this crate gives a runtime for the runs of a compiled pipeline, beside the
/// compile: the device a run opens and what it enables, the Vulkan and Metal vocabularies a runtime
+2 -1
View File
@@ -1779,7 +1779,8 @@ fn identity_pushes(field: PushField, loc: PushLoc, views: bool) -> bool {
| PushField::IndirectRange
| PushField::IndirectSequence
| PushField::IndirectBase => true,
PushField::RootTableAddress
PushField::DepthRangeFold
| PushField::RootTableAddress
| PushField::CaptureIndexAddress
| PushField::MergedDrawAddress
| PushField::AmplificationId
@@ -428,6 +428,12 @@ pub struct StageIoPlan {
/// A fragment function's depth output, which each return gives Metal's answer
/// (`clamp_depth`).
pub depth_clamp: Option<DepthClamp>,
/// A vertex function compiled under `LoweringInputs::depth_range_fold` that stores its
/// position: the fold each return applies to it (`fold_depth_range`).
pub depth_fold: Option<DepthFold>,
/// Under `LoweringInputs::depth_range_fold`, the function's own `ClipDistance` object and
/// how many of its elements the function writes, the fold's two following them.
pub own_clip: Option<(usize, u32)>,
/// The render pipeline's private masks a fragment function applies itself
/// (`LoweringInputs::sample_mask`), which each return ANDs into the function's own
/// `[[sample_mask]]` output or stores as it.
@@ -569,6 +575,17 @@ pub struct DepthClamp {
pub range: bool,
}
/// How a vertex function compiled under `LoweringInputs::depth_range_fold` stores its position
/// (`fold_depth_range`): its `Position` object, whose z each return stores as
/// `znear * w + (zfar - znear) * z` (`PushField::DepthRangeFold`), and its `ClipDistance` object,
/// whose elements `first` and `first + 1` it stores `z` and `w - z` to, of the z it returned.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DepthFold {
pub position: usize,
pub clip: usize,
pub first: u32,
}
impl StageIoPlan {
/// The index of an object equal to `o`, adding it when there is none.
fn object(&mut self, o: IoObject) -> usize {
@@ -1808,6 +1825,7 @@ pub fn emit_return(
let (outputs, returned, point) = (plan.outputs.clone(), plan.returned, plan.point_size_default);
let seconds = plan.rotated_seconds.clone();
let depth_clamp = plan.depth_clamp;
let depth_fold = plan.depth_fold;
let stencil_bits = plan.stencil_bits;
let primitive_id = plan.primitive_id;
// The private masks: the pixel's ANDed into the function's own `[[sample_mask]]` output
@@ -1853,6 +1871,10 @@ pub fn emit_return(
}
None => part,
};
let part = match depth_fold.filter(|f| f.position == o.link.object) {
Some(f) => fold_depth_range(cx, fb, part, f)?,
None => part,
};
let part = match private_mask.filter(|m| m.object == o.link.object) {
Some(m) => {
masked = true;
@@ -2503,6 +2525,44 @@ fn clamp_depth(
fb.select(negative_nan, zero, ranged)
}
/// The position `position` (a `float4`) of a vertex function compiled under
/// `LoweringInputs::depth_range_fold`, its z folded through the draw's viewport depth range
/// (`DepthFold`): `znear * w + (zfar - znear) * z`, `[znear, zfar - znear]` the bits of
/// `PushField::DepthRangeFold`, so a viewport of depths `[0, 1]` maps it to Metal's window z,
/// `znear + z / w * (zfar - znear)`. It stores `z` and `w - z`, of the z the function returned,
/// to the fold's two clip distances, which clip the draw to Metal's `0 <= z <= w` where the
/// consumer's depth clamping leaves z unclipped. The arithmetic is the device's
/// (`PrecisionNote::DeviceArithmetic`).
fn fold_depth_range(
cx: &mut EmitCx<'_>,
fb: &mut FunctionBuilder<'_>,
position: SValue,
fold: DepthFold,
) -> BResult<SValue> {
let f32_ = fb.module().ty(SType::Float { width: 32 })?;
let range = cx.push_field(fb, PushField::DepthRangeFold)?;
let word = |fb: &mut FunctionBuilder<'_>, i: u32| -> BResult<SValue> {
let bits = fb.composite_extract(range, &[i])?;
fb.convert(ConvOp::Bitcast, bits, f32_)
};
let (near, span) = (word(fb, 0)?, word(fb, 1)?);
let z = fb.composite_extract(position, &[2])?;
let w = fb.composite_extract(position, &[3])?;
let at_near = fb.binary(BinOp::FMul, near, w)?;
let across = fb.binary(BinOp::FMul, span, z)?;
let folded = fb.binary(BinOp::FAdd, at_near, across)?;
let g = global(cx, fold.clip)?;
let base = fb.module().global_value(g)?;
let below_w = fb.binary(BinOp::FSub, w, z)?;
for (k, distance) in [(fold.first, z), (fold.first + 1, below_w)] {
let at = fb.u32_const(k)?;
let at = fb.module().const_value(at)?;
let p = fb.access_chain(base, &[at])?;
fb.store(p, distance, MemAccess::default())?;
}
fb.composite_insert(folded, position, &[2])
}
/// A vertex function's index `index` (an integer held zero-extended in its 32-bit container)
/// where it is below the `u32` count push field `count`, and 0 where it is not:
///
+77 -12
View File
@@ -126,6 +126,67 @@ fn needs(f: Feature, v: VkFeature) -> Error {
Unsupported::needs(f, Capability::Feature(v)).into()
}
/// `declared` clip distances fit the device: at most `maxClipDistances`, and, where the depth
/// range `fold` adds two of its own, at most `maxCombinedClipAndCullDistances` too (no Metal
/// function writes a cull distance).
fn clip_distances_fit(cx: &SelectCx<'_>, declared: u32, fold: bool) -> Result<(), Error> {
let limits = cx.profile.fields().limits;
let mut bounds = vec![(VkLimit::MaxClipDistances, limits.max_clip_distances)];
if fold {
bounds.push((
VkLimit::MaxCombinedClipAndCullDistances,
limits.max_combined_clip_and_cull_distances,
));
}
match bounds.into_iter().find(|&(_, bound)| declared > bound) {
Some((past, bound)) => Err(limit(
Feature::ClipDistance,
past,
u64::from(declared),
bound,
)),
None => Ok(()),
}
}
/// The depth range fold of a vertex function compiled under `LoweringInputs::depth_range_fold`
/// that stores its position (`DepthFold`): its two clip distances follow its own, or are the
/// whole of a `ClipDistance` it declares for them, and it reads `PushField::DepthRangeFold`. A
/// function that stores no position has nothing to fold.
fn depth_range_fold(cx: &mut SelectCx<'_>) -> Result<(), Error> {
let Some(position) = cx.families.stage_io.invariant else {
return Ok(());
};
let (clip, first) = match cx.families.stage_io.own_clip {
Some(own) => own,
None => {
if !cx.profile.fields().fragment.clip_distance {
return Err(needs(Feature::ClipDistance, VkFeature::ShaderClipDistance));
}
clip_distances_fit(cx, 2, true)?;
let object = builtin(
&mut cx.families.stage_io,
B::ClipDistance,
IoDir::Output,
Shape::F32Array(2),
StageBuiltin::ClipDistance { count: 2 },
);
(object, 0)
}
};
cx.facts.insert(RuntimeFact::DepthRangeFold);
cx.push.insert(PushField::DepthRangeFold);
// The fold's z is the device's arithmetic, not Metal's viewport transform's rounding: on
// every function compiled under it, whatever the range.
cx.precision.insert(PrecisionNote::DeviceArithmetic);
cx.families.stage_io.depth_fold = Some(super::DepthFold {
position,
clip,
first,
});
Ok(())
}
fn limit(f: Feature, limit: VkLimit, required: u64, available: u32) -> Error {
Unsupported::needs(
f,
@@ -2335,6 +2396,9 @@ pub fn entry(cx: &mut SelectCx<'_>) -> Result<(), Error> {
if cx.inputs.region_viewports && cx.stage == Stage::Vertex {
region_viewport(cx, &outputs, returned)?;
}
if cx.inputs.depth_range_fold && cx.stage == Stage::Vertex {
depth_range_fold(cx)?;
}
// The primitive ID a fragment function reads from its varying.
if cx.inputs.primitive_id_varying && cx.stage == Stage::Vertex {
primitive_id_output(cx)?;
@@ -2684,24 +2748,25 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result<Lin
if array_size.is_some_and(|a| a != count) || count == 0 {
return Err(cx.invariant("a clip distance array of another size"));
}
if count > limits.max_clip_distances {
return Err(limit(
Feature::ClipDistance,
VkLimit::MaxClipDistances,
u64::from(count),
limits.max_clip_distances,
));
}
// Under the depth range fold, two more follow the function's own
// (`depth_range_fold`).
let fold = cx.inputs.depth_range_fold;
let declared = count + if fold { 2 } else { 0 };
clip_distances_fit(cx, declared, fold)?;
let f = io_form(cx, elem)?;
float_lanes(f, 1)?;
out(
let link = out(
cx,
B::ClipDistance,
Shape::F32Array(count),
Shape::F32Array(declared),
place,
f,
StageBuiltin::ClipDistance { count },
)
StageBuiltin::ClipDistance { count: declared },
);
if fold {
cx.families.stage_io.own_clip = Some((link.object, count));
}
link
}
OutputRole::RenderTargetArrayIndex | OutputRole::ViewportArrayIndex if vertex => {
let (index, spirv, contract) = match o.role {
+6 -1
View File
@@ -1848,7 +1848,12 @@ category, and says what makes an operation carry the note and what may differ. E
constexpr sampler clamped to the edge fetches its texel.
- `metal2vulkan-degrade-device-arithmetic` (precision). `PrecisionNote::DeviceArithmetic`: Float
division, remainder, square root, fused multiply-add, and dot products use Vulkan's precision
bounds (e.g. 2.5 ULP division, a possibly unfused `Fma`) rather than correct rounding.
bounds (e.g. 2.5 ULP division, a possibly unfused `Fma`) rather than correct rounding. A
vertex function compiled under `LoweringInputs::depth_range_fold` records it on every such
compile, whatever the range: its position's z is `znear * w + (zfar - znear) * z`, which the
device then divides by `w`, where Metal's viewport transform computes
`znear + z / w * (zfar - znear)`; the two round differently, so the depth a draw of it stores,
tests and reads in `[[position]].z` can differ from Metal's in its last bits.
- `metal2vulkan-degrade-device-signed-zero-inf-nan` (precision).
`PrecisionNote::DeviceSignedZeroInfNan`: Float operations LLVM requires to keep signed zeros,
infinities, and NaNs run without `SignedZeroInfNanPreserve`, which the device does not support at