Leave NaN bits and min/max picks to the device
One work packet, landed as 6 commits (a6e97e7f93..3919c8c94a on archive/development-linear-2026-10-28), in order: * Leave NaN bits and min/max picks to the device On the owner's ruling to promise the GPU's native arithmetic with no exact emulation, delete the NaN and minimum/maximum switch and every form that only it, or Metal's NaN bits, kept. What goes: - DevicePolicy::nan_and_min_max and NanMinMaxPolicy (exact_answers line, serde, ExactFormsOverCompilerLimit::nan_and_min_max, the fit leg). - The module's selects of Metal's NaN: NanEncoding::Device, ArithStrategy::Nan and lower/arith/nan.rs down to its answer classes. A NaN Metal answers that the device is not measured to answer records NativeNanEncoding. - Metal's operand pick in fmin, fmax, min3, max3, clamp and saturate (metal_min_max, metal_saturate, MinMaxRoute): NMin, NMax and NClamp on every profile, NativeMinMax where MetalMinMax is not taken. - Metal's texel NaN rule (TexelNanRoute, the 0x7e00 keeps, the half texel NaN keep, the NaN classes of reads, samples and gathers). - NaN canonicalization before colour and storage writes: StorageImageClass::HalfQuietNan and SmallFloatQuietNan, the half write NaN classes (HalfNans), the quieted heap small floats, the colour lanes that chose 0x7fc00000, the 16-bit colour outputs (StageIo and StageModule half_bit_colors, IoType::bits, Degradation:: ShaderHalfColorBits), PushField::TextureHalfChannels, RuntimeFact::StorageTextureHalfChannels and the slot word behind it. Such writes record DeviceNanEncoding where the stored NaN may not be Metal's (heap and formatless writes, 32-bit and packed float channels). - The narrow-float vertex fetch's canonical NaN: noted instead. - The runtime's colour NaN clears (nan_clear::NanClears and its texel computation, the inline-first NaN clear refusal, WorkCounts:: passes_not_inline_actions_nan_clear): the device's clear, announced as DeviceNanEncoding. The depth NaN clear and the bit-exact copies stay. - FAST-PATHS rows for the switch, the half texel keep and the half from bits under float controls; the known gap of RADV's sampler NaN; the API.md passages and catalogue entries. Kept: the notes that describe the native answer (NativeNanEncoding, NativeMinMax, DeviceNanEncoding), the measured deviations they read, the copy and depth paths, keeps_nan_sign, the heap half-bits twin, the half rounding and the blended snorm NaN of other lanes. Versions: SEMANTICS_VERSION 1871, ARTIFACT_FORMAT_VERSION 454, RUNTIME_VERSION 1652. docs/REFUSALS.md regenerated. Verified: cargo clippy --workspace --all-targets --all-features -D warnings, plain and with --cfg m2v_gpu; RUSTDOCFLAGS='-D warnings' cargo doc --workspace --all-features --no-deps; nextest of metal2vulkan filtered to the touched modules, fast_paths, catalogue, degradation, api_surface and profile (see the report for counts), and of the runtime, validation and conformance unit tests touched. No device test was run. * Re-bless the API signatures after the NaN and min/max deletion The table loses the public items the previous commit removed: NanMinMaxPolicy and its variants, DevicePolicy::nan_and_min_max, ExactFormsOverCompilerLimit::nan_and_min_max, PushField:: TextureHalfChannels, RuntimeFact::StorageTextureHalfChannels, StorageImageClass::HalfQuietNan and SmallFloatQuietNan, StageModule::half_bit_colors, Degradation::ShaderHalfColorBits and WorkCounts::passes_not_inline_actions_nan_clear. Verified: python3 scripts/api-signatures/signatures.py --bless; nextest of the api_signatures, api_surface, refusal_surface and feature_vocabulary binaries (21 passed); the previous commit's filtered metal2vulkan run, 1056 passed, plus runtime (53), validation (83 of 84; the failing c3 venue-identity test names the Apple M4 and touches no file of this change) and conformance (38) filtered runs. * Fix the tests the rebase onto development left broken The rebase of the NaN and min/max deletion onto development left two test compile errors: the extended-range samples still round through `half_toward_zero`, which the resolution had dropped with the storage-slot test that used it, and the RGBX storage cases named `HalfQuietNan`, which both sides' deletions removed (a half-float twin is `Identity` now). Verified: cargo clippy --workspace --all-targets --all-features -D warnings, plain and with --cfg m2v_gpu; RUSTDOCFLAGS='-D warnings' cargo doc. * Drop a dead dot form and let formatless half slots note conversion twice select_float_fn still computed dot's scalar result form, which only the removed NaN canonicalization read. The half-float storage test asserted that a formatless slot notes DeviceColorConversion exactly when the profile does not round Metal's way; a formatless slot may also reach a normalized image, whose conversion is the device's on every profile, so the note is only required one way there. Verified: cargo check --workspace --all-targets --all-features is clean. * Leave the fast division's NaN to the device in its test The float-maths lane's a_fast_division_answers_metals_nans_on_every_profile asserted Metal's canonical NaN after the device's OpFDiv where the profile does not take MetalCanonicalNans. Under the native-arithmetic ruling the module selects no NaN: the fast division is the device's OpFDiv on every profile, noted NativeNanEncoding where the device is not measured to answer Metal's. The test, now a_fast_division_leaves_its_nans_to_the_device, checks that the module is the same on both sides of the fact, the note where the fact is absent, the device's arithmetic, division and denormal notes on every committed profile, never DeviceNanEncoding, a NaN for each NaN case and 6 / 3 exactly. Verified: cargo nextest -E 'test(/engine_arith::a_fast_division/)' passes (2 tests); the previous form failed on amd-780m-hawkpoint-radv for fast_one_by_negative_nan (0xffc00000, the device's). * Re-pin the runtime sources at the landing tip The landed packet changed a runtime-sources input, so the committed digest no longer described the sources and `the_runtime_sources_are_the_committed_ones` would fail. Recomputed over the same inputs and committed by land-pkt.sh.
This commit is contained in:
1 parent
2a14a4a363
commit
79166a74b1
123 files changed
+1409
-5787
No files matched your search
@@ -453,12 +453,6 @@ impl Case for HalfOutputBlends {
|
||||
// written from it would be the suite overruling the contract it exists to test. Five of the
|
||||
// six formats are therefore left **divergent** on this round's MoltenVK, with the measured
|
||||
// counts in the module docs above.
|
||||
// A half-float attachment also takes the stage's `half` through a 16-bit output on a
|
||||
// device that does not store a 32-bit output's NaN as Metal does, announced as
|
||||
// `shader-half-color-bits` on the three 16-bit formats of this family. It is the case's own
|
||||
// shape again -- a stored `half` output into a half-float attachment -- so its code is
|
||||
// declared, and it loosens no stored code either: the three rows stay divergent on the
|
||||
// texels the module docs above measure, which is the finding and must not be laundered.
|
||||
//
|
||||
// Two more of the same shape are declared from the run that shows them: a device whose own
|
||||
// conversion into the attachment is not Metal's (`device-color-conversion`, lavapipe) and
|
||||
@@ -482,7 +476,6 @@ impl Case for HalfOutputBlends {
|
||||
.chain(
|
||||
[
|
||||
Degradation::HalfOutputFastMathBlend,
|
||||
Degradation::ShaderHalfColorBits,
|
||||
Degradation::DeviceColorConversion,
|
||||
Degradation::DeviceNanEncoding,
|
||||
]
|
||||
|
||||
@@ -1675,10 +1675,6 @@ impl Gpu for Runtime {
|
||||
"passes_not_inline_actions_unequal_reach",
|
||||
c.passes_not_inline_actions_unequal_reach,
|
||||
),
|
||||
(
|
||||
"passes_not_inline_actions_nan_clear",
|
||||
c.passes_not_inline_actions_nan_clear,
|
||||
),
|
||||
(
|
||||
"passes_not_inline_actions_resolve",
|
||||
c.passes_not_inline_actions_resolve,
|
||||
|
||||
@@ -34,8 +34,8 @@
|
||||
//! lies a hair below `k` for some `k` (1/65535 stored 0 there). A NaN of a `half` or small-float
|
||||
//! channel has no such value: Vulkan leaves its bits to the device, and RADV and lavapipe write
|
||||
//! other NaNs than Metal's canonical quiet one (a Metal probe, the M3 Max and an M4 alike:
|
||||
//! `0x7e00`, and `0x7e0` and `0x3f0` for `RG11B10Float`, the sign dropped). [`nan_texel`] gives
|
||||
//! such a texel's bits, which `nan_clear.rs` writes before the pass. A `float` NaN keeps its sign
|
||||
//! `0x7e00`, and `0x7e0` and `0x3f0` for `RG11B10Float`, the sign dropped): the device's clear
|
||||
//! writes its own, announced (`nan_clear::degrade_nan_clears`). A `float` NaN keeps its sign
|
||||
//! (`0x7fc00000`, `0xffc00000`), which every device measured writes.
|
||||
//!
|
||||
//! An **extended-range** attachment holds its raw texels in an unsigned integer format, so its
|
||||
@@ -308,133 +308,25 @@ pub(super) fn word(
|
||||
})
|
||||
}
|
||||
|
||||
/// Where a `half` or small-float channel of `value`, the Vulkan clear value [`color`] gives an
|
||||
/// attachment of `pf`, is a NaN, whose bits Vulkan leaves to the device's conversion
|
||||
/// (`nan_clear.rs`): the unsigned-integer format of the texel's size and the clear value that
|
||||
/// writes Metal's texel there, its bits from the texel's first byte. `None` for every other
|
||||
/// clear, which converts exactly.
|
||||
/// A `half` NaN is the canonical quiet NaN, `0x7e00`, where not `signed`; where `signed` (a
|
||||
/// level Metal clears keeping them, `nan_clear::keeps_nan_sign`) it keeps the clear value's sign
|
||||
/// and the top ten bits of its payload, quieted: `sign | 0x7e00 | payload`, the double's
|
||||
/// mantissa's top ten bits (`0x7ffc...` stores `0x7f00`, `0x7fff...` `0x7fff`,
|
||||
/// `0xffff...` `0xffff`, the signalling `0x7ff4...` `0x7f00`, `0x7ff0...01` `0x7e00`).
|
||||
pub(super) fn nan_texel(
|
||||
pf: PixelFormat,
|
||||
value: &vk::ClearColorValue,
|
||||
signed: bool,
|
||||
) -> Option<(Format, vk::ClearColorValue)> {
|
||||
let nan = match signed {
|
||||
true => NanBits::Signed,
|
||||
false => NanBits::Signless,
|
||||
};
|
||||
small_float_texel(pf, value, nan)
|
||||
}
|
||||
|
||||
/// The texel Metal's resolve stores from samples that each hold [`nan_texel`]'s texel of
|
||||
/// `value`, where it averages them: each NaN channel zero, as its resolve counts a NaN sample, in
|
||||
/// the unsigned-integer format of the texel's size. `None` where `value` holds no `half` or
|
||||
/// small-float NaN.
|
||||
pub(super) fn resolved_nan_texel(
|
||||
pf: PixelFormat,
|
||||
value: &vk::ClearColorValue,
|
||||
) -> Option<(Format, vk::ClearColorValue)> {
|
||||
small_float_texel(pf, value, NanBits::Zero)
|
||||
}
|
||||
|
||||
/// Where a channel of `value`, the Vulkan clear value [`color`] gives an attachment of `pf` whose
|
||||
/// channels are 32-bit floats, is a NaN: the unsigned-integer format of the texel's size and the
|
||||
/// clear value that writes, where `kept`, the texel's bits, which the device's clear writes too (a
|
||||
/// `float` converts nothing), else the texel Metal's resolve stores from samples that each hold
|
||||
/// it, each NaN channel `0x7fc00000`; for a write of the texel elsewhere (`nan_clear.rs`'s
|
||||
/// resolves). `None` for another format or a clear without a NaN.
|
||||
pub(super) fn float_nan_texel(
|
||||
pf: PixelFormat,
|
||||
value: &vk::ClearColorValue,
|
||||
kept: bool,
|
||||
) -> Option<(Format, vk::ClearColorValue)> {
|
||||
/// Whether a float channel of `value`, the Vulkan clear value [`color`] gives an attachment of
|
||||
/// `pf`, is a NaN: `Some(true)` where a `half` or small-float one is, whose bits Vulkan leaves to
|
||||
/// the device's conversion (`nan_clear::degrade_nan_clears`), `Some(false)` where only a 32-bit
|
||||
/// float one is, which converts nothing. `None` for every other clear.
|
||||
pub(super) fn nan_channels(pf: PixelFormat, value: &vk::ClearColorValue) -> Option<bool> {
|
||||
let channels = channels(pf)?;
|
||||
// SAFETY: every member of the union is four 32-bit values; any bits are a valid `f32`.
|
||||
let float32 = unsafe { value.float32 };
|
||||
let used: Vec<f32> = channels
|
||||
.iter()
|
||||
.zip(float32)
|
||||
.filter(|(c, _)| !matches!(c, Channel::Unused))
|
||||
.map(|(c, v)| matches!(c, Channel::Float).then_some(v))
|
||||
.collect::<Option<_>>()?;
|
||||
if !used.iter().any(|v| v.is_nan()) {
|
||||
return None;
|
||||
}
|
||||
let bits = |v: &f32| match v.is_nan() && !kept {
|
||||
true => 0x7fc0_0000,
|
||||
false => v.to_bits(),
|
||||
};
|
||||
let bytes: Vec<u8> = used.iter().flat_map(|v| bits(v).to_le_bytes()).collect();
|
||||
uint_texel(&bytes)
|
||||
}
|
||||
|
||||
/// What a NaN channel of a [`small_float_texel`] holds.
|
||||
#[derive(Clone, Copy)]
|
||||
enum NanBits {
|
||||
/// The canonical quiet NaN, without a sign.
|
||||
Signless,
|
||||
/// The canonical quiet NaN with the clear value's sign, in a `half` channel.
|
||||
Signed,
|
||||
/// Zero.
|
||||
Zero,
|
||||
}
|
||||
|
||||
/// The texel of `value` in `pf`, a format of `half` or small-float channels, each NaN channel as
|
||||
/// `nan` says ([`nan_texel`]); `None` where no such channel is a NaN.
|
||||
fn small_float_texel(
|
||||
pf: PixelFormat,
|
||||
value: &vk::ClearColorValue,
|
||||
nan: NanBits,
|
||||
) -> Option<(Format, vk::ClearColorValue)> {
|
||||
let channels = channels(pf)?;
|
||||
// SAFETY: every member of the union is four 32-bit values; any bits are a valid `f32`.
|
||||
let float32 = unsafe { value.float32 };
|
||||
let small_float = |c: &Channel| matches!(c, Channel::Half | Channel::Ufloat(_));
|
||||
if !channels
|
||||
.iter()
|
||||
.zip(float32)
|
||||
.any(|(c, v)| small_float(c) && v.is_nan())
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let mut bits = 0u64;
|
||||
let mut at = 0;
|
||||
for (&channel, v) in channels.iter().zip(float32) {
|
||||
let (field, width) = match (channel, nan) {
|
||||
(Channel::Half, NanBits::Zero) if v.is_nan() => (0, 16),
|
||||
(Channel::Ufloat(mantissa), NanBits::Zero) if v.is_nan() => (0, mantissa + 5),
|
||||
// The sign and the top ten payload bits, quieted ([`convert`] carries the clear
|
||||
// value's in the `float`).
|
||||
(Channel::Half, NanBits::Signed) if v.is_nan() => {
|
||||
let bits = v.to_bits();
|
||||
let kept = ((bits >> 16) & 0x8000) | 0x7e00 | ((bits >> 13) & 0x3ff);
|
||||
(u64::from(kept), 16)
|
||||
}
|
||||
(Channel::Half, _) => (u64::from(f32_to_f16(v)), 16),
|
||||
(Channel::Ufloat(mantissa), _) => (ufloat_bits(v, mantissa), mantissa + 5),
|
||||
(Channel::Unused, _) => continue,
|
||||
// No format mixes small floats with other channels.
|
||||
_ => return None,
|
||||
};
|
||||
bits |= field << at;
|
||||
at += width;
|
||||
}
|
||||
if at % 8 != 0 {
|
||||
return None;
|
||||
}
|
||||
let bytes = bits.to_le_bytes();
|
||||
uint_texel(bytes.get(..at as usize / 8)?)
|
||||
let nans = || channels.iter().zip(float32).filter(|(_, v)| v.is_nan());
|
||||
let narrow = nans().any(|(c, _)| matches!(c, Channel::Half | Channel::Ufloat(_)));
|
||||
let float = nans().any(|(c, _)| matches!(c, Channel::Float));
|
||||
(narrow || float).then_some(narrow)
|
||||
}
|
||||
|
||||
/// The unsigned-integer format of `texel`'s size (2, 4, 8 or 16 bytes: `R16_UINT`, `R32_UINT`,
|
||||
/// `R32G32_UINT`, `R32G32B32A32_UINT`) and the clear value whose conversion into it writes
|
||||
/// exactly `texel`'s bytes, its little-endian 16- or 32-bit words: a texel whose bits no clear
|
||||
/// of its own format controls is written so, then copied bit-wise into an image of its format
|
||||
/// (`nan_clear.rs`, a new multisampled texture's pattern: `first_move::Pattern::Scratch`).
|
||||
/// (a new multisampled texture's pattern: `first_move::Pattern::Scratch`).
|
||||
/// `None` for another size.
|
||||
pub(crate) fn uint_texel(texel: &[u8]) -> Option<(Format, vk::ClearColorValue)> {
|
||||
let format = match texel.len() {
|
||||
@@ -456,29 +348,6 @@ pub(crate) fn uint_texel(texel: &[u8]) -> Option<(Format, vk::ClearColorValue)>
|
||||
Some((format, vk::ClearColorValue { uint32 }))
|
||||
}
|
||||
|
||||
/// The bits of a small unsigned float of `mantissa` bits (and a 5-bit exponent) holding `v`, which
|
||||
/// is one exactly ([`ufloat_value`]'s result): NaN is the canonical quiet NaN (the top mantissa
|
||||
/// bit), as Metal writes it (a Metal probe on the M3 Max and an M4).
|
||||
fn ufloat_bits(v: f32, mantissa: u32) -> u64 {
|
||||
if v.is_nan() {
|
||||
return (31 << mantissa) | (1 << (mantissa - 1));
|
||||
}
|
||||
if v.is_infinite() {
|
||||
return 31 << mantissa;
|
||||
}
|
||||
if v <= 0.0 {
|
||||
return 0;
|
||||
}
|
||||
let steps = 1u64 << mantissa;
|
||||
let exponent = binade(v).max(-14);
|
||||
// Exact: `v` is a whole number of the binade's spacing.
|
||||
let scaled = (f64::from(v) / 2f64.powi(exponent) * steps as f64) as u64;
|
||||
match scaled < steps {
|
||||
true => scaled,
|
||||
false => (((exponent + 15) as u64) << mantissa) | (scaled - steps),
|
||||
}
|
||||
}
|
||||
|
||||
/// Each channel's texel under Metal's conversion of `color`.
|
||||
fn convert(channels: &[Channel; 4], color: [f64; 4]) -> [Texel; 4] {
|
||||
let shared = shared_exponent(channels, color);
|
||||
@@ -493,7 +362,8 @@ fn convert(channels: &[Channel; 4], color: [f64; 4]) -> [Texel; 4] {
|
||||
Channel::Uint(bits) => Texel::Uint(uint(x, bits)),
|
||||
Channel::Sint(bits) => Texel::Sint(sint(x, bits)),
|
||||
// A NaN is the quiet `float` NaN of the double's sign and top payload bits, which
|
||||
// `nan_texel` keeps where Metal's clear does; every other value is the `half`'s.
|
||||
// Metal's clear keeps where it keeps a `half` NaN's sign; every other value is the
|
||||
// `half`'s.
|
||||
Channel::Half if x.is_nan() => {
|
||||
let bits = x.to_bits();
|
||||
let sign = ((bits >> 32) & 0x8000_0000) as u32;
|
||||
@@ -724,6 +594,29 @@ pub(crate) mod tests {
|
||||
use super::*;
|
||||
use PixelFormat as P;
|
||||
|
||||
/// The bits of a small unsigned float of `mantissa` bits (and a 5-bit exponent) holding `v`,
|
||||
/// which is one exactly ([`ufloat_value`]'s result): NaN is the canonical quiet NaN (the top
|
||||
/// mantissa bit), as Metal writes it (a Metal probe on the M3 Max and an M4).
|
||||
fn ufloat_bits(v: f32, mantissa: u32) -> u64 {
|
||||
if v.is_nan() {
|
||||
return (31 << mantissa) | (1 << (mantissa - 1));
|
||||
}
|
||||
if v.is_infinite() {
|
||||
return 31 << mantissa;
|
||||
}
|
||||
if v <= 0.0 {
|
||||
return 0;
|
||||
}
|
||||
let steps = 1u64 << mantissa;
|
||||
let exponent = binade(v).max(-14);
|
||||
// Exact: `v` is a whole number of the binade's spacing.
|
||||
let scaled = (f64::from(v) / 2f64.powi(exponent) * steps as f64) as u64;
|
||||
match scaled < steps {
|
||||
true => scaled,
|
||||
false => (((exponent + 15) as u64) << mantissa) | (scaled - steps),
|
||||
}
|
||||
}
|
||||
|
||||
/// The bytes of the texel a clear of `color` writes into an attachment of `pf`: each channel
|
||||
/// converted as [`convert`] converts it, laid out as Metal lays out `pf`'s texel,
|
||||
/// little-endian, the fields from the texel's lowest bit in the order the format's name lists
|
||||
@@ -1062,263 +955,6 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A clear of a `half` or small-float NaN writes Metal's texel through an integer format of its
|
||||
/// size (the bytes Metal wrote on the M3 Max and an M4), and no other clear does.
|
||||
#[test]
|
||||
fn nan_texels_are_metals() {
|
||||
let n = f64::NAN;
|
||||
let cases: &[(PixelFormat, [f64; 4], Format, &str)] = &[
|
||||
(P::R16Float, [n, 0.0, 0.0, 0.0], Format::R16_UINT, "007e"),
|
||||
(P::R16Float, [-n, 0.0, 0.0, 0.0], Format::R16_UINT, "007e"),
|
||||
(P::RG16Float, [n, 1.0, 0.5, n], Format::R32_UINT, "007e003c"),
|
||||
(
|
||||
P::RG16Float,
|
||||
[1.0, n, 2.0, 0.25],
|
||||
Format::R32_UINT,
|
||||
"003c007e",
|
||||
),
|
||||
(
|
||||
P::RGBA16Float,
|
||||
[-n, -n, -n, -n],
|
||||
Format::R32G32_UINT,
|
||||
"007e007e007e007e",
|
||||
),
|
||||
(
|
||||
P::RGBA16Float,
|
||||
[n, 1.0, 0.5, n],
|
||||
Format::R32G32_UINT,
|
||||
"007e003c0038007e",
|
||||
),
|
||||
(
|
||||
P::RGBA16Float,
|
||||
[1.0, n, 2.0, 0.25],
|
||||
Format::R32G32_UINT,
|
||||
"003c007e00400034",
|
||||
),
|
||||
(P::RG11B10Float, [n, n, n, n], Format::R32_UINT, "e0073ffc"),
|
||||
(
|
||||
P::RG11B10Float,
|
||||
[-n, -n, -n, -n],
|
||||
Format::R32_UINT,
|
||||
"e0073ffc",
|
||||
),
|
||||
(
|
||||
P::RG11B10Float,
|
||||
[n, 1.0, 0.5, n],
|
||||
Format::R32_UINT,
|
||||
"e0071e70",
|
||||
),
|
||||
(
|
||||
P::RG11B10Float,
|
||||
[1.0, n, 2.0, 0.25],
|
||||
Format::R32_UINT,
|
||||
"c0033f80",
|
||||
),
|
||||
(
|
||||
P::RG11B10Float,
|
||||
[1e-6, n, f64::INFINITY, 0.0],
|
||||
Format::R32_UINT,
|
||||
"01003ff8",
|
||||
),
|
||||
];
|
||||
for &(pf, c, format, want) in cases {
|
||||
let value = color(pf, c, ClearRoute::ThroughHalf).unwrap();
|
||||
let (got, bits) = nan_texel(pf, &value, false).unwrap();
|
||||
// SAFETY: `nan_texel` writes `uint32`.
|
||||
let words = unsafe { bits.uint32 };
|
||||
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
assert_eq!(got, format, "{pf:?} {c:?}");
|
||||
assert_eq!(hex(&bytes[..want.len() / 2]), want, "{pf:?} {c:?}");
|
||||
assert!(bytes[want.len() / 2..].iter().all(|&b| b == 0), "{pf:?}");
|
||||
}
|
||||
for (pf, c) in [
|
||||
(P::RGBA16Float, [0.1, -2.5, 65504.0, 1e-5]),
|
||||
(P::RG11B10Float, [0.1, -1.0, 70000.0, 0.0]),
|
||||
(P::R32Float, [n, 0.0, 0.0, 0.0]),
|
||||
(P::RGBA32Float, [-n, n, 1.0, 0.0]),
|
||||
(P::RGB9E5Float, [n, 1.0, 0.5, n]),
|
||||
(P::RGBA8Unorm, [n, n, n, n]),
|
||||
(P::B5G6R5Unorm, [n, n, n, n]),
|
||||
] {
|
||||
assert!(
|
||||
nan_texel(pf, &color(pf, c, ClearRoute::ThroughHalf).unwrap(), false).is_none(),
|
||||
"{pf:?}"
|
||||
);
|
||||
assert!(
|
||||
nan_texel(pf, &color(pf, c, ClearRoute::ThroughHalf).unwrap(), true).is_none(),
|
||||
"{pf:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Where Metal keeps a NaN clear's sign (a level of 16 or more texels a side), a `half` NaN is
|
||||
/// `0x7e00` with the clear value's sign; the small floats, which have none, and every finite
|
||||
/// channel are as without it.
|
||||
#[test]
|
||||
fn signed_nan_texels_keep_the_sign_of_a_half_nan() {
|
||||
let n = f64::NAN;
|
||||
let cases: &[(PixelFormat, [f64; 4], &str)] = &[
|
||||
(P::RGBA16Float, [-n, -n, -n, -n], "00fe00fe00fe00fe"),
|
||||
(P::RGBA16Float, [n, 1.0, 0.5, -n], "007e003c003800fe"),
|
||||
(P::RGBA16Float, [n, 1.0, 0.5, n], "007e003c0038007e"),
|
||||
(P::R16Float, [-n, 0.0, 0.0, 0.0], "00fe"),
|
||||
(P::RG16Float, [-n, -2.5, 0.0, 0.0], "00fe00c1"),
|
||||
(P::RG11B10Float, [-n, -n, -n, -n], "e0073ffc"),
|
||||
];
|
||||
for &(pf, c, want) in cases {
|
||||
let (_, bits) =
|
||||
nan_texel(pf, &color(pf, c, ClearRoute::ThroughHalf).unwrap(), true).unwrap();
|
||||
// SAFETY: `nan_texel` writes `uint32`.
|
||||
let words = unsafe { bits.uint32 };
|
||||
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
assert_eq!(hex(&bytes[..want.len() / 2]), want, "{pf:?} {c:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Metal's resolve of samples each holding a NaN clear's texel stores each NaN channel zero
|
||||
/// and every other channel as the texel holds it (an M4: `RGBA16Float` (NaN, 1, 0.5, -NaN)
|
||||
/// resolves to `0000 3c00 3800 0000`; `RG11B10Float` (NaN, 1, 0.5) to `701e0000`); a clear
|
||||
/// without such a NaN has none.
|
||||
#[test]
|
||||
fn resolved_nan_texels_zero_each_nan_channel() {
|
||||
let n = f64::NAN;
|
||||
let cases: &[(PixelFormat, [f64; 4], &str)] = &[
|
||||
(P::RGBA16Float, [n, 1.0, 0.5, -n], "0000003c00380000"),
|
||||
(P::RGBA16Float, [-n, -n, -n, -n], "0000000000000000"),
|
||||
(P::R16Float, [-n, 0.0, 0.0, 0.0], "0000"),
|
||||
(P::RG16Float, [-n, f64::INFINITY, 0.0, 0.0], "0000007c"),
|
||||
(P::RG11B10Float, [n, 1.0, 0.5, n], "00001e70"),
|
||||
(P::RG11B10Float, [n, n, n, n], "00000000"),
|
||||
];
|
||||
for &(pf, c, want) in cases {
|
||||
let value = color(pf, c, ClearRoute::ThroughHalf).unwrap();
|
||||
let (format, bits) = resolved_nan_texel(pf, &value).unwrap();
|
||||
assert_eq!(format, nan_texel(pf, &value, false).unwrap().0, "{pf:?}");
|
||||
// SAFETY: `resolved_nan_texel` writes `uint32`.
|
||||
let words = unsafe { bits.uint32 };
|
||||
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
assert_eq!(hex(&bytes[..want.len() / 2]), want, "{pf:?} {c:?}");
|
||||
}
|
||||
let finite = color(
|
||||
P::RGBA16Float,
|
||||
[0.1, 1.0, 0.5, 1.0],
|
||||
ClearRoute::ThroughHalf,
|
||||
);
|
||||
assert!(resolved_nan_texel(P::RGBA16Float, &finite.unwrap()).is_none());
|
||||
}
|
||||
|
||||
/// A 32-bit float NaN clears to the double's sign and top payload bits, quieted, as Metal's
|
||||
/// conversion (`0x7ff0000020000000` stores `0x7fc00001`, `0xfff8...`
|
||||
/// `0xffc00000`, `0x7ffc...` `0x7fe00000`, the signalling `0x7ff0...01` `0x7fc00000`), and
|
||||
/// `float_nan_texel` gives those bits where kept, and each NaN channel `0x7fc00000` where
|
||||
/// not, Metal's resolve of them (its other channels as they are); a clear without a NaN, or of
|
||||
/// another format, none.
|
||||
#[test]
|
||||
fn float_nan_texels_are_metal_s_conversion() {
|
||||
let nan = f64::from_bits;
|
||||
// The clear, its kept texel and its resolved one.
|
||||
let cases: &[(PixelFormat, [f64; 4], &str, &str)] = &[
|
||||
(
|
||||
P::R32Float,
|
||||
[nan(0x7ff0_0000_2000_0000), 0.0, 0.0, 0.0],
|
||||
"0100c07f",
|
||||
"0000c07f",
|
||||
),
|
||||
(
|
||||
P::R32Float,
|
||||
[nan(0xfff8_0000_0000_0000), 0.0, 0.0, 0.0],
|
||||
"0000c0ff",
|
||||
"0000c07f",
|
||||
),
|
||||
(
|
||||
P::R32Float,
|
||||
[nan(0x7ffc_0000_0000_0000), 0.0, 0.0, 0.0],
|
||||
"0000e07f",
|
||||
"0000c07f",
|
||||
),
|
||||
(
|
||||
P::R32Float,
|
||||
[nan(0x7ff0_0000_0000_0001), 0.0, 0.0, 0.0],
|
||||
"0000c07f",
|
||||
"0000c07f",
|
||||
),
|
||||
(
|
||||
P::RG32Float,
|
||||
[nan(0x7ff8_0000_0000_0000), 1.0, 0.0, 0.0],
|
||||
"0000c07f0000803f",
|
||||
"0000c07f0000803f",
|
||||
),
|
||||
(
|
||||
P::RGBA32Float,
|
||||
[
|
||||
0.5,
|
||||
nan(0xfff8_0000_0000_0000),
|
||||
-2.0,
|
||||
nan(0x7ffc_0000_0000_0000),
|
||||
],
|
||||
"0000003f0000c0ff000000c00000e07f",
|
||||
"0000003f0000c07f000000c00000c07f",
|
||||
),
|
||||
];
|
||||
for &(pf, c, kept, resolved) in cases {
|
||||
let value = color(pf, c, ClearRoute::ThroughHalf).unwrap();
|
||||
for (keeps, want) in [(true, kept), (false, resolved)] {
|
||||
let (format, bits) = float_nan_texel(pf, &value, keeps).unwrap();
|
||||
let format_for = |size: usize| uint_texel(&vec![0; size]).unwrap().0;
|
||||
assert!(format == format_for(want.len() / 2), "{pf:?}");
|
||||
// SAFETY: `float_nan_texel` writes `uint32`.
|
||||
let words = unsafe { bits.uint32 };
|
||||
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
assert_eq!(hex(&bytes[..want.len() / 2]), want, "{pf:?} {c:?} {keeps}");
|
||||
}
|
||||
}
|
||||
let finite = color(P::R32Float, [0.5, 0.0, 0.0, 0.0], ClearRoute::ThroughHalf);
|
||||
assert!(float_nan_texel(P::R32Float, &finite.unwrap(), true).is_none());
|
||||
let half = color(P::RGBA16Float, [f64::NAN; 4], ClearRoute::ThroughHalf);
|
||||
assert!(float_nan_texel(P::RGBA16Float, &half.unwrap(), false).is_none());
|
||||
}
|
||||
|
||||
/// Where Metal keeps a NaN clear's sign it keeps the top ten bits of the double's payload
|
||||
/// too, quieted (an M4: `0x7ffc...` stores `0x7f00`, `0x7fff...` `0x7fff`,
|
||||
/// `0xffff...` `0xffff`, the signalling `0x7ff4...` `0x7f00` and `0xfff0...01` `0xfe00`);
|
||||
/// elsewhere every such NaN is `0x7e00`.
|
||||
#[test]
|
||||
fn signed_nan_texels_keep_a_half_nan_s_payload() {
|
||||
let nan = f64::from_bits;
|
||||
let payloads = [
|
||||
nan(0x7ffc_0000_0000_0000),
|
||||
nan(0x7fff_ffff_ffff_ffff),
|
||||
nan(0xffff_ffff_ffff_ffff),
|
||||
nan(0x7ff4_0000_0000_0000),
|
||||
];
|
||||
let low = [nan(0xfff0_0000_0000_0001), 0.0, 0.0, 0.0];
|
||||
let cases: &[(PixelFormat, [f64; 4], &str, &str)] = &[
|
||||
(
|
||||
P::RGBA16Float,
|
||||
payloads,
|
||||
"007fff7fffff007f",
|
||||
"007e007e007e007e",
|
||||
),
|
||||
(P::R16Float, low, "00fe", "007e"),
|
||||
(
|
||||
P::RG16Float,
|
||||
[nan(0x7ff0_0000_2000_0000), 1.0, 0.0, 0.0],
|
||||
"007e003c",
|
||||
"007e003c",
|
||||
),
|
||||
];
|
||||
for &(pf, c, kept, dropped) in cases {
|
||||
let value = color(pf, c, ClearRoute::ThroughHalf).unwrap();
|
||||
for (signed, want) in [(true, kept), (false, dropped)] {
|
||||
let (_, bits) = nan_texel(pf, &value, signed).unwrap();
|
||||
// SAFETY: `nan_texel` writes `uint32`.
|
||||
let words = unsafe { bits.uint32 };
|
||||
let bytes: Vec<u8> = words.iter().flat_map(|w| w.to_le_bytes()).collect();
|
||||
assert_eq!(hex(&bytes[..want.len() / 2]), want, "{pf:?} {c:?} {signed}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Vulkan clear value of each converted texel is one Vulkan's conversion maps back onto
|
||||
/// it: an exact value, or one within a hair of the normalized integer.
|
||||
#[test]
|
||||
|
||||
@@ -2548,7 +2548,7 @@ fn record(
|
||||
});
|
||||
}
|
||||
}
|
||||
device.degrade_half_texel_writes(&variant.pipeline().dependencies, Some(formats));
|
||||
device.degrade_half_texel_writes(&variant.pipeline().dependencies);
|
||||
objects.degrade_bound_formats(
|
||||
std::slice::from_ref(&variant.pipeline().stage),
|
||||
Some(formats),
|
||||
|
||||
@@ -529,13 +529,6 @@ degradations! {
|
||||
ShaderColorConversion = "shader-color-conversion", Performance,
|
||||
"the fragment function rounds each such channel to nearest even before it writes it: \
|
||||
about 35 more instructions per channel";
|
||||
/// A fragment function writes a `half` to a half-float color attachment as the bits of
|
||||
/// the half Metal stores, through a 16-bit output, on a device that does not store a
|
||||
/// 32-bit output's NaN as Metal does (`StageModule::half_bit_colors`).
|
||||
ShaderHalfColorBits = "shader-half-color-bits", Performance,
|
||||
"the fragment function writes each such output as its half's bits through a 16-bit \
|
||||
output: about 20 more instructions per output, and the attachment takes no Vulkan \
|
||||
blend of one and zero";
|
||||
/// A Metal render pass runs as several Vulkan render pass instances (`render.rs`): a
|
||||
/// framebuffer fetch through the pixel interlock keeps its attachment out of its draws'
|
||||
/// subpass, and the pass's draws leave different attachments out, or its last draws
|
||||
@@ -2158,18 +2151,16 @@ degradations! {
|
||||
/// infinity where Metal answers 65504; a NaN's encoding the device's.
|
||||
NativeHalfQuantize = "native-half-quantize";
|
||||
/// Class: native device maths. The device's NaN answers a `float` or `half` operation's
|
||||
/// NaN result where Metal's bits would be selected (`NanMinMaxPolicy::Native`, the
|
||||
/// default on a device whose arithmetic is not measured to answer Metal's canonical NaN;
|
||||
/// `Exact` keeps Metal's). Recorded bound: where Metal answers a NaN the device answers a
|
||||
/// NaN result where Metal answers a NaN the device is not measured to answer (every NaN
|
||||
/// but the canonical one on a device measured to answer Metal's canonical NaN). Recorded
|
||||
/// bound: where Metal answers a NaN the device answers a
|
||||
/// NaN, its sign and payload the device's own, where Metal answers `0x7fc00000`
|
||||
/// (`0x7e00` as `half`), an operand's bits, or the canonical NaN with an operand's sign;
|
||||
/// every other result unchanged.
|
||||
NativeNanEncoding = "native-nan-encoding";
|
||||
/// Class: native device maths. The device's `NMin`, `NMax` or `NClamp` answers Metal's
|
||||
/// `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` (its `clamp(x, +0, 1)`) on
|
||||
/// `float` or `half` where the translation would select Metal's operand
|
||||
/// (`NanMinMaxPolicy::Native`, the default on a device not measured to answer Metal's;
|
||||
/// `Exact` keeps Metal's). Recorded bound: an operand, Metal's but at three ties: of two
|
||||
/// `float` or `half` on a device not measured to answer Metal's operand. Recorded bound: an operand, Metal's but at three ties: of two
|
||||
/// NaNs a NaN (Metal: the second operand's bits), of `+0` and `-0` either zero (Metal: the
|
||||
/// second), and an `f32` denormal beside a zero or another denormal compared by its value
|
||||
/// where the device keeps denormals (Metal compares it as a zero and answers the second).
|
||||
@@ -2521,9 +2512,6 @@ impl Kinds {
|
||||
kinds.add(Degradation::YCbCrFilterNotExact);
|
||||
}
|
||||
}
|
||||
if !stage.half_bit_colors.is_empty() {
|
||||
kinds.add(Degradation::ShaderHalfColorBits);
|
||||
}
|
||||
if !stage.rounded_colors.is_empty() {
|
||||
kinds.add(Degradation::ShaderColorConversion);
|
||||
}
|
||||
@@ -2620,12 +2608,10 @@ pub(crate) fn dropped_exact_forms(
|
||||
metal2vulkan::pipeline::RuntimeFact::ExactFormsOverCompilerLimit {
|
||||
sampling,
|
||||
texel_conversion,
|
||||
nan_and_min_max,
|
||||
} => Some(
|
||||
[
|
||||
(sampling, "exact sampling"),
|
||||
(texel_conversion, "exact texel conversion"),
|
||||
(nan_and_min_max, "exact NaN and minimum and maximum"),
|
||||
]
|
||||
.into_iter()
|
||||
.filter_map(|(dropped, name)| dropped.then_some(name))
|
||||
@@ -3110,18 +3096,6 @@ impl Device {
|
||||
(object(), self.stage_note_reason(note, stage))
|
||||
});
|
||||
}
|
||||
if !stage.half_bit_colors.is_empty() {
|
||||
self.degrade_at(at, Degradation::ShaderHalfColorBits, || {
|
||||
(
|
||||
object(),
|
||||
format!(
|
||||
"the device stores a 32-bit output's NaN to the half-float format of \
|
||||
color attachment(s) {:?} as another NaN than the `half`'s own bits",
|
||||
stage.half_bit_colors
|
||||
),
|
||||
)
|
||||
});
|
||||
}
|
||||
if !stage.rounded_colors.is_empty() {
|
||||
self.degrade_at(at, Degradation::ShaderColorConversion, || {
|
||||
(
|
||||
@@ -3288,70 +3262,6 @@ impl Device {
|
||||
});
|
||||
}
|
||||
|
||||
/// Announce `PrecisionNote::DeviceNanEncoding` at a draw or dispatch of a pipeline of
|
||||
/// `dependencies` whose `half` texel writes to a texture slot read whether its texture's
|
||||
/// channels are 16-bit floats (`RuntimeFact::StorageTextureHalfChannels`: the slot's storage
|
||||
/// choice declares no format), where `formats` binds there a texture whose stored NaN the
|
||||
/// device's conversion decides (`metal::format::half_write_nans_converted`: 16-bit
|
||||
/// float channels, or a packed small float's), on a device without
|
||||
/// `VkProperty::MetalHalfTexelWrites`; where the command's bound formats are not known
|
||||
/// (`formats` `None`: an execution of indirect commands the GPU writes), at every such slot.
|
||||
/// A 32-bit float, normalized or integer texture there stores Metal's answer and announces
|
||||
/// nothing. The module records no note for such a write: this is its announcement.
|
||||
pub(crate) fn degrade_half_texel_writes(
|
||||
&self,
|
||||
dependencies: &[metal2vulkan::pipeline::RuntimeDependency],
|
||||
formats: Option<BoundFormats<'_>>,
|
||||
) {
|
||||
use metal2vulkan::pipeline::RuntimeFact;
|
||||
self.degrade_heap_half_texel_writes(dependencies);
|
||||
let mut slots = dependencies.iter().filter_map(|d| match d.fact {
|
||||
RuntimeFact::StorageTextureHalfChannels { slot } => Some(slot),
|
||||
_ => None,
|
||||
});
|
||||
let Some(first) = slots.next() else {
|
||||
return;
|
||||
};
|
||||
if !self
|
||||
.shared()
|
||||
.announced
|
||||
.pending(Degradation::DeviceNanEncoding)
|
||||
|| self
|
||||
.compile_device()
|
||||
.profile()
|
||||
.enabled()
|
||||
.properties
|
||||
.contains(&metal2vulkan::device::VkProperty::MetalHalfTexelWrites)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let converted = |slot: SlotRef| match formats {
|
||||
Some(f) => f(slot).map(|pf| (slot, Some(pf))).filter(|(_, pf)| {
|
||||
pf.is_some_and(metal2vulkan::metal::format::half_write_nans_converted)
|
||||
}),
|
||||
None => Some((slot, None)),
|
||||
};
|
||||
let Some((slot, format)) = std::iter::once(first).chain(slots).find_map(converted) else {
|
||||
return;
|
||||
};
|
||||
self.degrade(Degradation::DeviceNanEncoding, || {
|
||||
let bound = match format {
|
||||
Some(pf) => format!("bound as {pf:?}"),
|
||||
None => "of a format the GPU's commands bind".to_owned(),
|
||||
};
|
||||
(
|
||||
format!("the {:?} function of a pipeline state", slot.stage),
|
||||
format!(
|
||||
"it writes `half` texels to texture {} {bound}, whose NaNs the device \
|
||||
stores as it converts them, not as Metal stores a written half (the \
|
||||
half's own bits in a 16-bit float channel, the format's canonical NaN in a \
|
||||
packed small float one)",
|
||||
slot.index
|
||||
),
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
/// Announce `PrecisionNote::DeviceNanEncoding` at a draw or dispatch of a pipeline of
|
||||
/// `dependencies` whose writes through heap handles store half-float members' bits through
|
||||
/// the unsigned integer twin (`RuntimeFact::HeapHalfTexelWrites`), where the device's heap
|
||||
@@ -3359,7 +3269,7 @@ impl Device {
|
||||
/// (`heap_sets::NanResidue`: a half-float texture the twin does not hold, and for a `half`
|
||||
/// write a packed small float one). Every texture the device holds is at its resource ID for
|
||||
/// every command (`heap_sets.rs`), so any of them may be one the function's handles name.
|
||||
fn degrade_heap_half_texel_writes(
|
||||
pub(crate) fn degrade_half_texel_writes(
|
||||
&self,
|
||||
dependencies: &[metal2vulkan::pipeline::RuntimeDependency],
|
||||
) {
|
||||
|
||||
@@ -155,16 +155,15 @@ pub(super) struct Affected {
|
||||
/// and a multisampled copy is then a draw (`radv_gfx_copy_image`) that fetches each sample in
|
||||
/// that format and exports it: a NaN in a 16-bit float channel lands as `0xfe00`, its sign and
|
||||
/// payload lost, while a single-sampled copy kept them. Read in 26.2's source (2026-10-09), and
|
||||
/// measured on 26.2.4 (driverVersion 0x6802004) on the Radeon 780M (`deviceID` 0x15bf;
|
||||
/// `runtime_lane::renders::multisampled_nan_clears_store_metal_s_texel`: every NaN sample of a 4x
|
||||
/// `R16Float` and `RGBA16Float` NaN clear, copied from its unsigned-integer scratch, held
|
||||
/// `0xfe00`: a scratch not mutable to the attachment's format alike): known broken through
|
||||
/// 26.2.4. The path is every RADV GPU's, so every device has it. Nothing is refused: the NaN
|
||||
/// clear of a multisampled attachment is written through a view of its image in the
|
||||
/// unsigned-integer format of its texel size (`nan_clear.rs`), which the runtime's multisampled
|
||||
/// color render targets of such formats take there where it costs the image nothing
|
||||
/// (`nan_clear::view_candidate`), and is the device's copy, announced (`device-nan-encoding`),
|
||||
/// where the image takes no such view.
|
||||
/// measured on 26.2.4 (driverVersion 0x6802004) on the Radeon 780M (`deviceID` 0x15bf: every
|
||||
/// NaN sample of a 4x `R16Float` and `RGBA16Float` texel copied from an unsigned-integer scratch
|
||||
/// held `0xfe00`, a scratch not mutable to the attachment's format alike): known broken through
|
||||
/// 26.2.4. The path is every RADV GPU's, so every device has it. Nothing is refused: a blit copy
|
||||
/// between multisampled images of such a format runs through views of them in the
|
||||
/// unsigned-integer format of its texel size where both take one (`sample_planes::BitsCopy`),
|
||||
/// which the runtime's multisampled color render targets of such formats take where it costs the
|
||||
/// image nothing (`nan_clear::view_candidate`), and is the device's copy, announced
|
||||
/// (`device-nan-encoding`), elsewhere.
|
||||
///
|
||||
/// `ReadsCommandBuffersAfterTheirSignal`:
|
||||
/// - MoltenVK (`MOLTENVK`): on a device with `MTLSharedEvent` the GPU signals a timeline
|
||||
|
||||
@@ -416,7 +416,7 @@ impl Device {
|
||||
/// size; then with the usage its framebuffer fetch's form
|
||||
/// needs ([`fetch_candidate`]), or a multisampled depth/stencil attachment's copies without
|
||||
/// colour copies need (`depth_stencil_scratch::sampled_candidate`), then the unsigned-integer
|
||||
/// view a NaN clear writes a multisampled attachment through on a device whose copies
|
||||
/// view a copy keeps a multisampled attachment's NaN bits through on a device whose copies
|
||||
/// convert its NaNs (`nan_clear::view_candidate`), then the input attachment usage the
|
||||
/// exact color resolve reads a multisampled color attachment through
|
||||
/// (`color_resolve::input_candidate`), and then the feedback loop usage a draw that reads the
|
||||
|
||||
@@ -733,8 +733,7 @@ fn announce(device: &Device, p: &Prepared, objects: &VariantObjects) {
|
||||
[(®ion.specialization, None)],
|
||||
);
|
||||
}
|
||||
// The GPU's commands bind the textures: every slot whose `half` writes read its word.
|
||||
device.degrade_half_texel_writes(&p.variant.pipeline().dependencies, None);
|
||||
device.degrade_half_texel_writes(&p.variant.pipeline().dependencies);
|
||||
device.degrade_bound_formats(std::slice::from_ref(&p.variant.pipeline().stage), None);
|
||||
// The values the variant's plan pushes for the commands the GPU writes.
|
||||
for (n, region) in p.commands.regions.iter().enumerate() {
|
||||
|
||||
@@ -1,69 +1,25 @@
|
||||
//! Clears of a NaN in a `half` or small-float channel, written as Metal writes them.
|
||||
//! Clears of a NaN, and copies of NaN texels.
|
||||
//!
|
||||
//! **Metal** writes the canonical quiet NaN: `0x7e00` for a `half` NaN of either sign, `0x7e0` and
|
||||
//! `0x3f0` for the 11- and 10-bit channels of `RG11B10Float`, the sign dropped (a Metal probe, an
|
||||
//! M4 on macOS 27.0.1 and the M3 Max on 26.7, alike, each plain and under the debug layer).
|
||||
//! **Vulkan** converts a clear value to the attachment's format as the device likes, and the
|
||||
//! devices measured differ there: RADV writes a `half` NaN as `0xfe00`, and lavapipe an
|
||||
//! `RG11B10Float` NaN as `0x7c1` and `0x3e1` (lane `renders::clears_store_the_bytes_metal_stores`).
|
||||
//! An integer clear converts nothing.
|
||||
//!
|
||||
//! So a color attachment whose `Clear` load holds such a NaN ([`clear_value::nan_texel`]) is
|
||||
//! cleared before the pass instead: a scratch image of the unsigned-integer format of its texel
|
||||
//! size (`R16Uint`, `R32Uint` or `RG32Uint`), of its samples and layers
|
||||
//! (`attachment_stand_in::stand_in_as`), is cleared by `vkCmdClearColorImage` to the texel's
|
||||
//! bits, which are copied into the attachment bit-wise (formats of one texel size) over the
|
||||
//! clear's reach (`clear_reach.rs`), and the pass loads it. The scratch image is the pass's own,
|
||||
//! held until its command buffer completes.
|
||||
//!
|
||||
//! **Kept sign**. Where Metal keeps the attachment's texture losslessly compressed, the
|
||||
//! attachment's level is 16 texels or more a side, and the pass has no draw call
|
||||
//! ([`keeps_nan_sign`]), its clear keeps a `half` NaN's sign, `0xfe00` for a negative one, in the
|
||||
//! texel and every sample; elsewhere it drops it (an M4 under macOS 27.0.1, sizes 1 to 256, 1x and
|
||||
//! 4x, `R16Float`, `RG16Float` and `RGBA16Float`; any draw call drops it, one wholly off the
|
||||
//! target, of no area or whose fragments all discard too; the consumer's M3 Max alike at 4x4). The
|
||||
//! scratch is mutable to the attachment's format (`stand_in_as`), so a device that copies between
|
||||
//! formats through a view copies so: MoltenVK's copy of a multisampled image between formats that
|
||||
//! take no such view goes through a buffer, which holds no samples, and left the NaN channels zero.
|
||||
//!
|
||||
//! **Resolves**. Metal's resolve of such a clear in a pass with no draw call stores the clear's
|
||||
//! texel, its sign kept, where the sign is kept and Metal also keeps the resolve texture compressed
|
||||
//! (at its level, of the attachment's extent); elsewhere it averages the samples, each NaN counted
|
||||
//! zero ([`clear_value::resolved_nan_texel`]): a `PixelFormatView` or unoptimized resolve texture,
|
||||
//! a level under 16 a side, a pass whose draw calls draw nothing (a draw call of no vertices drops
|
||||
//! the sign as any draw call does), or a later pass that loads the attachment and resolves it,
|
||||
//! alike. No device's resolve gives either (each keeps the NaN, or zeroes it where Metal keeps it:
|
||||
//! MoltenVK after the copy), so in a pass whose draws reach no tile, every sample holding the
|
||||
//! clear, the resolve texture's render area is written after the pass's resolve, its copies
|
||||
//! included, the same way: a scratch image cleared to that texel's bits and copied in. A pass that
|
||||
//! draws resolves by the device (`device-rounded-resolve`).
|
||||
//!
|
||||
//! **32-bit floats**. Metal clears a `float` NaN as the double's conversion, its sign and top
|
||||
//! payload bits kept, at every level, as the devices' clears do ([`clear_value::color`] states the
|
||||
//! bits), so such a clear needs nothing before the pass. Its resolve in a pass with no draw call
|
||||
//! keeps the clear's texel where the `half` NaN's resolve keeps it, and makes `0x7fc00000` in each
|
||||
//! NaN channel elsewhere, a pass whose draw calls draw nothing among them (the consumer's M3 Max:
|
||||
//! `R32Float`, `RG32Float` and `RGBA32Float` at 2 and 4 samples, 16 a side, cleared to `-NaN`, a
|
||||
//! draw call of no vertices: `0x7fc00000`). A device's resolve need give neither: MoltenVK's, which
|
||||
//! is Metal's own resolve, keeps the sign where its pass records no draw. So in a pass whose draws
|
||||
//! reach no tile the resolve is written after the pass as the `half` one's is, the kept texel or
|
||||
//! Metal's resolve of it ([`clear_value::float_nan_texel`]), on every device alike: where the
|
||||
//! device's resolve stored it already, the write stores the same bits.
|
||||
//! **Color**. Metal writes the canonical quiet NaN for a `half` NaN clear (`0x7e00` of either
|
||||
//! sign), and `0x7e0` and `0x3f0` for the 11- and 10-bit channels of `RG11B10Float`, the sign
|
||||
//! dropped, but where it keeps the attachment's texture losslessly compressed, its level is 16
|
||||
//! texels or more a side, and the pass has no draw call ([`keeps_nan_sign`]), where it keeps a
|
||||
//! `half` NaN's sign. Its resolve of such a clear in a pass with no draw call keeps the clear's
|
||||
//! texel or averages the samples, each NaN counted zero, and makes `0x7fc00000` in each `float`
|
||||
//! NaN channel. Vulkan converts a clear value to the attachment's format as the device likes, and
|
||||
//! resolves its samples as the device likes: the pass clears and resolves by the device, announced
|
||||
//! (`device-nan-encoding`, [`degrade_nan_clears`]). An integer clear converts nothing.
|
||||
//!
|
||||
//! **Copies that convert NaNs**. A device whose copy into a multisampled float image draws the
|
||||
//! samples through that image's format (`RuntimeDriverDefect::MultisampledCopiesConvertFloatNans`:
|
||||
//! RADV, whose copies store every 16-bit float NaN as `0xfe00`) cannot copy the scratch's bits into
|
||||
//! a multisampled attachment. There the clear is written through a view of the attachment's image
|
||||
//! in the unsigned-integer format of its texel size instead: a render pass of that view alone,
|
||||
//! loaded and stored, in which `vkCmdClearAttachments` clears the clear's reach to the texel's bits
|
||||
//! (an integer clear converts nothing). A multisampled color render target the runtime makes of
|
||||
//! such a format takes the view there where it costs the image nothing ([`view_candidate`]), as one
|
||||
//! of `PixelFormatView` usage does; an image that takes none (a caller's, or one the view would
|
||||
//! cost) is copied as elsewhere, announced once (`device-nan-encoding`). A resolve's write lands in
|
||||
//! a single-sampled texture, whose copies keep the bits. The runtime's other copies into such an
|
||||
//! image, a blit copy between textures and an attachment stand-in's, announce the same
|
||||
//! ([`degrade_converting_copy`]); a blit copy between two images that both take the unsigned view
|
||||
//! runs through it instead, exactly (`sample_planes::BitsCopy`).
|
||||
//! RADV, whose copies store every 16-bit float NaN as `0xfe00`) does not copy a NaN's bits into a
|
||||
//! multisampled image. A multisampled color render target the runtime makes of such a format takes
|
||||
//! a view in the unsigned-integer format of its texel size where it costs the image nothing
|
||||
//! ([`view_candidate`]), as one of `PixelFormatView` usage does, and a blit copy between two images
|
||||
//! that both take the unsigned view runs through it, exactly (`sample_planes::BitsCopy`). Into an
|
||||
//! image that takes none (a caller's, or one the view would cost) the device copies, announced once
|
||||
//! (`device-nan-encoding`, [`degrade_converting_copy`]): a blit copy between textures and an
|
||||
//! attachment stand-in's.
|
||||
//!
|
||||
//! **Depth** (our probe `nanclear`, the M3 Max under macOS 27.0.1, plain Metal): a `Clear` load
|
||||
//! whose `clearDepth` is a NaN of any sign or payload stores `0x7fc00000` in every texel and
|
||||
@@ -87,30 +43,20 @@
|
||||
//! hands such a store to its driver (`render_target::DontCare::Discarded`, MoltenVK among them),
|
||||
//! where Metal keeps the texture's earlier texels, which the word would replace; and a
|
||||
//! multisampled depth on a device without either form of the write.
|
||||
//!
|
||||
//! Refused (`NotImplemented(Render)`): such a clear of a memoryless attachment (no image to copy
|
||||
//! into), of one whose sample planes stand for it (`sample_planes.rs` clears the planes by the
|
||||
//! device's conversion), of one whose resolve texture reaches past it (`resolve.rs` clears that
|
||||
//! reach likewise), of a 3D or 1D attachment (`attachment_stand_in::stand_in_as`), and of an
|
||||
//! attachment whose image takes no transfer writes.
|
||||
|
||||
use super::attachment_stand_in::{self, StandInCopies};
|
||||
use super::blit::TRANSFER;
|
||||
use super::buffer::Buffer;
|
||||
use super::clear_reach;
|
||||
use super::clear_value;
|
||||
use super::command_buffer::CommandBuffer;
|
||||
use super::degradation::Degradation;
|
||||
use super::depth_copy::{self, DepthDraw, Drawn};
|
||||
use super::depth_stencil_scratch::colour_copies_refused;
|
||||
use super::encoder::EncoderCore;
|
||||
use super::error::{internal, Error, RuntimeGap};
|
||||
use super::error::{internal, Error};
|
||||
use super::framebuffer_fetch::views_in;
|
||||
use super::image_plan::{compatible, ImagePlan};
|
||||
use super::render_pass::{PassLayout, Target};
|
||||
use super::render_target::{
|
||||
self, DontCare, FramebufferObject, RenderPassObject, ATTACHMENT_STAGES,
|
||||
};
|
||||
use super::render_target::DontCare;
|
||||
use super::render_values::{LoadAction, StoreAction};
|
||||
use super::resource::ResourceKey;
|
||||
use super::sample_copy::bits_image;
|
||||
@@ -128,301 +74,39 @@ use metal2vulkan::vk::{
|
||||
Format, ImageAspectFlags, ImageCreateFlags, ImageUsageFlags, NumericFormat,
|
||||
};
|
||||
|
||||
/// The clears before a pass of its attachments whose `Clear` load holds a `half` or small-float
|
||||
/// NaN (the module docs), with the uses they make and the copies into the attachments.
|
||||
pub(super) struct NanClears {
|
||||
/// Each scratch image, its clear value and its layers.
|
||||
clears: Vec<(vk::Image, vk::ClearColorValue, u32)>,
|
||||
uses: Vec<Use<ResourceKey>>,
|
||||
copies: Option<StandInCopies>,
|
||||
/// The scratch images, held until the command buffer completes.
|
||||
scratch: Vec<Texture>,
|
||||
/// The clears through an unsigned-integer view of the attachment (the module docs), and the
|
||||
/// uses they make.
|
||||
views: Vec<ViewClear>,
|
||||
view_uses: Vec<Use<ResourceKey>>,
|
||||
}
|
||||
|
||||
/// A NaN write through a view of the target's image in the unsigned-integer format of its texel
|
||||
/// size: a render pass of that view alone, loaded and stored (`render_target::reach_pass`), in
|
||||
/// which `vkCmdClearAttachments` clears `extent` from the origin, over `layers`, to `value`.
|
||||
struct ViewClear {
|
||||
pass: RenderPassObject,
|
||||
framebuffer: FramebufferObject,
|
||||
extent: [u32; 2],
|
||||
layers: u32,
|
||||
value: vk::ClearColorValue,
|
||||
}
|
||||
|
||||
impl NanClears {
|
||||
/// The clears of `layout`'s attachments, a pass with a draw call where `called`
|
||||
/// (`clear_reach::cleared`), each attachment cleared here then loaded in the pass; then,
|
||||
/// in a pass whose draws reach no tile (`drew` false: no draw call, or draw calls that draw
|
||||
/// nothing), the writes of their resolves after the pass (the module docs). `None` for either
|
||||
/// when there is none; refused as the module docs say.
|
||||
pub(super) fn plan(
|
||||
maker: &CommandBuffer,
|
||||
layout: &mut PassLayout,
|
||||
(called, drew): (bool, bool),
|
||||
) -> Result<(Option<NanClears>, Option<NanClears>), Error> {
|
||||
let mut before = Writes::default();
|
||||
let mut after = Writes::default();
|
||||
let mut cleared = Vec::new();
|
||||
for (index, color) in layout.colors.iter().enumerate() {
|
||||
let Some(color) = color.as_ref().filter(|c| c.load == LoadAction::Clear) else {
|
||||
continue;
|
||||
};
|
||||
let pixel_format = color.target.texture.pixel_format();
|
||||
let signed = keeps_nan_sign(&color.target, called);
|
||||
// The resolve texture's level and slice, where the pass's draws reach no tile, so
|
||||
// every sample holds the clear.
|
||||
let resolves = matches!(
|
||||
color.store,
|
||||
StoreAction::MultisampleResolve | StoreAction::StoreAndMultisampleResolve
|
||||
);
|
||||
let to = color
|
||||
.resolve
|
||||
.as_ref()
|
||||
.filter(|_| resolves && !drew && color.target.samples > 1)
|
||||
.map(|r| r.copy_to.as_ref().unwrap_or(&r.attachment));
|
||||
let Some(texel) = clear_value::nan_texel(pixel_format, &color.clear, signed) else {
|
||||
// A 32-bit float NaN, which the device clears as Metal does: its resolve written
|
||||
// with the clear's texel where Metal keeps it, else with Metal's resolve of it, as
|
||||
// below (the module docs).
|
||||
if let Some(to) = to {
|
||||
let kept = signed && keeps_nan_sign(to, called);
|
||||
if let Some(texel) =
|
||||
clear_value::float_nan_texel(pixel_format, &color.clear, kept)
|
||||
{
|
||||
after.add(maker, to, texel, layout.extent)?;
|
||||
}
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let past_resolve = color.resolve.as_ref().is_some_and(|r| r.clear.is_some());
|
||||
if color.memoryless || color.planes.is_some() || past_resolve {
|
||||
return Err(Error::NotImplemented(RuntimeGap::Render));
|
||||
}
|
||||
let extent = match clear_reach::stores(color.store) {
|
||||
true => clear_reach::cleared(layout, color.target.extent, called),
|
||||
false => layout.extent,
|
||||
};
|
||||
before.add(maker, &color.target, texel, extent)?;
|
||||
cleared.push(index);
|
||||
let Some(to) = to else {
|
||||
continue;
|
||||
};
|
||||
let texel = match signed && keeps_nan_sign(to, called) {
|
||||
true => Some(texel),
|
||||
false => clear_value::resolved_nan_texel(pixel_format, &color.clear),
|
||||
};
|
||||
let texel = texel.ok_or_else(|| internal("a NaN clear without a resolved texel"))?;
|
||||
after.add(maker, to, texel, layout.extent)?;
|
||||
}
|
||||
let before = before.finish()?;
|
||||
for index in cleared {
|
||||
if let Some(color) = layout.colors.get_mut(index).and_then(Option::as_mut) {
|
||||
color.load = LoadAction::Load;
|
||||
}
|
||||
}
|
||||
Ok((before, after.finish()?))
|
||||
}
|
||||
|
||||
/// Record the clears and the copies in `core`'s command buffer, between barriers from
|
||||
/// everything before and to everything after, and hold the scratch images until it
|
||||
/// completes.
|
||||
pub(super) fn record(self, core: &mut EncoderCore) {
|
||||
let NanClears {
|
||||
clears,
|
||||
uses,
|
||||
copies,
|
||||
scratch,
|
||||
views,
|
||||
view_uses,
|
||||
} = self;
|
||||
core.barrier(Barrier::everything());
|
||||
core.command(TRANSFER, &uses, |device, raw| {
|
||||
for (image, value, layers) in &clears {
|
||||
let range = vk::ImageSubresourceRange {
|
||||
aspect_mask: vk::ImageAspectFlags::COLOR,
|
||||
base_mip_level: 0,
|
||||
level_count: 1,
|
||||
base_array_layer: 0,
|
||||
layer_count: *layers,
|
||||
};
|
||||
// SAFETY: the encoder's command buffer is recording outside a render pass; the
|
||||
// scratch image is live until it completes (held below), rests in `GENERAL`,
|
||||
// takes transfer writes (`stand_in_as` with copies), and has one level and
|
||||
// `layers` layers of a color aspect; an unsigned-integer format takes `uint32`.
|
||||
unsafe {
|
||||
device.cmd_clear_color_image(
|
||||
raw,
|
||||
*image,
|
||||
vk::ImageLayout::GENERAL,
|
||||
value,
|
||||
&[range],
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(copies) = copies {
|
||||
copies.record(core);
|
||||
}
|
||||
core.retain(scratch);
|
||||
if views.is_empty() {
|
||||
return;
|
||||
}
|
||||
core.barrier(Barrier::everything());
|
||||
core.command(ATTACHMENT_STAGES, &view_uses, |device, raw| {
|
||||
for clear in &views {
|
||||
let [width, height] = clear.extent;
|
||||
let area = vk::Rect2D {
|
||||
offset: vk::Offset2D { x: 0, y: 0 },
|
||||
extent: vk::Extent2D { width, height },
|
||||
};
|
||||
let begin = vk::RenderPassBeginInfo::default()
|
||||
.render_pass(clear.pass.raw)
|
||||
.framebuffer(clear.framebuffer.raw)
|
||||
.render_area(area);
|
||||
let attachments = [vk::ClearAttachment {
|
||||
aspect_mask: vk::ImageAspectFlags::COLOR,
|
||||
color_attachment: 0,
|
||||
clear_value: vk::ClearValue { color: clear.value },
|
||||
}];
|
||||
let rects = [vk::ClearRect {
|
||||
rect: area,
|
||||
base_array_layer: 0,
|
||||
layer_count: clear.layers,
|
||||
}];
|
||||
// SAFETY: the encoder's command buffer is recording outside a render pass; the
|
||||
// pass, its framebuffer and the attachment's image are live until it completes
|
||||
// (held below, and the texture by the encoder); the image rests in `GENERAL`, the
|
||||
// pass's layout; the area is the framebuffer's and the layers its own; the
|
||||
// subpass's one color attachment is the one cleared, of an unsigned-integer
|
||||
// format, which takes `uint32`.
|
||||
unsafe {
|
||||
device.cmd_begin_render_pass(raw, &begin, vk::SubpassContents::INLINE);
|
||||
device.cmd_clear_attachments(raw, &attachments, &rects);
|
||||
device.cmd_end_render_pass(raw);
|
||||
}
|
||||
}
|
||||
});
|
||||
core.barrier(Barrier::everything());
|
||||
core.retain(views);
|
||||
}
|
||||
}
|
||||
|
||||
/// A pass's NaN writes as they are planned ([`NanClears::plan`]): each a scratch image of an
|
||||
/// unsigned-integer format, cleared to a texel's bits and copied into its target.
|
||||
#[derive(Default)]
|
||||
struct Writes {
|
||||
/// Each scratch image, its clear value and its layers.
|
||||
clears: Vec<(vk::Image, vk::ClearColorValue, u32)>,
|
||||
uses: Vec<Use<ResourceKey>>,
|
||||
/// Each scratch image, the target it is copied into, and the extent from the origin copied.
|
||||
pairs: Vec<(Target, Target, [u32; 2])>,
|
||||
/// The writes through an unsigned-integer view of the target, and the uses they make.
|
||||
views: Vec<ViewClear>,
|
||||
view_uses: Vec<Use<ResourceKey>>,
|
||||
}
|
||||
|
||||
impl Writes {
|
||||
/// Write `texel`, an unsigned-integer format of its size and the clear value of its bits
|
||||
/// (`clear_value::nan_texel`), into `to` over `extent` from the origin; refused where `to`'s
|
||||
/// image takes no copies (`attachment_stand_in::check_copies`). On a device whose
|
||||
/// multisampled copies convert float NaNs, a multisampled `to` is written through its image's
|
||||
/// view in that format where the image takes one, else by the copy, announced (the module
|
||||
/// docs).
|
||||
fn add(
|
||||
&mut self,
|
||||
maker: &CommandBuffer,
|
||||
to: &Target,
|
||||
(format, value): (metal2vulkan::vk::Format, vk::ClearColorValue),
|
||||
extent: [u32; 2],
|
||||
) -> Result<(), Error> {
|
||||
let device = maker.device();
|
||||
if to.samples > 1 && converts_nans(device) {
|
||||
if views_in(to.texture.image_plan()?, format)
|
||||
&& renders_unsigned(device, format, to.samples)?
|
||||
{
|
||||
let viewed = Target {
|
||||
format,
|
||||
..to.clone()
|
||||
};
|
||||
let (pass, framebuffer, made) =
|
||||
render_target::reach_pass(device, &viewed, false, extent)?;
|
||||
self.view_uses.extend(made);
|
||||
self.views.push(ViewClear {
|
||||
pass,
|
||||
framebuffer,
|
||||
extent,
|
||||
layers: to.layers,
|
||||
value,
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
device.degrade(Degradation::DeviceNanEncoding, || {
|
||||
(
|
||||
format!(
|
||||
"a multisampled {:?} attachment's NaN clear",
|
||||
to.texture.pixel_format()
|
||||
),
|
||||
"its image takes no view in the unsigned-integer format of its texel size \
|
||||
that the device renders at its sample count, and the device's copy into a \
|
||||
multisampled float image stores each NaN as it converts it \
|
||||
(`RuntimeDriverDefect::MultisampledCopiesConvertFloatNans`), not with the \
|
||||
sign and payload Metal's clear stores"
|
||||
.to_owned(),
|
||||
)
|
||||
});
|
||||
}
|
||||
attachment_stand_in::check_copies(to)?;
|
||||
let scratch = attachment_stand_in::stand_in_as(maker, to, true, format)?;
|
||||
let write = Access::new(TRANSFER, vk::AccessFlags2::TRANSFER_WRITE);
|
||||
self.uses.push(
|
||||
scratch
|
||||
.texture
|
||||
.image_use(0..1, 0..scratch.layers, write, true)?,
|
||||
);
|
||||
self.clears
|
||||
.push((scratch.texture.raw_image()?, value, scratch.layers));
|
||||
self.pairs.push((scratch, to.clone(), extent));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The writes' clears and copies; `None` when there is none.
|
||||
fn finish(self) -> Result<Option<NanClears>, Error> {
|
||||
if self.pairs.is_empty() && self.views.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
let pairs: Vec<_> = self
|
||||
.pairs
|
||||
.iter()
|
||||
.map(|(from, to, extent)| (from, to, *extent))
|
||||
.collect();
|
||||
let copies = match pairs.is_empty() {
|
||||
true => None,
|
||||
false => Some(
|
||||
StandInCopies::plan(&pairs, false)?
|
||||
.ok_or_else(|| internal("NaN writes without copies"))?,
|
||||
),
|
||||
/// Announce `PrecisionNote::DeviceNanEncoding` where a color attachment of `layout`, a pass whose
|
||||
/// draws reach a tile where `drew`, clears to a NaN whose bits the device's conversion decides (the
|
||||
/// module docs): a `half` or small-float channel's, or a resolve's of a pass whose draws reach no
|
||||
/// tile, where every sample holds the clear.
|
||||
pub(super) fn degrade_nan_clears(device: &Device, layout: &PassLayout, drew: bool) {
|
||||
let held = layout.colors.iter().flatten().find_map(|color| {
|
||||
let resolves = matches!(
|
||||
color.store,
|
||||
StoreAction::MultisampleResolve | StoreAction::StoreAndMultisampleResolve
|
||||
) && color.resolve.is_some()
|
||||
&& !drew
|
||||
&& color.target.samples > 1;
|
||||
let pf = color.target.texture.pixel_format();
|
||||
let narrow = (color.load == LoadAction::Clear)
|
||||
.then(|| clear_value::nan_channels(pf, &color.clear))
|
||||
.flatten()?;
|
||||
(narrow || resolves).then_some((pf, narrow))
|
||||
});
|
||||
let Some((pf, narrow)) = held else {
|
||||
return;
|
||||
};
|
||||
device.degrade(Degradation::DeviceNanEncoding, || {
|
||||
let what = match narrow {
|
||||
true => "the device converts it to the format's NaN as it likes",
|
||||
false => "the device's resolve of its samples keeps or drops the NaN as it likes",
|
||||
};
|
||||
let Writes {
|
||||
clears,
|
||||
uses,
|
||||
pairs,
|
||||
views,
|
||||
view_uses,
|
||||
} = self;
|
||||
Ok(Some(NanClears {
|
||||
clears,
|
||||
uses,
|
||||
copies,
|
||||
scratch: pairs.into_iter().map(|(from, _, _)| from.texture).collect(),
|
||||
views,
|
||||
view_uses,
|
||||
}))
|
||||
}
|
||||
(
|
||||
format!("a {pf:?} color attachment's NaN clear"),
|
||||
format!(
|
||||
"{what}, where Metal stores its canonical quiet NaN or the clear's sign and payload"
|
||||
),
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
/// Whether Metal's NaN clear of `target`, in a pass with a draw call where `called`, keeps a
|
||||
@@ -450,8 +134,7 @@ pub(super) fn keeps_nan_sign(target: &Target, called: bool) -> bool {
|
||||
}
|
||||
|
||||
/// Whether `format` is a color format of floats narrower than 32 bits (a `half`'s, a packed
|
||||
/// small float's): those whose NaN clear the runtime writes ([`clear_value::nan_texel`]), and
|
||||
/// whose NaNs a device whose multisampled copies convert float NaNs converts
|
||||
/// small float's): those whose NaNs a device whose multisampled copies convert float NaNs converts
|
||||
/// (`driver_defects.rs`: RADV's copy exports them through a conversion).
|
||||
pub(super) fn narrow_float(format: Format) -> bool {
|
||||
format.block().is_some_and(|block| {
|
||||
@@ -504,11 +187,11 @@ fn converts_nans(device: &Device) -> bool {
|
||||
}
|
||||
|
||||
/// `plan` mutable with a view in the unsigned-integer format of its texel size, through which a
|
||||
/// NaN clear writes its samples (the module docs), where the device's multisampled copies convert
|
||||
/// float NaNs: a multisampled color attachment that is not transient, of a format whose NaN
|
||||
/// clear the runtime writes, whose view format is of its compatibility class and one the device
|
||||
/// renders at its sample count ([`renders_unsigned`]). `None` elsewhere, and where the plan
|
||||
/// takes the view already.
|
||||
/// copy of its samples keeps their bits (the module docs, `sample_planes::BitsCopy`), where the
|
||||
/// device's multisampled copies convert float NaNs: a multisampled color attachment that is not
|
||||
/// transient, of a format of floats narrower than 32 bits ([`narrow_float`]), whose view format
|
||||
/// is of its compatibility class and one the device renders at its sample count
|
||||
/// ([`renders_unsigned`]). `None` elsewhere, and where the plan takes the view already.
|
||||
pub(super) fn view_candidate(
|
||||
plan: &ImagePlan,
|
||||
device: &Device,
|
||||
|
||||
@@ -301,7 +301,7 @@ use super::kept_bytes;
|
||||
use super::linear_attachment;
|
||||
use super::linear_merge::LinearMerge;
|
||||
use super::live_bind::{Emptied, LiveBind, Reshape};
|
||||
use super::nan_clear::{keeps_nan_sign, NanClears, NanDepthWrite};
|
||||
use super::nan_clear::{keeps_nan_sign, NanDepthWrite};
|
||||
use super::owned_kernel::OwnedModule;
|
||||
use super::pipeline::Settled;
|
||||
use super::pipeline::{BufferForms, DrawPipeline};
|
||||
@@ -4678,13 +4678,8 @@ impl RenderLowering {
|
||||
scratch(&|index, c| stored(c) && !merged.iter().any(|&(at, _)| at == index));
|
||||
copied_back.extend(depth_stencil_copies(true));
|
||||
let stand_ins_out = StandInCopies::plan_aspects(&copied_back, false)?;
|
||||
// A clear holding a `half` or small-float NaN: written before the pass as Metal writes
|
||||
// it, through a scratch image of an integer format, and loaded in the pass
|
||||
// (`nan_clear.rs`). After the stand-ins' copies, which keep the attachment's own load.
|
||||
// And, in a pass whose draws reach no tile, its resolves written after the pass as
|
||||
// Metal's resolve stores them (`nan_clear.rs`).
|
||||
let (nan_clears, nan_resolves) =
|
||||
NanClears::plan(core.command_buffer(), &mut layout, (called, drew))?;
|
||||
// A clear holding a NaN the device's conversion or resolve decides (`nan_clear.rs`).
|
||||
super::nan_clear::degrade_nan_clears(core.device(), &layout, drew);
|
||||
// A depth whose `Clear` load held a NaN, loaded instead: Metal's word written into its
|
||||
// texture over the clear's reach before the pass, before anything copies the depth out
|
||||
// of it (`nan_clear.rs`).
|
||||
@@ -5060,9 +5055,6 @@ impl RenderLowering {
|
||||
for (_, merge) in &merged {
|
||||
merge.record_keep(&mut core);
|
||||
}
|
||||
if let Some(clears) = nan_clears {
|
||||
clears.record(&mut core);
|
||||
}
|
||||
if let Some(clears) = reach_clears {
|
||||
clears.record(&mut core);
|
||||
}
|
||||
@@ -5486,9 +5478,6 @@ impl RenderLowering {
|
||||
if let Some(copies) = resolve_copies {
|
||||
copies.record(&mut core);
|
||||
}
|
||||
if let Some(writes) = nan_resolves {
|
||||
writes.record(&mut core);
|
||||
}
|
||||
if let Some(results) = results {
|
||||
results.record(&mut core);
|
||||
}
|
||||
@@ -8526,7 +8515,7 @@ impl RenderLowering {
|
||||
};
|
||||
// The formats the draw binds, which a specialized notice names.
|
||||
let formats = |slot| tables.bound_format(slot);
|
||||
device.degrade_half_texel_writes(&variant.pipeline().dependencies, Some(&formats));
|
||||
device.degrade_half_texel_writes(&variant.pipeline().dependencies);
|
||||
(variant.objects()).degrade_bound_formats(&variant.pipeline().stages, Some(&formats));
|
||||
// A variant whose notes test no bound value is quiet at every draw, and kept as none
|
||||
// (`Device::tests_bound_values`).
|
||||
|
||||
@@ -1942,7 +1942,7 @@ impl RenderLowering {
|
||||
let formats = |slot| tables.bound_format(slot);
|
||||
self.core
|
||||
.device()
|
||||
.degrade_half_texel_writes(&variant.pipeline().dependencies, Some(&formats));
|
||||
.degrade_half_texel_writes(&variant.pipeline().dependencies);
|
||||
self.core
|
||||
.device()
|
||||
.degrade_bound_formats(&variant.pipeline().stages, Some(&formats));
|
||||
|
||||
@@ -134,7 +134,6 @@ use crate::clear_reach;
|
||||
use crate::device::Device;
|
||||
use crate::error::Error;
|
||||
use crate::linear_attachment;
|
||||
use crate::nan_clear::keeps_nan_sign;
|
||||
use crate::render_pass::{ColorTarget, PassLayout};
|
||||
use crate::render_target::{
|
||||
self, Feedback, FramebufferObject, PassShape, Position, RenderPassObject,
|
||||
@@ -248,15 +247,8 @@ pub(super) fn opens_inline(
|
||||
// late. Else the first action ruled out.
|
||||
let loaded = match color.load {
|
||||
LoadAction::Load => (area != layout.extent).then_some(ActionsRefused::UnequalReach),
|
||||
LoadAction::Clear => {
|
||||
let signed = keeps_nan_sign(target, true);
|
||||
let format = texture.pixel_format();
|
||||
match clear_reach::cleared(layout, target.extent, true) == area {
|
||||
false => Some(ActionsRefused::UnequalReach),
|
||||
true => crate::clear_value::nan_texel(format, &color.clear, signed)
|
||||
.map(|_| ActionsRefused::NanClear),
|
||||
}
|
||||
}
|
||||
LoadAction::Clear => (clear_reach::cleared(layout, target.extent, true) != area)
|
||||
.then_some(ActionsRefused::UnequalReach),
|
||||
LoadAction::DontCare => Some(ActionsRefused::DontCareLoad),
|
||||
};
|
||||
let refused = loaded
|
||||
|
||||
@@ -1113,10 +1113,7 @@ impl RenderLowering {
|
||||
.objects()
|
||||
.tested_formats(&|slot| tables.bound_format(slot))
|
||||
});
|
||||
device.degrade_half_texel_writes(
|
||||
&variant.pipeline().dependencies,
|
||||
Some(&|slot| tables.bound_format(slot)),
|
||||
);
|
||||
device.degrade_half_texel_writes(&variant.pipeline().dependencies);
|
||||
device.degrade_bound_formats(
|
||||
std::slice::from_ref(&variant.pipeline().stage),
|
||||
Some(&|slot| tables.bound_format(slot)),
|
||||
|
||||
@@ -77,7 +77,6 @@ fn fit_into(dependencies: &mut Vec<RuntimeDependency>) {
|
||||
RuntimeFact::ExactFormsOverCompilerLimit {
|
||||
sampling: true,
|
||||
texel_conversion: true,
|
||||
nan_and_min_max: false,
|
||||
},
|
||||
Mechanism::None,
|
||||
));
|
||||
|
||||
@@ -114,10 +114,11 @@ fn a_draw_call_drops_a_half_nan_s_sign() {
|
||||
}
|
||||
|
||||
/// On a device whose multisampled copies convert float NaNs (RADV), a multisampled render target
|
||||
/// the runtime makes, of a format whose NaN clear it writes, takes a view in the unsigned-integer
|
||||
/// format of its texel size, through which the clear is written (`nan_clear.rs`), wherever it
|
||||
/// costs the image nothing; where the view would change the image's memory requirements, its
|
||||
/// clear is announced instead. Elsewhere nothing asks for it. Each prints `NAN-CLEAR-VIEW`.
|
||||
/// the runtime makes, of a format of floats narrower than 32 bits, takes a view in the
|
||||
/// unsigned-integer format of its texel size, through which a copy keeps its samples' bits
|
||||
/// (`nan_clear.rs`), wherever it costs the image nothing; where the view would change the image's
|
||||
/// memory requirements, its copies are announced instead. Elsewhere nothing asks for it. Each
|
||||
/// prints `NAN-CLEAR-VIEW`.
|
||||
#[test]
|
||||
fn a_nan_clear_target_takes_an_unsigned_view_where_copies_convert_and_it_is_free() {
|
||||
let scratch = Scratch::new();
|
||||
|
||||
@@ -584,8 +584,6 @@ pub(crate) enum ActionsRefused {
|
||||
/// of whole tiles (`clear_reach.rs`) reaches another extent than another color's, or loaded,
|
||||
/// or a memoryless color smaller, where another's clear reaches past the render area.
|
||||
UnequalReach,
|
||||
/// Cleared to a NaN whose bits the device's clear would not keep (`clear_value::nan_texel`).
|
||||
NanClear,
|
||||
/// Resolved, into a resolve attachment or by a copy after the pass.
|
||||
Resolve,
|
||||
/// Stored other than by `Store`, or late (`storeActionOptions` set after the encoder).
|
||||
@@ -3739,9 +3737,6 @@ pub struct WorkCounts {
|
||||
/// smaller memoryless texture. A pass whose attachments share the reach records its first
|
||||
/// instance inline over it.
|
||||
pub passes_not_inline_actions_unequal_reach: u64,
|
||||
/// Of those, the ones where it is a clear to a NaN whose bits the device's clear would not
|
||||
/// keep.
|
||||
pub passes_not_inline_actions_nan_clear: u64,
|
||||
/// Of those, the ones where it is a resolve, into a resolve attachment or by a copy after the
|
||||
/// pass.
|
||||
pub passes_not_inline_actions_resolve: u64,
|
||||
@@ -5012,7 +5007,6 @@ impl Device {
|
||||
.load(Ordering::Relaxed),
|
||||
passes_not_inline_actions_dont_care_load: actions(ActionsRefused::DontCareLoad),
|
||||
passes_not_inline_actions_unequal_reach: actions(ActionsRefused::UnequalReach),
|
||||
passes_not_inline_actions_nan_clear: actions(ActionsRefused::NanClear),
|
||||
passes_not_inline_actions_resolve: actions(ActionsRefused::Resolve),
|
||||
passes_not_inline_actions_store: actions(ActionsRefused::Store),
|
||||
passes_not_inline_buffer_textures: not_inline(NotInline::BufferTextures),
|
||||
|
||||
@@ -1 +1 @@
|
||||
3d4df3af6a75270a98fba273007ec0aa849a57a434bd7b5a61058b6ba89b9c39
|
||||
ba946094128fdce3aefe2b69a7e272da1ee6847dd4f21d40e05fd04b43e5094d
|
||||
@@ -110,8 +110,8 @@
|
||||
//! `--policy NAMES` (`run` and `time`) opens the device with those `DevicePolicy` switches at their
|
||||
//! accurate forms, where it opens at the default policy otherwise: a comma-separated list of
|
||||
//! `exact-answers` (`DevicePolicy::exact_answers`) and field names (`sampling`, `ycbcr_filter`,
|
||||
//! `texel_conversion`, `nan_and_min_max`), each set to its `Exact` form, so a making under an
|
||||
//! application's exact forms is timed as it makes them.
|
||||
//! `texel_conversion`), each set to its `Exact` form, so a making under an application's exact
|
||||
//! forms is timed as it makes them.
|
||||
//!
|
||||
//! `--device-type` names the device the draw runs on, as validation's other device commands do
|
||||
//! (`cpu` matches only a CPU implementation such as lavapipe); the device opens through
|
||||
@@ -148,7 +148,7 @@
|
||||
|
||||
use metal2vulkan::bind::SamplerDescriptor;
|
||||
use metal2vulkan::device::{
|
||||
DevicePolicy, NanMinMaxPolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy,
|
||||
DevicePolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy,
|
||||
};
|
||||
use metal2vulkan::metal::state::DepthStencilDescriptor;
|
||||
use metal2vulkan::metal::CompareFunction;
|
||||
@@ -316,11 +316,9 @@ fn policy(options: &BTreeMap<String, String>) -> Result<DevicePolicy, String> {
|
||||
"sampling" => policy.sampling = SamplingPolicy::Exact,
|
||||
"ycbcr_filter" => policy.ycbcr_filter = YCbCrFilterPolicy::Exact,
|
||||
"texel_conversion" => policy.texel_conversion = TexelConversionPolicy::Exact,
|
||||
"nan_and_min_max" => policy.nan_and_min_max = NanMinMaxPolicy::Exact,
|
||||
_ => {
|
||||
return Err(format!(
|
||||
"--policy {name:?}: exact-answers, sampling, ycbcr_filter, texel_conversion \
|
||||
or nan_and_min_max"
|
||||
"--policy {name:?}: exact-answers, sampling, ycbcr_filter or texel_conversion"
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,14 +36,13 @@
|
||||
//! Each case draws the same inputs into the format, every channel of a texel the same input,
|
||||
//! plain and through blending with factors one and zero, reads the attachment back, and compares
|
||||
//! every channel with the rule. One difference is the recorded near-equivalent
|
||||
//! `DeviceNanEncoding`, not a failure, where the fragment stage records it: a NaN a half-float
|
||||
//! channel stores as another NaN (ANV and RADV store `0xfe00`; lavapipe quiets or canonicalizes a
|
||||
//! `half` NaN). Such channels are counted and printed apart, with the codes stored; where the
|
||||
//! fragment stage does not record the note (the driver is measured to store Metal's NaN,
|
||||
//! `DriverDeviation::MetalFloatColorNans` and `MetalHalfColorNans`, or to store a 16-bit output's
|
||||
//! bits, `HalfColorOutputBits`, through which MoltenVK writes a `half` output), and for every other
|
||||
//! channel, a NaN's class included, the lane is exact. A case written through a 16-bit output says
|
||||
//! so. The fragment function writes the output as computed and the device converts it: where the
|
||||
//! `DeviceNanEncoding`, not a failure, where the fragment stage records it: a NaN a half-float or
|
||||
//! unsigned small float channel stores as another NaN (ANV and RADV store `0xfe00`; lavapipe
|
||||
//! quiets or canonicalizes a `half` NaN; RADV and NVIDIA keep a small float NaN's payload). Such
|
||||
//! channels are counted and printed apart, with the codes stored; where the fragment stage does
|
||||
//! not record the note (the driver is measured to store Metal's NaN,
|
||||
//! `DriverDeviation::MetalFloatColorNans` and `MetalHalfColorNans`), and for every other channel, a
|
||||
//! NaN's class included, the lane is exact. The fragment function writes the output as computed and the device converts it: where the
|
||||
//! device is measured to convert the kind of channel as Metal does (MoltenVK on Apple's GPUs,
|
||||
//! `DriverDeviation::MetalColorWrites`; `MetalSmallFloatColorWrites`, a `float` output to a
|
||||
//! half-float or `RG11B10Float` channel; `MetalNorm16ColorWrites`, an output to a 16-bit unorm or
|
||||
@@ -57,7 +56,6 @@ use super::resolves::{lane, quiet, Lane};
|
||||
use crate::candidate::runtime_samples::{library, shape};
|
||||
use crate::runtime_lane::buffer_with;
|
||||
use metal2vulkan::bind::SRGB_RESOLVE_THRESHOLDS;
|
||||
use metal2vulkan::error::DriverDeviation;
|
||||
use metal2vulkan::metal::format::WordAttachment;
|
||||
use metal2vulkan::metal::{
|
||||
BlendFactor, ColorWriteMask, PixelFormat, PrimitiveType, TextureUsage, TextureWriteRoundingMode,
|
||||
@@ -74,10 +72,7 @@ use metal2vulkan_runtime::{
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// The kinds [`pipeline_states_announce_the_shader_conversion_once`] takes.
|
||||
pub(super) const COLOR_WRITES: [Degradation; 2] = [
|
||||
Degradation::ShaderColorConversion,
|
||||
Degradation::ShaderHalfColorBits,
|
||||
];
|
||||
pub(super) const COLOR_WRITES: [Degradation; 1] = [Degradation::ShaderColorConversion];
|
||||
|
||||
/// The texels of a row.
|
||||
const WIDTH: usize = 1024;
|
||||
@@ -694,9 +689,16 @@ pub(super) fn half_toward_zero(x: f32) -> u16 {
|
||||
sign | (exponent << 10) | ((bits >> 13) & 0x3ff) as u16
|
||||
}
|
||||
|
||||
/// Whether `code`, of `channel`, is a NaN: a half with every exponent bit and a fraction.
|
||||
fn half_nan(channel: Channel, code: u64) -> bool {
|
||||
matches!(channel, Channel::Half) && code & 0x7c00 == 0x7c00 && code & 0x3ff != 0
|
||||
/// Whether `code`, of `channel`, is a NaN: a half, or an unsigned small float, with every
|
||||
/// exponent bit and a fraction.
|
||||
fn float_nan(channel: Channel, code: u64) -> bool {
|
||||
let fraction = match channel {
|
||||
Channel::Half => 10,
|
||||
Channel::UnsignedFloat(bits) => bits,
|
||||
_ => return false,
|
||||
};
|
||||
let exponent = 0x1f << fraction;
|
||||
code & exponent == exponent && code & ((1 << fraction) - 1) != 0
|
||||
}
|
||||
|
||||
/// The `bits` bits at `offset` of a texel.
|
||||
@@ -714,18 +716,11 @@ struct Drawn {
|
||||
stored: Vec<u8>,
|
||||
/// Whether the fragment stage records `PrecisionNote::DeviceNanEncoding`.
|
||||
noted: bool,
|
||||
/// Whether the fragment stage declares the `StorageInputOutput16` capability: its color output
|
||||
/// is written as the bits of the half Metal stores, through a 16-bit output.
|
||||
sixteen: bool,
|
||||
/// Whether the fragment stage records `PrecisionNote::DeviceColorConversion`: the device's own
|
||||
/// conversion of the attachment's channels, printed against Metal's and not held to it.
|
||||
converted: bool,
|
||||
}
|
||||
|
||||
/// `OpCapability StorageInputOutput16`: the instruction's first word (two words, opcode 17) and
|
||||
/// the capability (4436).
|
||||
const IO16_CAPABILITY: [u32; 2] = [0x0002_0011, 4436];
|
||||
|
||||
/// How a draw blends: not at all, with factors one and zero, or by premultiplied source-over (one
|
||||
/// and one minus the source alpha, added, for color and alpha).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -783,7 +778,6 @@ fn drawn(
|
||||
let noted = fragment
|
||||
.precision_notes
|
||||
.contains(&PrecisionNote::DeviceNanEncoding);
|
||||
let sixteen = fragment.spirv.windows(2).any(|w| w == IO16_CAPABILITY);
|
||||
let converted = fragment
|
||||
.precision_notes
|
||||
.contains(&PrecisionNote::DeviceColorConversion);
|
||||
@@ -828,7 +822,6 @@ fn drawn(
|
||||
Ok(Drawn {
|
||||
stored,
|
||||
noted,
|
||||
sixteen,
|
||||
converted,
|
||||
})
|
||||
}
|
||||
@@ -863,7 +856,6 @@ fn draws_store_metals_codes() {
|
||||
let Drawn {
|
||||
stored,
|
||||
noted,
|
||||
sixteen,
|
||||
converted,
|
||||
} = match drawn(&lane, case, &values, blend, None) {
|
||||
Ok(drawn) => drawn,
|
||||
@@ -886,7 +878,7 @@ fn draws_store_metals_codes() {
|
||||
channels += 1;
|
||||
let got = field(texel, offset, channel.bits());
|
||||
let want = metal_of(channel, x, blended, case.output);
|
||||
if got != want && noted && half_nan(channel, got) && half_nan(channel, want) {
|
||||
if got != want && noted && float_nan(channel, got) && float_nan(channel, want) {
|
||||
nans += 1;
|
||||
if stores.len() < 4 {
|
||||
stores.insert(format!("{want:#06x} as {got:#06x}"));
|
||||
@@ -902,20 +894,17 @@ fn draws_store_metals_codes() {
|
||||
}
|
||||
}
|
||||
}
|
||||
let output = if sixteen { ", a 16-bit output" } else { "" };
|
||||
if nans > 0 {
|
||||
let stores = stores.into_iter().collect::<Vec<_>>().join(", ");
|
||||
eprintln!(
|
||||
"color write {label} on {name}: {nans} NaN channels store another NaN \
|
||||
(DeviceNanEncoding, recorded{output}: {stores})"
|
||||
(DeviceNanEncoding, recorded: {stores})"
|
||||
);
|
||||
} else if noted {
|
||||
eprintln!(
|
||||
"color write {label} on {name}: DeviceNanEncoding recorded, no NaN channel \
|
||||
differs{output}"
|
||||
differs"
|
||||
);
|
||||
} else if sixteen {
|
||||
eprintln!("color write {label} on {name}: written through a 16-bit output");
|
||||
}
|
||||
let recorded = match converted {
|
||||
true => " (DeviceColorConversion, recorded)",
|
||||
@@ -1183,9 +1172,8 @@ fn channel_lane(pf: PixelFormat, offset: u32) -> usize {
|
||||
/// announces `shader-color-conversion` on every device, its fragment stage listing the attachment
|
||||
/// as rounded (the one rounding the function makes: no device's conversion rounds a half to
|
||||
/// nearest even). One writing `half4` to an `RGBA16Float` attachment at Metal's default mode
|
||||
/// announces `shader-half-color-bits` where the device writes it as the half's bits through a
|
||||
/// 16-bit output (MoltenVK, `HalfColorOutputBits`), its stage listing the attachment as written so
|
||||
/// exactly there and never as rounded.
|
||||
/// announces no shader conversion, its stage never listing the attachment as rounded: the half is
|
||||
/// stored as the device converts it.
|
||||
#[test]
|
||||
fn pipeline_states_announce_the_shader_conversion_once() {
|
||||
let (messages, _cache, lane) = lane();
|
||||
@@ -1198,9 +1186,6 @@ fn pipeline_states_announce_the_shader_conversion_once() {
|
||||
.function_descriptor()
|
||||
};
|
||||
let compile = device.compile_device();
|
||||
let bits = compile
|
||||
.profile()
|
||||
.takes_driver_deviation(DriverDeviation::HalfColorOutputBits);
|
||||
// Each kind is announced once per device: the second state's are those the first did not.
|
||||
let mut seen = BTreeSet::new();
|
||||
for (fragment, rounding, kind, listed) in [
|
||||
@@ -1213,8 +1198,8 @@ fn pipeline_states_announce_the_shader_conversion_once() {
|
||||
(
|
||||
"rt6_fill_rgba16float",
|
||||
TextureWriteRoundingMode::TowardZero,
|
||||
Degradation::ShaderHalfColorBits,
|
||||
bits,
|
||||
Degradation::ShaderColorConversion,
|
||||
false,
|
||||
),
|
||||
] {
|
||||
let mut descriptor =
|
||||
@@ -1230,15 +1215,11 @@ fn pipeline_states_announce_the_shader_conversion_once() {
|
||||
compiled.stages.iter().map(list).collect::<Vec<&[u32]>>()
|
||||
};
|
||||
let rounded = lists(&|s| s.rounded_colors.as_slice());
|
||||
let half_bits = lists(&|s| s.half_bit_colors.as_slice());
|
||||
let (want_rounded, want_bits): (&[&[u32]], &[&[u32]]) =
|
||||
match (kind == Degradation::ShaderColorConversion, listed) {
|
||||
(true, true) => (&[&[], &[0]], &[&[], &[]]),
|
||||
(false, true) => (&[&[], &[]], &[&[], &[0]]),
|
||||
(_, false) => (&[&[], &[]], &[&[], &[]]),
|
||||
};
|
||||
let want_rounded: &[&[u32]] = match listed {
|
||||
true => &[&[], &[0]],
|
||||
false => &[&[], &[]],
|
||||
};
|
||||
assert_eq!(rounded, want_rounded, "{fragment}");
|
||||
assert_eq!(half_bits, want_bits, "{fragment}");
|
||||
let mut expected: BTreeSet<Degradation> = compiled
|
||||
.stages
|
||||
.iter()
|
||||
@@ -1298,8 +1279,10 @@ fn the_rules_give_metals_spot_answers() {
|
||||
assert_eq!(metal(f10, 1.0 + 1.0 / 32.0 - 1e-7, false), 15 << 5);
|
||||
assert_eq!(metal(f11, 2f32.powi(-20), false), 1);
|
||||
assert_eq!(metal(f11, 2f32.powi(-20) * 0.99, false), 0);
|
||||
assert!(half_nan(HALF, 0x7e00) && half_nan(HALF, 0xfe00) && half_nan(HALF, 0x7c01));
|
||||
assert!(!half_nan(HALF, 0x7c00) && !half_nan(HALF, 0xfc00) && !half_nan(U16, 0x7e00));
|
||||
assert!(float_nan(HALF, 0x7e00) && float_nan(HALF, 0xfe00) && float_nan(HALF, 0x7c01));
|
||||
assert!(!float_nan(HALF, 0x7c00) && !float_nan(HALF, 0xfc00) && !float_nan(U16, 0x7e00));
|
||||
assert!(float_nan(f11, 0x7e0) && float_nan(f11, 0x7c1) && float_nan(f10, 0x3f0));
|
||||
assert!(!float_nan(f11, 0x7c0) && !float_nan(f10, 0x3e0));
|
||||
for c in 0..0x7c0 {
|
||||
let x = unsigned_float_value(c, 6) as f32;
|
||||
assert_eq!(metal(f11, x, false), u64::from(c), "{c:#x}");
|
||||
|
||||
@@ -1869,8 +1869,7 @@ fn a_creation_s_notices_and_messages_reach_the_sink_on_the_asking_thread() {
|
||||
/// every precision note a stage records that no specialization removes (a specialized one is
|
||||
/// announced where a draw or dispatch binds a variant keeping it), but
|
||||
/// `ArgumentPixelSamplerScaling`, which a draw or dispatch listing the state announces;
|
||||
/// `shader-half-color-bits` where a stage writes a `half`'s bits to a color attachment,
|
||||
/// `shader-color-conversion` where one rounds a color write to Metal's code; and reconvergence
|
||||
/// `shader-color-conversion` where a stage rounds a color write to Metal's code; and reconvergence
|
||||
/// that is not Metal's.
|
||||
fn making_kinds<'a>(stages: impl IntoIterator<Item = &'a StageModule>) -> BTreeSet<Degradation> {
|
||||
let mut kinds = BTreeSet::new();
|
||||
@@ -1881,9 +1880,6 @@ fn making_kinds<'a>(stages: impl IntoIterator<Item = &'a StageModule>) -> BTreeS
|
||||
kinds.insert(Degradation::from_precision_note(note));
|
||||
}
|
||||
}
|
||||
if !stage.half_bit_colors.is_empty() {
|
||||
kinds.insert(Degradation::ShaderHalfColorBits);
|
||||
}
|
||||
if !stage.rounded_colors.is_empty() {
|
||||
kinds.insert(Degradation::ShaderColorConversion);
|
||||
}
|
||||
|
||||
@@ -1190,10 +1190,10 @@ const MIN_MAX_CASES: [&str; 4] = [
|
||||
"nan-model-min-max-at-zeros-and-denormals-under-fast-math",
|
||||
];
|
||||
|
||||
/// Every word of [`MIN_MAX_CASES`] is the Metal row's of the same chip on every profile: the
|
||||
/// device's `NMin`, `NMax` and `NClamp` where the profile takes `DriverDeviation::MetalMinMax`
|
||||
/// (the kernels then require `VkProperty::MetalMinMax`), else the operand the module picks
|
||||
/// itself (`math::metal_min_max`).
|
||||
/// Every word of [`MIN_MAX_CASES`] is the Metal row's of the same chip where the profile takes
|
||||
/// `DriverDeviation::MetalMinMax`: the device's `NMin`, `NMax` and `NClamp` (the kernels then
|
||||
/// require `VkProperty::MetalMinMax`). Elsewhere the module emits the same instructions and
|
||||
/// records `native-min-max`, so a differing word is the device's answer, printed, not a failure.
|
||||
#[test]
|
||||
fn minimums_and_maximums_answer_as_metal() {
|
||||
let messages = Messages::default();
|
||||
@@ -1227,7 +1227,7 @@ fn minimums_and_maximums_answer_as_metal() {
|
||||
differ.len(),
|
||||
metal.len() / 4
|
||||
);
|
||||
if !differ.is_empty() {
|
||||
if metals && !differ.is_empty() {
|
||||
failures.push(format!(
|
||||
"{case_name} on {name}: words differ from Metal (word, device, Metal): {:x?}",
|
||||
&differ[..differ.len().min(24)]
|
||||
|
||||
@@ -1822,7 +1822,7 @@ fn measure(runs: &[Run]) {
|
||||
"FRAME-COST {name} {label}: a frame's passes: {:.1} recorded their first instance \
|
||||
inline; not inline for the encoder {:.1}, the layout {:.1}, a memoryless color {:.1}, \
|
||||
a color's actions {:.1} (a DontCare load {:.1}, a reach not shared {:.1}, \
|
||||
a clear to a NaN {:.1}, a resolve {:.1}, a store {:.1}), a texture over a buffer \
|
||||
a resolve {:.1}, a store {:.1}), a texture over a buffer \
|
||||
{:.1}, another attachment kind \
|
||||
{:.1}, a storage color {:.1}, a stand-in {:.1}, a draw {:.1}; {:.1} split instances \
|
||||
recorded inline, {:.1} instances ended unrun; the replays' {:.1} render pass begins \
|
||||
@@ -1834,7 +1834,6 @@ fn measure(runs: &[Run]) {
|
||||
per_frame(|c| c.passes_not_inline_actions),
|
||||
per_frame(|c| c.passes_not_inline_actions_dont_care_load),
|
||||
per_frame(|c| c.passes_not_inline_actions_unequal_reach),
|
||||
per_frame(|c| c.passes_not_inline_actions_nan_clear),
|
||||
per_frame(|c| c.passes_not_inline_actions_resolve),
|
||||
per_frame(|c| c.passes_not_inline_actions_store),
|
||||
per_frame(|c| c.passes_not_inline_buffer_textures),
|
||||
|
||||
@@ -19,17 +19,17 @@
|
||||
//! stored as another NaN is counted apart, not as a failure, where the device announces
|
||||
//! `device-nan-encoding` (the recorded near-equivalent).
|
||||
//!
|
||||
//! The product writes through the storage choice's class (`metal::format::half_storage_class`):
|
||||
//! as computed on MoltenVK (`DriverDeviation::MetalHalfStorageNans`), and its NaN quieted to
|
||||
//! `0x7fc00000` elsewhere (`HalfQuietNan`; ANV then stores `0xfe00` and announces the note), the
|
||||
//! device's conversion rounding every other value; or, on a device not measured to store a
|
||||
//! written `half`'s NaN as its bits, as the bits the shader rounds toward zero, through the
|
||||
//! texture's unsigned integer alias (`StorageImageClass::HalfBits`). A case is held to Metal's
|
||||
//! rounding where the device is measured to make it (`DriverDeviation::MetalHalfStorageWrites`:
|
||||
//! RADV, ANV, NVIDIA's measured GPUs, lavapipe from Mesa 26.0.8 through 26.2.4 and MoltenVK), the
|
||||
//! measurement of the deviation on that device; elsewhere the module records the device's
|
||||
//! conversion (`PrecisionNote::DeviceColorConversion`), and the lane prints the channels that
|
||||
//! differ without holding them.
|
||||
//! The product writes through the storage choice's class (`metal::format::storage_choice`):
|
||||
//! as computed, the device's conversion rounding every value and storing every NaN; or, on a device
|
||||
//! not measured to store a written `half`'s NaN as its bits, as the bits the shader rounds toward
|
||||
//! zero, through the texture's unsigned integer alias (`StorageImageClass::HalfBits`). A case is
|
||||
//! held to Metal's rounding where the device is measured to make it
|
||||
//! (`DriverDeviation::MetalHalfStorageWrites`: RADV, ANV, NVIDIA's measured GPUs, lavapipe from
|
||||
//! Mesa 26.0.8 through 26.2.4 and MoltenVK), the measurement of the deviation on that device;
|
||||
//! elsewhere the module records the device's conversion (`PrecisionNote::DeviceColorConversion`),
|
||||
//! and the lane prints the channels that differ without holding them. A NaN is the device's,
|
||||
//! announced as `device-nan-encoding` where the profile does not take `MetalHalfStorageNans` (ANV
|
||||
//! stores `0xfe00`).
|
||||
|
||||
use super::color_writes::{
|
||||
half, half_toward_zero, specials, unsigned_float, unsigned_float_toward_zero,
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
//! The NaNs of float texels read, sampled and gathered with `half` and `float` results, on the
|
||||
//! device the cfg selects, under the validation layer, under the lane's exact policy, under the
|
||||
//! default one (native device sampling and maths, what a consumer runs) and under the default one
|
||||
//! with the NaN switch on (`NanMinMaxPolicy::Exact`).
|
||||
//! device the cfg selects, under the validation layer, under the lane's exact policy and under the
|
||||
//! default one (native device sampling and maths, what a consumer runs).
|
||||
//!
|
||||
//! What plain Metal answers (our own probe: an Apple M3 Max under macOS 26.7,
|
||||
//! safe and fast math alike, every NaN lane of the eight formats below): a lane is a NaN where a
|
||||
@@ -27,13 +26,11 @@
|
||||
//! texel (native device sampling and texel conversion): its NaN lanes are printed on
|
||||
//! `HALF-TEXEL-RAW` lines, the device's decode itself.
|
||||
//!
|
||||
//! What the switch guarantees on every device, and the test asserts: a `half` result's NaN is
|
||||
//! `0x7e00` wherever Metal's rule does not keep the texel's own bits (a 32-bit float or small
|
||||
//! float texel, a linear sample), printed on a `HALF-TEXEL-SWITCH-BREACH` line where it is not.
|
||||
//! The one-texel accesses of a 16-bit float texel keep the device's decode, Metal's bits only
|
||||
//! where the device widens a half exactly (NVIDIA), and whether a lane is a NaN at all is the
|
||||
//! device's filter's (a zero-weight tap of an infinity or a NaN may make one); both are measured
|
||||
//! and printed, not asserted.
|
||||
//! A NaN's bits are the device's (`device-nan-encoding`, `native-nan-encoding`): Metal's only where
|
||||
//! the device answers them (a 16-bit float texel's one-texel accesses where the device widens a
|
||||
//! half exactly, NVIDIA), and whether a lane is a NaN at all is the device's filter's (a
|
||||
//! zero-weight tap of an infinity or a NaN may make one); both are measured and printed, not
|
||||
//! asserted.
|
||||
//!
|
||||
//! Under every policy a `half` lane whose value is a finite `float` beyond `half`'s range (the
|
||||
//! largest `float`, alone or filtered) is infinity of its sign, or 65504 where the device's
|
||||
@@ -47,7 +44,6 @@ use super::degrade_notices::{counts, on_device_with};
|
||||
use super::{buffer_with, read_buffer, WAIT};
|
||||
use crate::air_library::AirLibrary;
|
||||
use metal2vulkan::bind::SamplerDescriptor;
|
||||
use metal2vulkan::device::NanMinMaxPolicy;
|
||||
use metal2vulkan::metal::{PixelFormat, SamplerAddressMode, SamplerMinMagFilter, TextureUsage};
|
||||
use metal2vulkan::pipeline::{ComputePipelineDescriptor, StageSource};
|
||||
use metal2vulkan_devtools::llvm_assemble_text;
|
||||
@@ -516,10 +512,9 @@ fn is_nan(w: u32, half: bool) -> bool {
|
||||
/// The lanes of every access of [`OPS`], `half` and `float`, to every format of [`FORMATS`] on
|
||||
/// `device` that differ from Metal's NaN answers, printed; under the default policy (`raw`) also
|
||||
/// every NaN lane of a `float` result, the device's decode. Returns the count of differing lanes
|
||||
/// of `half` results and of `float` results, of the `half` NaN lanes that are not `0x7e00`
|
||||
/// where Metal's rule does not keep the texel's own bits (the switch's guarantee, the module
|
||||
/// docs), and of the `half` lanes beyond `half`'s range that are neither infinity nor 65504.
|
||||
fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize, usize) {
|
||||
/// of `half` results and of `float` results, and of the `half` lanes beyond `half`'s range that
|
||||
/// are neither infinity nor 65504.
|
||||
fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize) {
|
||||
let sampler = |filter| {
|
||||
let mut d = SamplerDescriptor::new();
|
||||
d.min_filter = filter;
|
||||
@@ -533,7 +528,7 @@ fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize, usize
|
||||
sampler(SamplerMinMagFilter::Linear),
|
||||
);
|
||||
let name = device.name();
|
||||
let mut totals = (0, 0, 0, 0);
|
||||
let mut totals = (0, 0, 0);
|
||||
for half in [true, false] {
|
||||
let result = if half { "half" } else { "float" };
|
||||
for op in OPS {
|
||||
@@ -547,7 +542,6 @@ fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize, usize
|
||||
let texture = made(device, f);
|
||||
let got = dispatch(device, (&pipeline, op, half), &texture, s);
|
||||
let (mut nans, mut differ) = (0, 0);
|
||||
let own = op.one_texel() && f.kind == Kind::Half;
|
||||
for (x, lanes) in got.iter().enumerate() {
|
||||
for (k, &g) in lanes.iter().enumerate() {
|
||||
let want = metal_nan(f, op, x, k, half);
|
||||
@@ -570,18 +564,9 @@ fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize, usize
|
||||
shown(want)
|
||||
);
|
||||
}
|
||||
if half && !own && is_nan(g, true) && g != 0x7e00 {
|
||||
totals.2 += 1;
|
||||
if leg == "switch" {
|
||||
eprintln!(
|
||||
"HALF-TEXEL-SWITCH-BREACH {leg} {op:?} {:?} texel {x} lane {k}: {g:04x}",
|
||||
f.format
|
||||
);
|
||||
}
|
||||
}
|
||||
if let (true, Some(sign)) = (half, overflows(f, op, x, k)) {
|
||||
if g != sign | 0x7c00 && g != sign | 0x7bff {
|
||||
totals.3 += 1;
|
||||
totals.2 += 1;
|
||||
eprintln!(
|
||||
"HALF-TEXEL-OVERFLOW {leg} {op:?} {:?} texel {x} lane {k}: {g:04x}",
|
||||
f.format
|
||||
@@ -611,30 +596,22 @@ fn measure(device: &Device, leg: &str, raw: bool) -> (usize, usize, usize, usize
|
||||
}
|
||||
|
||||
/// Each device's NaN answers for float texels' reads, samples and gathers, `half` and `float`,
|
||||
/// under the lane's exact policy, the default one, and the default one with the NaN switch on:
|
||||
/// measured and printed, the differing lanes counted. Under the switch every `half` NaN Metal's
|
||||
/// rule does not keep is `0x7e00`.
|
||||
/// under the lane's exact policy and the default one: measured and printed, the differing lanes
|
||||
/// counted.
|
||||
#[test]
|
||||
fn float_texel_nans_by_device_and_policy() {
|
||||
for (leg, default, switch) in [
|
||||
("exact", false, false),
|
||||
("default", true, false),
|
||||
("switch", true, true),
|
||||
] {
|
||||
for (leg, default) in [("exact", false), ("default", true)] {
|
||||
on_device_with(
|
||||
|options| {
|
||||
if default {
|
||||
options.policy = DeviceOptions::default().policy;
|
||||
}
|
||||
if switch {
|
||||
options.policy.nan_and_min_max = NanMinMaxPolicy::Exact;
|
||||
}
|
||||
},
|
||||
|device, messages| {
|
||||
let (h, f, breaches, overflows) = measure(device, leg, default);
|
||||
let (h, f, overflows) = measure(device, leg, default);
|
||||
let announced = counts(&messages.take_notices());
|
||||
eprintln!(
|
||||
"HALF-TEXEL-TOTAL {} {leg}: {h} half lanes differ, {f} float lanes differ, {breaches} half NaNs not 0x7e00 outside a 16-bit one-texel access, {overflows} half lanes beyond half's range neither infinity nor 65504; announced {:?}",
|
||||
"HALF-TEXEL-TOTAL {} {leg}: {h} half lanes differ, {f} float lanes differ, {overflows} half lanes beyond half's range neither infinity nor 65504; announced {:?}",
|
||||
device.name(),
|
||||
announced.keys().map(|k| k.code()).collect::<Vec<_>>()
|
||||
);
|
||||
@@ -643,13 +620,6 @@ fn float_texel_nans_by_device_and_policy() {
|
||||
0,
|
||||
"a half beyond half's range is infinity or 65504 (the HALF-TEXEL-OVERFLOW lines)"
|
||||
);
|
||||
if switch {
|
||||
assert_eq!(
|
||||
breaches,
|
||||
0,
|
||||
"under the NaN switch every half NaN Metal's rule does not keep is 0x7e00 (the HALF-TEXEL-SWITCH-BREACH lines)"
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -13,10 +13,10 @@
|
||||
//! a heap element) each write the `half4` buffer 0 holds at lane `gid` (its bits, [`texel`]) at
|
||||
//! texel `(gid, 0)` of a [`N`] by 1 `Private` texture whose every byte was [`FILL`]. Each
|
||||
//! format's stored words are printed with every lane that differs from Metal's (`in -> stored,
|
||||
//! Metal's`). A 32-bit float channel stores Metal's on every device (the write turns each NaN
|
||||
//! into `0x7fc00000`); a 16-bit or packed float channel stores Metal's on a device with
|
||||
//! `VkProperty::MetalHalfTexelWrites`; and a pipeline whose stores differ announces
|
||||
//! `device-nan-encoding`.
|
||||
//! Metal's`). The write stores the half widened, a NaN's payload in the significand's top bits:
|
||||
//! a 16-bit float channel stores Metal's on a device with `VkProperty::MetalHalfTexelWrites`, a
|
||||
//! 32-bit or packed float channel's NaN is the device's, and a pipeline whose stores differ
|
||||
//! announces `device-nan-encoding`.
|
||||
|
||||
use super::degrade_notices::{counts, on_device_with};
|
||||
use super::{buffer_with, layer_reported_nothing, read_buffer, WAIT};
|
||||
@@ -317,10 +317,10 @@ fn stored(
|
||||
}
|
||||
|
||||
/// Each format's stored words through `write`, `read_write` and `held`, printed with the lanes
|
||||
/// that differ from Metal's (the module docs): none in a 32-bit float channel, none in a 16-bit
|
||||
/// or packed float one on a device with `VkProperty::MetalHalfTexelWrites`; a pipeline whose
|
||||
/// stores differ announces `device-nan-encoding` (at its making, or at the dispatch that binds
|
||||
/// such a texture to a slot of no declared format).
|
||||
/// that differ from Metal's (the module docs): none in a 16-bit float channel on a device with
|
||||
/// `VkProperty::MetalHalfTexelWrites`; a pipeline whose stores differ announces
|
||||
/// `device-nan-encoding` (at its making, or at the dispatch that binds such a texture to a slot of
|
||||
/// no declared format).
|
||||
#[test]
|
||||
fn half_writes_store_their_nans_as_metal_or_announce() {
|
||||
let mut report = Vec::new();
|
||||
@@ -380,9 +380,9 @@ fn half_writes_store_their_nans_as_metal_or_announce() {
|
||||
f.name,
|
||||
differ.len()
|
||||
);
|
||||
// A 32-bit float channel (not the packed word) takes `0x7fc00000` as it is.
|
||||
let float32 = f.word_bytes == 4 && f.format != PixelFormat::RG11B10Float;
|
||||
if float32 || keeps {
|
||||
// A 16-bit float channel stores the half's bits where the device keeps
|
||||
// them.
|
||||
if keeps && f.word_bytes == 2 {
|
||||
assert!(
|
||||
differ.is_empty(),
|
||||
"{access} {}: {} lanes differ from Metal's",
|
||||
|
||||
@@ -112,14 +112,13 @@ fn a_pass_that_does_not_record_inline_counts_the_first_check_that_ruled_it_out()
|
||||
}
|
||||
|
||||
/// The counts of passes kept from recording inline by a color's actions, then by the first
|
||||
/// action ruled out: a `DontCare` load, a reach past the render area not shared, a clear to a
|
||||
/// NaN, a resolve, a store.
|
||||
fn actions_counts(counts: &WorkCounts) -> [u64; 6] {
|
||||
/// action ruled out: a `DontCare` load, a reach past the render area not shared, a resolve, a
|
||||
/// store.
|
||||
fn actions_counts(counts: &WorkCounts) -> [u64; 5] {
|
||||
[
|
||||
counts.passes_not_inline_actions,
|
||||
counts.passes_not_inline_actions_dont_care_load,
|
||||
counts.passes_not_inline_actions_unequal_reach,
|
||||
counts.passes_not_inline_actions_nan_clear,
|
||||
counts.passes_not_inline_actions_resolve,
|
||||
counts.passes_not_inline_actions_store,
|
||||
]
|
||||
@@ -131,14 +130,14 @@ fn actions_counts(counts: &WorkCounts) -> [u64; 6] {
|
||||
/// area of half the texture's side, which Metal's clear of whole 32-pixel tiles reaches past,
|
||||
/// beside a second color loaded, whose texels past the render area Metal keeps (where it is
|
||||
/// alone, the pass records inline over the reach), and a larger texture cleared past a memoryless
|
||||
/// color's side, which sets the render area; an `RGBA16Float` texture cleared to a NaN,
|
||||
/// whose bits the device's clear would not keep; resolved, a single-sampled attachment's texels
|
||||
/// copied into the resolve texture; and stored `DontCare`.
|
||||
/// color's side, which sets the render area; resolved, a single-sampled attachment's texels
|
||||
/// copied into the resolve texture; and stored `DontCare`. An `RGBA16Float` texture cleared to a
|
||||
/// NaN, which the device's clear converts, records inline.
|
||||
#[test]
|
||||
fn a_pass_kept_by_a_color_s_actions_counts_the_first_action_ruled_out() {
|
||||
let (messages, _cache, lane) = lane();
|
||||
let rgba16f = PixelFormat::RGBA16Float;
|
||||
let ran = |descriptor: &RenderPassDescriptor, pf: PixelFormat| -> [u64; 6] {
|
||||
let ran = |descriptor: &RenderPassDescriptor, pf: PixelFormat| -> [u64; 5] {
|
||||
let colors = descriptor
|
||||
.color_attachments
|
||||
.iter()
|
||||
@@ -155,16 +154,12 @@ fn a_pass_kept_by_a_color_s_actions_counts_the_first_action_ruled_out() {
|
||||
let stored = color_pass(&target, None, StoreAction::Store, (0, 0));
|
||||
let mut undefined = stored.clone();
|
||||
undefined.color_attachments[0].load_action = LoadAction::DontCare;
|
||||
assert_eq!(
|
||||
ran(&undefined, RGBA8),
|
||||
[1, 1, 0, 0, 0, 0],
|
||||
"loaded DontCare"
|
||||
);
|
||||
assert_eq!(ran(&undefined, RGBA8), [1, 1, 0, 0, 0], "loaded DontCare");
|
||||
let mut part = stored.clone();
|
||||
(part.render_target_width, part.render_target_height) = (SIZE / 2, SIZE / 2);
|
||||
assert_eq!(
|
||||
ran(&part, RGBA8),
|
||||
[0, 0, 0, 0, 0, 0],
|
||||
[0, 0, 0, 0, 0],
|
||||
"cleared past half its side, alone"
|
||||
);
|
||||
let beside = lane.single(RGBA8);
|
||||
@@ -174,7 +169,7 @@ fn a_pass_kept_by_a_color_s_actions_counts_the_first_action_ruled_out() {
|
||||
loaded.store_action = StoreAction::Store;
|
||||
assert_eq!(
|
||||
ran(&part, RGBA8),
|
||||
[1, 0, 1, 0, 0, 0],
|
||||
[1, 0, 1, 0, 0],
|
||||
"cleared past half its side, beside a color loaded"
|
||||
);
|
||||
// A 64x64 texture cleared over the 4x4 render area of a memoryless color beside it, loaded and
|
||||
@@ -200,13 +195,13 @@ fn a_pass_kept_by_a_color_s_actions_counts_the_first_action_ruled_out() {
|
||||
cleared.store_action = StoreAction::Store;
|
||||
assert_eq!(
|
||||
ran(&past, RGBA8),
|
||||
[1, 0, 1, 0, 0, 0],
|
||||
[1, 0, 1, 0, 0],
|
||||
"cleared past a memoryless color's side"
|
||||
);
|
||||
let half = lane.single(rgba16f);
|
||||
let mut nan = color_pass(&half, None, StoreAction::Store, (0, 0));
|
||||
nan.color_attachments[0].clear_color = ClearColor::new(f64::NAN, 0.0, 0.0, 1.0);
|
||||
assert_eq!(ran(&nan, rgba16f), [1, 0, 0, 1, 0, 0], "cleared to a NaN");
|
||||
assert_eq!(ran(&nan, rgba16f), [0, 0, 0, 0, 0], "cleared to a NaN");
|
||||
let resolve = lane.single(RGBA8);
|
||||
let resolved = color_pass(
|
||||
&target,
|
||||
@@ -214,9 +209,9 @@ fn a_pass_kept_by_a_color_s_actions_counts_the_first_action_ruled_out() {
|
||||
StoreAction::MultisampleResolve,
|
||||
(0, 0),
|
||||
);
|
||||
assert_eq!(ran(&resolved, RGBA8), [1, 0, 0, 0, 1, 0], "resolved");
|
||||
assert_eq!(ran(&resolved, RGBA8), [1, 0, 0, 1, 0], "resolved");
|
||||
let unstored = color_pass(&target, None, StoreAction::DontCare, (0, 0));
|
||||
assert_eq!(ran(&unstored, RGBA8), [1, 0, 0, 0, 0, 1], "stored DontCare");
|
||||
assert_eq!(ran(&unstored, RGBA8), [1, 0, 0, 0, 1], "stored DontCare");
|
||||
drop((target, beside, scratch, wide, half, resolve));
|
||||
quiet(lane, &messages);
|
||||
}
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
//! The device's forms of Metal's maths, through the runtime, on the device the cfg selects, under
|
||||
//! the validation layer, with the NaN and minimum and maximum choice on and off. Every other lane
|
||||
//! takes Metal's answers where a switch keeps them (`candidate::runtime_case::validated_options`
|
||||
//! sets `DevicePolicy::exact_answers`); this one starts from those options. The maths functions,
|
||||
//! divisions and fused multiply-adds (`PrecisionNote::NativeTranscendentals`, `NativeDivision`,
|
||||
//! `NativeFma`) and `dot`, `mix` and `fast::sqrt` (`NativeDot`, `NativeMix`, and
|
||||
//! `NativeTranscendentals` for `fast::sqrt`) are the device's on every device whose functions are
|
||||
//! not Metal's own; the NaN and minimum and maximum (`NanMinMaxPolicy::Native`:
|
||||
//! `NativeNanEncoding`, `NativeMinMax`) are where the choice is on. Under each setting the stage
|
||||
//! records exactly the kinds of the forms it takes (where the device's answer is not Metal's own),
|
||||
//! the pipeline state announces the kinds its stage records, and every thread's answers stay
|
||||
//! within the bounds the kinds record; where the choice is off a NaN product is Metal's canonical
|
||||
//! NaN `0x7fc00000`.
|
||||
//! the validation layer. Every other lane takes Metal's answers where a switch keeps them
|
||||
//! (`candidate::runtime_case::validated_options` sets `DevicePolicy::exact_answers`); this one
|
||||
//! starts from those options. The maths functions, divisions and fused multiply-adds
|
||||
//! (`PrecisionNote::NativeTranscendentals`, `NativeDivision`, `NativeFma`) and `dot`, `mix` and
|
||||
//! `fast::sqrt` (`NativeDot`, `NativeMix`, and `NativeTranscendentals` for `fast::sqrt`) are the
|
||||
//! device's on every device whose functions are not Metal's own, and the NaN and minimum and
|
||||
//! maximum (`NativeNanEncoding`, `NativeMinMax`) on every device not measured to answer Metal's.
|
||||
//! The stage records exactly the kinds of the forms it takes (where the device's answer is not
|
||||
//! Metal's own), the pipeline state announces the kinds its stage records, and every thread's
|
||||
//! answers stay within the bounds the kinds record.
|
||||
//!
|
||||
//! The kernel reads ten `float`s a thread and writes fourteen: `sin` and `cos` of an angle in
|
||||
//! `[-π, π]`, `exp2` of an exponent in `[-10, 10]`, `log2` of a value in `[2^-20, 2^20]`, a
|
||||
@@ -25,7 +23,7 @@ use super::degrade_notices::{counts, on_device_with};
|
||||
use super::{buffer_with, read_buffer, Messages, WAIT};
|
||||
use crate::air_library::AirLibrary;
|
||||
use metal2vulkan::cache::VariantKey;
|
||||
use metal2vulkan::device::{FloatControl, FloatWidth, NanMinMaxPolicy, VkProperty};
|
||||
use metal2vulkan::device::{FloatControl, FloatWidth, VkProperty};
|
||||
use metal2vulkan::error::DriverDeviation;
|
||||
use metal2vulkan::library::Library;
|
||||
use metal2vulkan::pipeline::{ComputePipelineDescriptor, FunctionDescriptor, PrecisionNote};
|
||||
@@ -315,75 +313,39 @@ const NATIVE: [PrecisionNote; 7] = [
|
||||
PrecisionNote::NativeMix,
|
||||
];
|
||||
|
||||
/// Whether a setting turns the NaN and minimum and maximum choice on.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Setting {
|
||||
nan_min_max: bool,
|
||||
}
|
||||
|
||||
/// The choice off and on.
|
||||
const SETTINGS: [Setting; 2] = [
|
||||
Setting { nan_min_max: false },
|
||||
Setting { nan_min_max: true },
|
||||
];
|
||||
|
||||
/// `x` rounded to a `half` to nearest even (a normal `half`'s magnitude).
|
||||
fn to_half(x: f64) -> f64 {
|
||||
let ulp = half_ulp(x);
|
||||
(x / ulp).round_ties_even() * ulp
|
||||
}
|
||||
|
||||
/// Where a thread's answers are not Metal's under `setting` (Metal's own being known exactly where
|
||||
/// the choice is off): Metal's canonical NaN for the product of a NaN.
|
||||
fn not_metal_s(setting: Setting, x: &[f32; IN], r: &[f32; OUT]) -> Vec<String> {
|
||||
let n = x[9];
|
||||
let mut out = Vec::new();
|
||||
let mut want = |what: &str, got: f32, metal: f32| {
|
||||
if got.to_bits() != metal.to_bits() {
|
||||
out.push(format!("{what}: {got:e} for Metal's {metal:e}"));
|
||||
}
|
||||
};
|
||||
if !setting.nan_min_max && n.is_nan() {
|
||||
want("n * b", r[9], f32::from_bits(0x7fc0_0000));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Under each setting, on a device whose `float` functions are not Metal's own, the stage records
|
||||
/// exactly the kinds of the forms it takes: the maths functions `NativeTranscendentals` and
|
||||
/// `NativeDivision` (and `NativeFma` where an `fma` takes the device's `Fma`), `NativeDot`,
|
||||
/// `NativeMix` and `NativeTranscendentals` (`fast::sqrt`), and with the NaN and minimum and maximum
|
||||
/// on `NativeNanEncoding` (on a device whose arithmetic is not measured to answer Metal's canonical
|
||||
/// NaN) and `NativeMinMax`; the pipeline state announces each native kind of its stage once; every
|
||||
/// thread's answers are within the bounds their kinds record, and Metal's where the choice is off.
|
||||
/// On MoltenVK, whose functions, minimum and maximum, and NaNs are Metal's own, the stage records
|
||||
/// none of them under any setting and announces none. The device announces
|
||||
/// `float-tininess-after-rounding` as it is made, exactly off MoltenVK.
|
||||
/// On a device whose `float` functions are not Metal's own, the stage records exactly the kinds of
|
||||
/// the forms it takes: the maths functions `NativeTranscendentals` and `NativeDivision` (and
|
||||
/// `NativeFma` where an `fma` takes the device's `Fma`), `NativeDot`, `NativeMix` and
|
||||
/// `NativeTranscendentals` (`fast::sqrt`), and `NativeMinMax` where the device is not measured to
|
||||
/// answer Metal's operand; and `NativeNanEncoding` wherever the device is not measured to answer
|
||||
/// Metal's canonical NaN (on one measured to, it records the note where the kernel computes another
|
||||
/// of Metal's NaNs). The pipeline state announces each native kind of its stage once, and every
|
||||
/// thread's answers are within the bounds their kinds record. On MoltenVK, whose functions and
|
||||
/// minimum and maximum are Metal's own, the stage records none of their kinds and announces none.
|
||||
/// The device announces `float-tininess-after-rounding` as it is made, exactly off MoltenVK.
|
||||
#[test]
|
||||
fn each_choice_answers_within_its_recorded_bounds_on_and_metal_s_off() {
|
||||
fn native_maths_answers_within_its_recorded_bounds() {
|
||||
let bitcode = llvm_assemble_text(&kernel()).unwrap();
|
||||
for setting in SETTINGS {
|
||||
on_device_with(
|
||||
|options| {
|
||||
if setting.nan_min_max {
|
||||
options.policy.nan_and_min_max = NanMinMaxPolicy::Native;
|
||||
}
|
||||
},
|
||||
|device, messages| answers_under(device, messages, setting, &bitcode),
|
||||
);
|
||||
}
|
||||
on_device_with(
|
||||
|_| {},
|
||||
|device, messages| answers_under(device, messages, &bitcode),
|
||||
);
|
||||
}
|
||||
|
||||
/// [`each_choice_answers_within_its_recorded_bounds_on_and_metal_s_off`] under `setting`, on
|
||||
/// `device`, made with it.
|
||||
fn answers_under(device: &Device, messages: &Messages, setting: Setting, bitcode: &[u8]) {
|
||||
let name = format!("{} {setting:?}", device.name());
|
||||
/// [`native_maths_answers_within_its_recorded_bounds`] on `device`.
|
||||
fn answers_under(device: &Device, messages: &Messages, bitcode: &[u8]) {
|
||||
let name = device.name().to_string();
|
||||
let expected = stage_kinds(device, bitcode);
|
||||
let compile = device.compile_device();
|
||||
let takes = |d| compile.profile().takes_driver_deviation(d);
|
||||
let metals = takes(DriverDeviation::MetalFloatFunctions);
|
||||
eprintln!("{name}: Metal's own functions {metals}; native kinds {expected:?}");
|
||||
let Setting { nan_min_max } = setting;
|
||||
// The constructor checked the creation notices against `creation_kinds`: the device's
|
||||
// multiply and fused multiply-add, announced as it was made.
|
||||
assert_eq!(
|
||||
@@ -398,16 +360,16 @@ fn answers_under(device: &Device, messages: &Messages, setting: Setting, bitcode
|
||||
(PrecisionNote::NativeMix, !metals),
|
||||
(
|
||||
PrecisionNote::NativeMinMax,
|
||||
nan_min_max && !metals && !takes(DriverDeviation::MetalMinMax),
|
||||
),
|
||||
(
|
||||
PrecisionNote::NativeNanEncoding,
|
||||
nan_min_max && !takes(DriverDeviation::MetalCanonicalNans),
|
||||
!metals && !takes(DriverDeviation::MetalMinMax),
|
||||
),
|
||||
] {
|
||||
let kind = Degradation::from_precision_note(note);
|
||||
assert_eq!(expected.contains(&kind), native, "{name}: {kind:?}");
|
||||
}
|
||||
if !takes(DriverDeviation::MetalCanonicalNans) {
|
||||
let kind = Degradation::from_precision_note(PrecisionNote::NativeNanEncoding);
|
||||
assert!(expected.contains(&kind), "{name}: {kind:?}");
|
||||
}
|
||||
|
||||
let library = device.new_library_with_air(bitcode).unwrap();
|
||||
let function = library.new_function_with_name("nm").unwrap();
|
||||
@@ -470,17 +432,12 @@ fn answers_under(device: &Device, messages: &Messages, setting: Setting, bitcode
|
||||
.enumerate()
|
||||
{
|
||||
failures.extend(broken(x, r).into_iter().map(|f| format!("thread {i}: {f}")));
|
||||
failures.extend(
|
||||
not_metal_s(setting, x, r)
|
||||
.into_iter()
|
||||
.map(|f| format!("thread {i}: {f}")),
|
||||
);
|
||||
let [_, _, _, a, b, ..] = x.map(f64::from);
|
||||
correctly_rounded += u32::from(r[4] == (a / b) as f32);
|
||||
}
|
||||
eprintln!(
|
||||
"{name}: {} answers break a bound or Metal's; {correctly_rounded} of {COUNT} quotients \
|
||||
correctly rounded",
|
||||
"{name}: {} answers break a bound; {correctly_rounded} of {COUNT} quotients correctly \
|
||||
rounded",
|
||||
failures.len()
|
||||
);
|
||||
assert!(
|
||||
|
||||
@@ -26,8 +26,9 @@
|
||||
//! A case with no current Metal row (one awaiting Metal qualification) goes the same way, and
|
||||
//! says so.
|
||||
//! - **Clears** write Metal's measured bytes: each color format, depth and stencil value an M4 was
|
||||
//! measured with, the NaNs of half, small-float and float formats among them (a Metal probe, the
|
||||
//! M3 Max alike). A format the device cannot render is counted.
|
||||
//! measured with, the NaNs of float formats among them (a Metal probe, the M3 Max alike); a NaN
|
||||
//! of a half-float or small-float format is the device's conversion, announced. A format the
|
||||
//! device cannot render is counted.
|
||||
//! - **Load and store actions**, the encoder's late store action, the passes' order against blits
|
||||
//! in one command buffer, and Metal's refusals of passes and draws, typed. What a `DontCare`
|
||||
//! load or store leaves is printed: Metal leaves it undefined, and Apple's GPU keeps the old
|
||||
@@ -44,22 +45,19 @@ use crate::candidate::engine::{linked_modules, LinkedModule, ENGINE_EXECUTOR_ABI
|
||||
use crate::candidate::runtime_case::{
|
||||
commit_render, render_pipeline_descriptor, render_pipeline_state, RenderInputs, TemplateState,
|
||||
};
|
||||
use crate::candidate::runtime_samples::encode as samples_of;
|
||||
use crate::candidate::tests::engine_render;
|
||||
use crate::case::{AuthoredCase, Stage};
|
||||
use crate::check::interface::AirInterface;
|
||||
use crate::executor_contract::multisample::{ReadbackView, SampleRead};
|
||||
use crate::gpu::TEST_DEVICE;
|
||||
use crate::store::CorpusStore;
|
||||
use metal2vulkan::bind::StatusReport;
|
||||
use metal2vulkan::error::RuntimeDriverDefect;
|
||||
use metal2vulkan::metal::{IndexType, PixelFormat, PrimitiveType, TextureType, TextureUsage};
|
||||
use metal2vulkan::metal::{IndexType, PixelFormat, PrimitiveType, TextureUsage};
|
||||
use metal2vulkan::pipeline::RenderPipelineDescriptor;
|
||||
use metal2vulkan_runtime::{
|
||||
AppleOnly, Attachment, BlitOption, Buffer, ClearColor, CommandBuffer, CommandBufferStatus,
|
||||
Device, DrawProblem, Error, Invalid, LoadAction, Origin, Problem, Region, RenderCommandEncoder,
|
||||
RenderPassDescriptor, RenderPassProblem, ResourceOptions, Size, StoreAction, Texture,
|
||||
TextureDescriptor,
|
||||
Degradation, Device, DrawProblem, Error, Invalid, LoadAction, Origin, Problem, Region,
|
||||
RenderCommandEncoder, RenderPassDescriptor, RenderPassProblem, ResourceOptions, Size,
|
||||
StoreAction, Texture, TextureDescriptor,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
@@ -835,15 +833,15 @@ pub(super) fn small_nan(channel: u32, exponent: u32, mantissa: u32) -> bool {
|
||||
(channel >> mantissa) & all == all && channel & ((1 << mantissa) - 1) != 0
|
||||
}
|
||||
|
||||
/// Each channel of a `pf` texel (`RGBA16Float`'s four halves, `RG11B10Float`'s three fields) as
|
||||
/// its bits, its exponent's width and its mantissa's.
|
||||
/// Each channel of a `pf` texel (a half-float format's halves, `RG11B10Float`'s three fields) as
|
||||
/// its bits, its exponent's width and its mantissa's; empty for another format.
|
||||
fn channels(pf: PixelFormat, texel: &[u8]) -> Vec<(u32, u32, u32)> {
|
||||
match pf {
|
||||
PixelFormat::RGBA16Float => texel
|
||||
PixelFormat::R16Float | PixelFormat::RG16Float | PixelFormat::RGBA16Float => texel
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|h| (u32::from(u16::from_le_bytes([h[0], h[1]])) & 0x7fff, 5, 10))
|
||||
.map(|h| (u32::from(u16::from_le_bytes([h[0], h[1]])), 5, 10))
|
||||
.collect(),
|
||||
PixelFormat::RG11B10Float => {
|
||||
let word = u32::from_le_bytes([texel[0], texel[1], texel[2], texel[3]]);
|
||||
@@ -857,408 +855,29 @@ fn channels(pf: PixelFormat, texel: &[u8]) -> Vec<(u32, u32, u32)> {
|
||||
}
|
||||
}
|
||||
|
||||
/// A NaN clear: its format and color, the texel where Metal drops a `half` NaN's sign, and the
|
||||
/// one where it keeps it ([`NAN_CLEARS`]).
|
||||
type NanClear = (PixelFormat, [f64; 4], &'static [u8], &'static [u8]);
|
||||
|
||||
/// Metal's NaN clears by format and clear color (an M4 under macOS 27.0.1; a Metal probe; the
|
||||
/// consumer's M3 Max alike at 4x4): the texel a level stores in its texels or every sample where
|
||||
/// Metal drops a `half` NaN's sign and payload (an uncompressed texture, or a level under 16 texels
|
||||
/// a side), then where it keeps them.
|
||||
const NAN_CLEARS: &[NanClear] = &[
|
||||
(
|
||||
PixelFormat::RGBA16Float,
|
||||
[f64::NAN, 1.0, 0.5, f64::NAN],
|
||||
&[0x00, 0x7e, 0x00, 0x3c, 0x00, 0x38, 0x00, 0x7e],
|
||||
&[0x00, 0x7e, 0x00, 0x3c, 0x00, 0x38, 0x00, 0x7e],
|
||||
),
|
||||
(
|
||||
PixelFormat::RGBA16Float,
|
||||
[-f64::NAN, -f64::NAN, -f64::NAN, -f64::NAN],
|
||||
&[0x00, 0x7e, 0x00, 0x7e, 0x00, 0x7e, 0x00, 0x7e],
|
||||
&[0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe, 0x00, 0xfe],
|
||||
),
|
||||
(
|
||||
PixelFormat::RGBA16Float,
|
||||
[f64::NAN, 1.0, 0.5, -f64::NAN],
|
||||
&[0x00, 0x7e, 0x00, 0x3c, 0x00, 0x38, 0x00, 0x7e],
|
||||
&[0x00, 0x7e, 0x00, 0x3c, 0x00, 0x38, 0x00, 0xfe],
|
||||
),
|
||||
(
|
||||
PixelFormat::R16Float,
|
||||
[-f64::NAN, 0.0, 0.0, 0.0],
|
||||
&[0x00, 0x7e],
|
||||
&[0x00, 0xfe],
|
||||
),
|
||||
(
|
||||
PixelFormat::RGBA16Float,
|
||||
[
|
||||
f64::from_bits(0x7ffc_0000_0000_0000),
|
||||
1.0,
|
||||
f64::from_bits(0x7ff4_0000_0000_0000),
|
||||
f64::from_bits(0xffff_ffff_ffff_ffff),
|
||||
],
|
||||
&[0x00, 0x7e, 0x00, 0x3c, 0x00, 0x7e, 0x00, 0x7e],
|
||||
&[0x00, 0x7f, 0x00, 0x3c, 0x00, 0x7f, 0xff, 0xff],
|
||||
),
|
||||
(
|
||||
PixelFormat::RG11B10Float,
|
||||
[f64::NAN, 1.0, 0.5, f64::NAN],
|
||||
&[0xe0, 0x07, 0x1e, 0x70],
|
||||
&[0xe0, 0x07, 0x1e, 0x70],
|
||||
),
|
||||
(
|
||||
PixelFormat::RG11B10Float,
|
||||
[f64::NAN, f64::NAN, f64::NAN, f64::NAN],
|
||||
&[0xe0, 0x07, 0x3f, 0xfc],
|
||||
&[0xe0, 0x07, 0x3f, 0xfc],
|
||||
),
|
||||
(
|
||||
PixelFormat::R32Float,
|
||||
[f64::from_bits(0x7ff0_0000_2000_0000), 0.0, 0.0, 0.0],
|
||||
&[0x01, 0x00, 0xc0, 0x7f],
|
||||
&[0x01, 0x00, 0xc0, 0x7f],
|
||||
),
|
||||
(
|
||||
PixelFormat::R32Float,
|
||||
[-f64::NAN, 0.0, 0.0, 0.0],
|
||||
&[0x00, 0x00, 0xc0, 0xff],
|
||||
&[0x00, 0x00, 0xc0, 0xff],
|
||||
),
|
||||
];
|
||||
|
||||
/// `texel` with each NaN channel as Metal's 4x resolve makes it where it drops the clear's NaN
|
||||
/// (a level whose clear drops a `half` NaN's sign): zero in a small-float channel, and
|
||||
/// `0x7fc00000` in a 32-bit float one.
|
||||
fn nans_resolved(pf: PixelFormat, texel: &[u8]) -> Vec<u8> {
|
||||
match pf {
|
||||
PixelFormat::R32Float => texel
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
/// Whether texel `got` of `pf` differs from `want` only by one NaN for another in a half-float or
|
||||
/// small-float channel: the device's conversion of a NaN clear (`device-nan-encoding`).
|
||||
fn nan_for_nan(pf: PixelFormat, got: &[u8], want: &[u8]) -> bool {
|
||||
let (got, want) = (channels(pf, got), channels(pf, want));
|
||||
!want.is_empty()
|
||||
&& got.len() == want.len()
|
||||
&& got
|
||||
.iter()
|
||||
.flat_map(
|
||||
|f| match f32::from_le_bytes([f[0], f[1], f[2], f[3]]).is_nan() {
|
||||
true => 0x7fc0_0000u32.to_le_bytes(),
|
||||
false => [f[0], f[1], f[2], f[3]],
|
||||
},
|
||||
)
|
||||
.collect(),
|
||||
PixelFormat::RGBA16Float | PixelFormat::R16Float => texel
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.flat_map(|h| {
|
||||
match small_nan(u32::from(u16::from_le_bytes([h[0], h[1]])) & 0x7fff, 5, 10) {
|
||||
true => [0, 0],
|
||||
false => [h[0], h[1]],
|
||||
}
|
||||
})
|
||||
.collect(),
|
||||
PixelFormat::RG11B10Float => {
|
||||
let word = u32::from_le_bytes([texel[0], texel[1], texel[2], texel[3]]);
|
||||
let fields = [(0, 11, 6), (11, 11, 6), (22, 10, 5)];
|
||||
let kept = fields.iter().fold(0u32, |out, &(at, width, mantissa)| {
|
||||
let field = (word >> at) & ((1 << width) - 1);
|
||||
match small_nan(field, 5, mantissa) {
|
||||
true => out,
|
||||
false => out | (field << at),
|
||||
}
|
||||
});
|
||||
kept.to_le_bytes().to_vec()
|
||||
}
|
||||
_ => texel.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A NaN `Clear` of a new `Private` attachment (`nan_clear.rs`) of 4x4, 16x16 and 64x64, 1x and
|
||||
/// 4x, plain (a usage Metal compresses) and with `PixelFormatView` usage (kept uncompressed),
|
||||
/// in a pass without a draw call, in one whose draw (`rt6_restart`, `clear_reach::Lane`) lies
|
||||
/// wholly off the target, and in one whose only draw call draws no vertices, stores Metal's texel
|
||||
/// ([`NAN_CLEARS`]): the one with a `half` NaN's sign where Metal keeps it, at a plain level of 16
|
||||
/// or more in a pass without a draw call, and without it elsewhere (a draw call of no vertices is
|
||||
/// a draw call: the consumer's M3 Max, `R32Float`, `RG32Float` and `RGBA32Float` at 2 and 4
|
||||
/// samples, 16 a side, cleared to `-NaN`, resolves `0x7fc00000`). A 1x attachment is read whole by a blit. Each sample of a 4x one
|
||||
/// is read through an unsigned view of its texel size where its format has one (`RGBA16Float`,
|
||||
/// `R16Float` and `R32Float`, `runtime_samples::encode`): its own with `PixelFormatView` usage,
|
||||
/// else a same-format copy's with it (Metal's and the devices' copies keep every sample's bits, but
|
||||
/// for a device whose multisampled copies convert float NaNs, `MultisampledCopiesConvertFloatNans`,
|
||||
/// on which a copy's samples are left unread). Every 4x one is resolved into a new plain 1x texture
|
||||
/// read by a blit. In a pass without a draw call Metal's resolve keeps the texel where it keeps the
|
||||
/// sign and stores zero in each small-float NaN channel and `0x7fc00000` in each 32-bit float one
|
||||
/// elsewhere, which the runtime writes on every device (an `R32Float` clear is Metal's conversion
|
||||
/// of the double at every level); so does one whose draw calls draw nothing, its resolve then
|
||||
/// Metal's texel without the sign. In a pass with a draw Metal's resolve averages the samples, each
|
||||
/// NaN zero: a device's resolve whose NaN channels differ only so is its resolve rule, printed
|
||||
/// (`device-rounded-resolve`), not this clear's. A `BGR10_XR` NaN clear is printed beside them, or
|
||||
/// the device's refusal of the format. Each prints `MSAA-NAN-CLEAR`.
|
||||
#[test]
|
||||
fn multisampled_nan_clears_store_metal_s_texel() {
|
||||
let (messages, cache, lane) = super::clear_reach::lane();
|
||||
let device = &lane.device;
|
||||
let name = device.name().to_owned();
|
||||
let xr: &[NanClear] = &[(PixelFormat::BGR10XR, [f64::NAN, 0.5, 1.0, 1.0], &[], &[])];
|
||||
// A triangle wholly off the target, the vertex function's positions.
|
||||
let off: Vec<u8> = [2.0f32, 2.0, 3.0, 2.0, 2.0, 3.0]
|
||||
.iter()
|
||||
.flat_map(|v| v.to_le_bytes())
|
||||
.collect();
|
||||
let off = buffer_with(device, &off).unwrap();
|
||||
let (mut wrong, mut checked) = (Vec::new(), 0usize);
|
||||
// A device whose multisampled copies convert float NaNs (RADV) cannot copy the samples of an
|
||||
// attachment without `PixelFormatView` usage out to be read.
|
||||
let copies_convert = device
|
||||
.properties()
|
||||
.driver_defects
|
||||
.contains(&RuntimeDriverDefect::MultisampledCopiesConvertFloatNans);
|
||||
for &(pf, color, small, large) in NAN_CLEARS.iter().chain(xr) {
|
||||
let bytes = match pf {
|
||||
PixelFormat::RGBA16Float => 8,
|
||||
PixelFormat::R16Float => 2,
|
||||
_ => 4,
|
||||
};
|
||||
let view = match pf {
|
||||
PixelFormat::RGBA16Float => Some(ReadbackView::Rg32Uint),
|
||||
PixelFormat::R16Float => Some(ReadbackView::R16Uint),
|
||||
PixelFormat::R32Float => Some(ReadbackView::R32Uint),
|
||||
_ => None,
|
||||
};
|
||||
let measured = !small.is_empty();
|
||||
for (side, samples, viewed, drawn) in [4u32, 16, 64]
|
||||
.into_iter()
|
||||
.flat_map(|side| [(side, 1u64), (side, 2), (side, 4)])
|
||||
.flat_map(|(side, samples)| [(side, samples, false), (side, samples, true)])
|
||||
.flat_map(|(side, samples, viewed)| {
|
||||
[Drawn::No, Drawn::OffTarget, Drawn::Nothing]
|
||||
.map(|drawn| (side, samples, viewed, drawn))
|
||||
})
|
||||
.filter(|&(_, _, _, drawn)| measured || drawn == Drawn::No)
|
||||
{
|
||||
let usage = TextureUsage::RENDER_TARGET | TextureUsage::SHADER_READ;
|
||||
let new = |samples: u64, viewed: bool| {
|
||||
let mut descriptor =
|
||||
TextureDescriptor::texture_2d(pf, side.into(), side.into(), false);
|
||||
if samples > 1 {
|
||||
descriptor.texture_type = TextureType::Type2DMultisample;
|
||||
descriptor.sample_count = samples;
|
||||
}
|
||||
descriptor.usage = match viewed {
|
||||
true => usage | TextureUsage::PIXEL_FORMAT_VIEW,
|
||||
false => usage,
|
||||
};
|
||||
descriptor.resource_options = ResourceOptions::private();
|
||||
device.new_texture(&descriptor)
|
||||
};
|
||||
let label = format!(
|
||||
"{pf:?} {color:?} {samples}x {side}x{side}{}{}",
|
||||
if viewed { " PixelFormatView" } else { "" },
|
||||
match drawn {
|
||||
Drawn::No => "",
|
||||
Drawn::OffTarget => " drawn off the target",
|
||||
Drawn::Nothing => " a draw call of no vertices",
|
||||
}
|
||||
);
|
||||
let texture = match new(samples, viewed) {
|
||||
Ok(texture) => texture,
|
||||
Err(Error::Unsupported(why)) => {
|
||||
println!("MSAA-NAN-CLEAR {label} on {name}: unsupported {why:?}");
|
||||
continue;
|
||||
}
|
||||
Err(error) => panic!("{label}: {error}"),
|
||||
};
|
||||
let resolved = (samples > 1).then(|| {
|
||||
attachment(
|
||||
device,
|
||||
pf,
|
||||
[side.into(), side.into()],
|
||||
ResourceOptions::private(),
|
||||
)
|
||||
.unwrap()
|
||||
});
|
||||
let mut pass = RenderPassDescriptor::new();
|
||||
let target = &mut pass.color_attachments[0];
|
||||
target.texture = Some(texture.clone());
|
||||
target.load_action = LoadAction::Clear;
|
||||
target.store_action = match &resolved {
|
||||
Some(resolved) => {
|
||||
target.resolve_texture = Some(resolved.clone());
|
||||
StoreAction::StoreAndMultisampleResolve
|
||||
}
|
||||
None => StoreAction::Store,
|
||||
};
|
||||
let [red, green, blue, alpha] = color;
|
||||
target.clear_color = ClearColor::new(red, green, blue, alpha);
|
||||
let pipeline =
|
||||
(drawn != Drawn::No).then(|| lane.pipeline(&[pf], (None, None), samples));
|
||||
let command_buffer = lane.queue.command_buffer().unwrap();
|
||||
let encoded = command_buffer
|
||||
.render_command_encoder(&pass)
|
||||
.and_then(|mut encoder| {
|
||||
if let Some(pipeline) = &pipeline {
|
||||
encoder.set_render_pipeline_state(pipeline)?;
|
||||
encoder.set_vertex_buffer(Some(&off), 0, 0)?;
|
||||
let vertices = match drawn {
|
||||
Drawn::Nothing => 0,
|
||||
_ => 3,
|
||||
};
|
||||
encoder.draw_primitives(PrimitiveType::Triangle, 0, vertices, 1, 0)?;
|
||||
}
|
||||
encoder.end_encoding()
|
||||
});
|
||||
match encoded {
|
||||
Ok(()) => {}
|
||||
// A device that cannot render the format refuses the pass (`BGR10_XR` on x86
|
||||
// lavapipe and on MoltenVK).
|
||||
Err(Error::Unsupported(why)) => {
|
||||
println!("MSAA-NAN-CLEAR {label} on {name}: unsupported {why:?}");
|
||||
continue;
|
||||
}
|
||||
Err(error) => {
|
||||
println!("MSAA-NAN-CLEAR {label} on {name}: refused {error:?}");
|
||||
wrong.push(format!("{label}: refused {error:?}"));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// The samples, through the unsigned view of a texture with `PixelFormatView` usage:
|
||||
// the attachment's own, or a copy's.
|
||||
let read = match (samples > 1, view) {
|
||||
(true, Some(_)) if !viewed && copies_convert => None,
|
||||
(true, Some(view)) => {
|
||||
let readable = match viewed {
|
||||
true => texture.clone(),
|
||||
false => {
|
||||
let copy = new(samples, true).unwrap();
|
||||
let mut blit = command_buffer.blit_command_encoder().unwrap();
|
||||
blit.copy_texture(&texture, ©).unwrap();
|
||||
blit.end_encoding().unwrap();
|
||||
copy
|
||||
}
|
||||
};
|
||||
Some(
|
||||
samples_of(
|
||||
device,
|
||||
&command_buffer,
|
||||
&readable,
|
||||
SampleRead::Color(view),
|
||||
[side, side],
|
||||
samples as u32,
|
||||
)
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
run(&command_buffer);
|
||||
let distinct = |all: &[u8]| {
|
||||
let mut seen: Vec<Vec<u8>> = Vec::new();
|
||||
for texel in all.chunks_exact(bytes) {
|
||||
if !seen.iter().any(|s| s == texel) {
|
||||
seen.push(texel.to_vec());
|
||||
}
|
||||
}
|
||||
seen
|
||||
};
|
||||
let stored = distinct(&blit_read(
|
||||
device,
|
||||
resolved.as_ref().unwrap_or(&texture),
|
||||
bytes as u64,
|
||||
));
|
||||
let sampled = read.map(|read| distinct(&read.bytes().unwrap()));
|
||||
let sampled_line = match &sampled {
|
||||
Some(sampled) => format!(" samples {sampled:02x?}"),
|
||||
None if samples > 1 && view.is_some() => {
|
||||
" samples unread (the device's copy converts NaNs)".to_owned()
|
||||
}
|
||||
None => String::new(),
|
||||
};
|
||||
let what = if samples > 1 { "resolved" } else { "stored" };
|
||||
if !measured {
|
||||
println!(
|
||||
"MSAA-NAN-CLEAR {label} on {name}:{sampled_line} {what} {stored:02x?} \
|
||||
(printed: no measured Metal texel)"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
checked += 1;
|
||||
let signed = side >= 16 && !viewed && drawn == Drawn::No;
|
||||
let texel = if signed { large } else { small };
|
||||
let samples_exact = sampled.iter().flatten().all(|sample| sample == texel);
|
||||
let verdict = if samples == 1 {
|
||||
match stored.iter().all(|got| got == texel) {
|
||||
true => Ok("Metal's texel".to_owned()),
|
||||
false => Err(()),
|
||||
}
|
||||
} else {
|
||||
let metal = match signed {
|
||||
true => texel.to_vec(),
|
||||
false => nans_resolved(pf, texel),
|
||||
};
|
||||
// A resolve keeping or dropping a NaN, of any bits, beside Metal's other channels.
|
||||
let resolve_rule = |got: &[u8]| {
|
||||
nans_resolved(pf, got) == nans_resolved(pf, texel)
|
||||
&& channels(pf, got).iter().zip(channels(pf, texel)).all(
|
||||
|(&(g, e, m), (t, _, _))| match small_nan(t, e, m) {
|
||||
true => g == 0 || small_nan(g, e, m),
|
||||
false => g == t,
|
||||
},
|
||||
)
|
||||
};
|
||||
match (samples_exact, stored.iter().all(|got| *got == metal)) {
|
||||
(true, true) => Ok("Metal's texel, Metal's resolve".to_owned()),
|
||||
(true, false)
|
||||
if drawn == Drawn::OffTarget
|
||||
&& stored.iter().all(|got| resolve_rule(got)) =>
|
||||
{
|
||||
Ok(format!(
|
||||
"Metal's texel; the device's resolve rule, Metal's resolve \
|
||||
{metal:02x?}"
|
||||
))
|
||||
}
|
||||
_ => Err(()),
|
||||
}
|
||||
};
|
||||
match verdict {
|
||||
Ok(verdict) => println!(
|
||||
"MSAA-NAN-CLEAR {label} on {name}:{sampled_line} {what} {stored:02x?}: {verdict}"
|
||||
),
|
||||
Err(()) => {
|
||||
println!(
|
||||
"MSAA-NAN-CLEAR {label} on {name}:{sampled_line} {what} {stored:02x?}: \
|
||||
WRONG, Metal {texel:02x?}"
|
||||
);
|
||||
wrong.push(format!(
|
||||
"{label}:{sampled_line} {what} {stored:02x?}, Metal {texel:02x?}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
println!("MSAA-NAN-CLEAR {checked} cases checked on {name}");
|
||||
drop(off);
|
||||
drop(lane);
|
||||
drop(cache);
|
||||
let _ = messages.take_notices();
|
||||
assert!(wrong.is_empty(), "{wrong:#?}");
|
||||
}
|
||||
|
||||
/// What a pass of [`multisampled_nan_clears_store_metal_s_texel`] draws.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum Drawn {
|
||||
/// No draw call.
|
||||
No,
|
||||
/// A triangle wholly off the target.
|
||||
OffTarget,
|
||||
/// A draw call of no vertices.
|
||||
Nothing,
|
||||
.zip(&want)
|
||||
.all(|(&(g, e, m), &(w, _, _))| g == w || (small_nan(g, e, m) && small_nan(w, e, m)))
|
||||
}
|
||||
|
||||
/// Each color clear Metal was measured with stores Metal's bytes, depth and stencil clears
|
||||
/// included; a format the device cannot render to is counted, not run.
|
||||
/// included, but a NaN of a half-float or small-float channel, which the device's clear converts as
|
||||
/// it likes, announced (`device-nan-encoding`) and printed; a format the device cannot render to is
|
||||
/// counted, not run.
|
||||
#[test]
|
||||
fn clears_store_the_bytes_metal_stores() {
|
||||
let messages = Messages::default();
|
||||
let cache = ScratchCache::new().unwrap();
|
||||
let device = validated_device(TEST_DEVICE, &messages, cache.path()).unwrap();
|
||||
let (mut checked, mut unsupported, mut wrong) = (0usize, Vec::new(), Vec::new());
|
||||
let mut announced = false;
|
||||
for &(pf, color, expected) in COLOR_CLEARS {
|
||||
let texture = match attachment(&device, pf, [1, 1], ResourceOptions::private()) {
|
||||
Ok(texture) => texture,
|
||||
@@ -1278,7 +897,15 @@ fn clears_store_the_bytes_metal_stores() {
|
||||
Err(error) => panic!("{pf:?}: {error}"),
|
||||
}
|
||||
let bytes = blit_read(&device, &texture, expected.len() as u64);
|
||||
if bytes != expected {
|
||||
announced |= super::degrade_notices::counts(&messages.take_notices())
|
||||
.contains_key(&Degradation::DeviceNanEncoding);
|
||||
if bytes != expected && announced && nan_for_nan(pf, &bytes, expected) {
|
||||
eprintln!(
|
||||
"clear {pf:?} {color:?} on {}: {bytes:02x?}, Metal {expected:02x?} \
|
||||
(device-nan-encoding)",
|
||||
device.name()
|
||||
);
|
||||
} else if bytes != expected {
|
||||
wrong.push(format!(
|
||||
"{pf:?} {color:?}: {bytes:02x?}, Metal {expected:02x?}"
|
||||
));
|
||||
|
||||
@@ -1718,11 +1718,10 @@ fn plan(p: &RenderPipeline, device: &Device, shape: &BindShape) -> Result<Bindin
|
||||
class: SlotClass::Texture,
|
||||
..
|
||||
}) => return Err(not_implemented(Feature::TexelBuffer)),
|
||||
// A storage texture's level count, and whether its channels are 16-bit floats,
|
||||
// which the resource plan records; and a value the bound resources decide, which
|
||||
// the plan records too (`slots::record_specialized`).
|
||||
// A storage texture's level count and integer channel widths, which the resource
|
||||
// plan records; and a value the bound resources decide, which the plan records too
|
||||
// (`slots::record_specialized`).
|
||||
PushField::TextureLevels(_)
|
||||
| PushField::TextureHalfChannels(_)
|
||||
| PushField::TextureIntegerChannels(_)
|
||||
| PushField::Specialized(_) => {}
|
||||
// A structure's instance count, which instantiation reads from the state.
|
||||
|
||||
@@ -434,18 +434,14 @@ fn member_view(
|
||||
// every access the device lets a heap make.
|
||||
let use_ = heap_storage_use(profile);
|
||||
let c = storage_choice(pixel_format, use_, profile).map_err(bind_error)?;
|
||||
// The class's one formatless declaration cannot convert per element, but for a
|
||||
// half-float format's NaN, which a heap write takes from the class its handle carries:
|
||||
// such a member is viewed through its own format.
|
||||
// The class's one formatless declaration cannot convert per element: a member is viewed
|
||||
// through its own format.
|
||||
let per_element = matches!(
|
||||
c.class,
|
||||
StorageImageClass::Identity
|
||||
| StorageImageClass::HalfQuietNan
|
||||
| StorageImageClass::SmallFloatQuietNan
|
||||
| StorageImageClass::HalfBits
|
||||
StorageImageClass::Identity | StorageImageClass::HalfBits
|
||||
);
|
||||
// A half-float member's writes take the class its handle carries, as before: the alias
|
||||
// a slot only written takes (`StorageImageClass::HalfBits`) is a slot's alone.
|
||||
// A half-float member's writes are the device's conversion's, as an `Identity` member's:
|
||||
// the alias a slot only written takes (`StorageImageClass::HalfBits`) is a slot's alone.
|
||||
let aliased = c.alias.is_some() && c.class != StorageImageClass::HalfBits;
|
||||
// An `A8Unorm` texture held in red (`StorageImageClass::AlphaInRed`): its `R8_UNORM`
|
||||
// image, whose texels a heap access converts where the handle carries `A8Unorm`'s class
|
||||
|
||||
@@ -818,12 +818,6 @@ pub(crate) fn slot_field(
|
||||
.iter()
|
||||
.find(|(k, _)| *k == key)
|
||||
.map(|(_, value)| FieldBytes::of(&value.to_le_bytes())),
|
||||
// Whether the texture the plan bound holds 16-bit float channels.
|
||||
PushField::TextureHalfChannels(slot) => resources
|
||||
.texture_half_channels
|
||||
.iter()
|
||||
.find(|(s, _)| *s == slot)
|
||||
.map(|(_, half)| FieldBytes::of(&half.to_le_bytes())),
|
||||
// The integer channel widths of the texture the plan bound.
|
||||
PushField::TextureIntegerChannels(slot) => resources
|
||||
.texture_integer_channels
|
||||
|
||||
@@ -454,11 +454,6 @@ pub(crate) struct ResourceTemplate {
|
||||
/// (`PushField::TextureLevels`): the bound texture's, 0 where a neutral stands in.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub texture_levels: Vec<(SlotRef, u32)>,
|
||||
/// Whether the bound texture's channels are 16-bit floats, which the binder pushes for each
|
||||
/// slot whose `half` writes read it (`PushField::TextureHalfChannels`): 1 or 0, 0 where a
|
||||
/// neutral stands in.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub texture_half_channels: Vec<(SlotRef, u32)>,
|
||||
/// The integer channel widths of the bound texture, which the binder pushes for each slot
|
||||
/// whose integer writes read them (`PushField::TextureIntegerChannels`):
|
||||
/// `metal::format::integer_channels_word` of its format, 0 where a neutral stands in.
|
||||
|
||||
@@ -430,11 +430,10 @@ fn plan(p: &ComputePipeline, device: &Device, shape: &BindShape) -> Result<Bindi
|
||||
class: SlotClass::Texture,
|
||||
..
|
||||
}) => return Err(not_implemented(Feature::TexelBuffer)),
|
||||
// A storage texture's level count, and whether its channels are 16-bit floats, which
|
||||
// the resource plan records; and a value the bound resources decide, which the plan
|
||||
// records too (`slots::record_specialized`).
|
||||
// A storage texture's level count and integer channel widths, which the resource plan
|
||||
// records; and a value the bound resources decide, which the plan records too
|
||||
// (`slots::record_specialized`).
|
||||
PushField::TextureLevels(_)
|
||||
| PushField::TextureHalfChannels(_)
|
||||
| PushField::TextureIntegerChannels(_)
|
||||
| PushField::Specialized(_) => {}
|
||||
// A structure's instance count, which instantiation reads from the state.
|
||||
|
||||
@@ -837,17 +837,6 @@ impl ResourcePlanner<'_> {
|
||||
};
|
||||
self.template.texture_levels.push((slot, levels));
|
||||
}
|
||||
if self.has_fact(RuntimeFact::StorageTextureHalfChannels { slot }) {
|
||||
let half = match (&write.0, self.texture_shape(slot)) {
|
||||
(WriteSource::Texture { .. }, Some(TextureShape::Texture { pixel_format, .. })) => {
|
||||
crate::metal::texel_format::half_channels(*pixel_format)
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
self.template
|
||||
.texture_half_channels
|
||||
.push((slot, u32::from(half)));
|
||||
}
|
||||
if self.has_fact(RuntimeFact::StorageTextureIntegerChannels { slot }) {
|
||||
let word = match (&write.0, self.texture_shape(slot)) {
|
||||
(
|
||||
|
||||
+8
-13
@@ -879,7 +879,6 @@ codec_enum! {
|
||||
VertexDepthClamp,
|
||||
BlendColor,
|
||||
ShaderTestsState,
|
||||
TextureHalfChannels(f0),
|
||||
CaptureAddress,
|
||||
CaptureLayout,
|
||||
CaptureIndexAddress,
|
||||
@@ -1128,12 +1127,11 @@ codec_struct! {
|
||||
StageIo {
|
||||
inputs, outputs, builtins, pulled, stage_in, multisampled, varyings_at_pixel,
|
||||
position_depth, coverage_loop, color_writes, rounded_colors, primitive_inputs,
|
||||
early_fragment_tests, extended_range_colors, unattached_colors, half_bit_colors,
|
||||
sample_mask, rotated_colors, rotated_factors, rotated_blends, srgb_fetches,
|
||||
half_output_lanes, texture_write_rounding, uniform_outputs, uniform_inputs,
|
||||
instanced_attributes, half_blend_colors, half_fast_colors,
|
||||
float_blend_colors, zero_indices, color_group, word_colors, alpha_in_red_colors,
|
||||
alpha_test, depth_compares,
|
||||
early_fragment_tests, extended_range_colors, unattached_colors, sample_mask,
|
||||
rotated_colors, rotated_factors, rotated_blends, srgb_fetches, half_output_lanes,
|
||||
texture_write_rounding, uniform_outputs, uniform_inputs, instanced_attributes,
|
||||
half_blend_colors, half_fast_colors, float_blend_colors, zero_indices, color_group,
|
||||
word_colors, alpha_in_red_colors, alpha_test, depth_compares,
|
||||
}
|
||||
DepthCompares { samplers, clamped }
|
||||
ColorGroup { present, width, group }
|
||||
@@ -1143,7 +1141,7 @@ codec_struct! {
|
||||
StageInInput { index, ty, fetch }
|
||||
StageInFetch { format, buffer_index, offset, stride, step_function, step_rate, index }
|
||||
IoVariable { key, role, ty }
|
||||
IoType { numeric, components, source_bits, bits }
|
||||
IoType { numeric, components, source_bits }
|
||||
}
|
||||
|
||||
codec_enum! {
|
||||
@@ -1255,7 +1253,6 @@ codec_enum! {
|
||||
CubicSampler { slot },
|
||||
CubicArgumentSampler { stage },
|
||||
ShaderTests { formatless, multisampled, planes },
|
||||
StorageTextureHalfChannels { slot },
|
||||
CapturedPositions { form },
|
||||
HeapRawSamples { stage, sampler },
|
||||
ShaderStencilTest { formatless },
|
||||
@@ -1273,8 +1270,7 @@ codec_enum! {
|
||||
ObjectThreadgroupArena { static_bytes, payload },
|
||||
ExactFormsOverCompilerLimit {
|
||||
sampling,
|
||||
texel_conversion,
|
||||
nan_and_min_max
|
||||
texel_conversion
|
||||
},
|
||||
MergedDraws,
|
||||
QuadPrimitiveIds,
|
||||
@@ -1332,8 +1328,7 @@ codec_struct! {
|
||||
StageModule {
|
||||
stage, entry_point, spirv, specialization, required_subgroup_size, stage_flags,
|
||||
reconvergence, precision_notes, strategies, constant_blob, rounded_colors,
|
||||
specialized_notes, half_bit_colors, own_pixel_textures, snapshot_textures, private_bytes,
|
||||
stats,
|
||||
specialized_notes, own_pixel_textures, snapshot_textures, private_bytes, stats,
|
||||
}
|
||||
SpecializedNote { note, when }
|
||||
SpecClause { all }
|
||||
|
||||
Vendored
+3
-3
@@ -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 = 1878;
|
||||
pub const SEMANTICS_VERSION: u32 = 1879;
|
||||
|
||||
/// 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 = 1878;
|
||||
/// 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 = 461;
|
||||
pub const ARTIFACT_FORMAT_VERSION: u32 = 462;
|
||||
|
||||
/// The version of what this crate's runtime does with a compiled pipeline: instantiating a binding
|
||||
/// plan (`BindingPlan::instantiate_*`: descriptor ranges, push bytes, root, argument, and handle
|
||||
@@ -93,7 +93,7 @@ pub const ARTIFACT_FORMAT_VERSION: u32 = 461;
|
||||
/// changes no behaviour, and then updates that hash alone with the commit saying why, or changes
|
||||
/// behaviour and also bumps this version. The commit that bumps it says what changed; this comment
|
||||
/// keeps no history.
|
||||
pub const RUNTIME_VERSION: u32 = 1660;
|
||||
pub const RUNTIME_VERSION: u32 = 1661;
|
||||
|
||||
/// The digest of the sources this build of the crate was compiled from: SHA-256, as lowercase hex,
|
||||
/// of the manifest, the build script, and exactly the files the crate roots' module tree compiles
|
||||
|
||||
@@ -13,14 +13,12 @@ use crate::device::description::{
|
||||
use crate::device::function_storage;
|
||||
use crate::device::metal::MetalDeviceProperties;
|
||||
use crate::device::policy::{
|
||||
ContainmentPolicy, DevicePolicy, NanMinMaxPolicy, SamplingPolicy, Unorm8LinearFilterPolicy,
|
||||
YCbCrFilterPolicy,
|
||||
ContainmentPolicy, DevicePolicy, SamplingPolicy, Unorm8LinearFilterPolicy, YCbCrFilterPolicy,
|
||||
};
|
||||
use crate::device::profile::{
|
||||
BufferAccess, Containment, CubeGradientRoute, CubeGradients, DescriptorCaps, DeviceProfile,
|
||||
DriverWorkaround, EnabledCaps, FloatFunctions, FormatTable, FragmentCaps, GuestIsolation,
|
||||
ImageCaps, Independence, LeafCaps, MinMaxRoute, NanEncoding, ProfileFields, Robustness,
|
||||
TexelNanRoute,
|
||||
ImageCaps, Independence, LeafCaps, NanEncoding, ProfileFields, Robustness,
|
||||
};
|
||||
use crate::device::requirements::{
|
||||
ApiVersion, FloatControl, FloatWidth, FormatUsage, ResolveMode, SubgroupOp, VkExtension,
|
||||
@@ -365,22 +363,12 @@ fn derive_fields(
|
||||
} else {
|
||||
FloatFunctions::Native
|
||||
},
|
||||
// The measured deviation; unmeasured, the device's NaN where the policy takes it, and the
|
||||
// module selects Metal's NaN itself where it asks for Metal's.
|
||||
// The measured deviation; unmeasured, the device's NaN, noted.
|
||||
nan_encoding: if deviates(DriverDeviation::MetalCanonicalNans) {
|
||||
NanEncoding::MetalCanonical
|
||||
} else if policy.nan_and_min_max == NanMinMaxPolicy::Exact {
|
||||
NanEncoding::Device
|
||||
} else {
|
||||
NanEncoding::Native
|
||||
},
|
||||
// Metal's NaN of a texel where the policy asks for Metal's, on every device: no device
|
||||
// fact decides it.
|
||||
texel_nans: if policy.nan_and_min_max == NanMinMaxPolicy::Exact {
|
||||
TexelNanRoute::Metal
|
||||
} else {
|
||||
TexelNanRoute::Device
|
||||
},
|
||||
// Metal's filter of a two-plane YCbCr texture through the slot's variant where the policy
|
||||
// asks for it: on a device that samples through Metal's own sampler, under the YCbCr
|
||||
// filter's switch or Metal's sampling; on one that samples natively, under the switch. A
|
||||
@@ -401,16 +389,6 @@ fn derive_fields(
|
||||
desc.device_type,
|
||||
Some(vk::PhysicalDeviceType::INTEGRATED_GPU | vk::PhysicalDeviceType::CPU)
|
||||
),
|
||||
// Metal's picks where the device's minimum and maximum are measured to be Metal's or its
|
||||
// functions are Metal's own; elsewhere the device's where the policy takes them.
|
||||
min_max: if deviates(DriverDeviation::MetalMinMax)
|
||||
|| deviates(DriverDeviation::MetalFloatFunctions)
|
||||
|| policy.nan_and_min_max == NanMinMaxPolicy::Exact
|
||||
{
|
||||
MinMaxRoute::Metal
|
||||
} else {
|
||||
MinMaxRoute::Native
|
||||
},
|
||||
// The device's measured value, keyed on its identity as the workarounds are, or the floor.
|
||||
function_storage: function_storage::of(desc),
|
||||
// The measured deviations, one per pipeline kind (the graphics one per macOS release's
|
||||
|
||||
@@ -113,8 +113,6 @@ pub fn mechanism(fact: &RuntimeFact, profile: &DeviceProfile) -> Mechanism {
|
||||
RuntimeFact::BicubicTexels { .. } => Mechanism::Specialization,
|
||||
// The binder writes the bound texture's level count per draw or dispatch.
|
||||
RuntimeFact::StorageTextureLevels { .. } => Mechanism::PushConstant,
|
||||
// The binder writes whether the bound texture's channels are 16-bit floats.
|
||||
RuntimeFact::StorageTextureHalfChannels { .. } => Mechanism::PushConstant,
|
||||
// The binder writes the bound texture's integer channel widths.
|
||||
RuntimeFact::StorageTextureIntegerChannels { .. } => Mechanism::PushConstant,
|
||||
// The binder views each level of the bound texture at its element.
|
||||
|
||||
@@ -67,9 +67,8 @@ pub(crate) use mechanism::mechanism;
|
||||
pub use metal::{MetalDeviceProperties, SimdSupport, StageSimd};
|
||||
pub use policy::{
|
||||
BatchOrderPolicy, CompletionPolicy, ContainmentPolicy, DecodedTexelsPolicy, DevicePolicy,
|
||||
HeapCompressionPolicy, HostPageTexturePolicy, NanMinMaxPolicy, RenderLoweringPolicy,
|
||||
SamplingPolicy, TexelConversionPolicy, Unorm8LinearFilterPolicy, VertexNormalizedPolicy,
|
||||
YCbCrFilterPolicy,
|
||||
HeapCompressionPolicy, HostPageTexturePolicy, RenderLoweringPolicy, SamplingPolicy,
|
||||
TexelConversionPolicy, Unorm8LinearFilterPolicy, VertexNormalizedPolicy, YCbCrFilterPolicy,
|
||||
};
|
||||
pub(crate) use profile::whole_point_size;
|
||||
pub use profile::{DeviceProfile, SpirvValidation};
|
||||
|
||||
@@ -40,10 +40,6 @@ pub struct DevicePolicy {
|
||||
/// Whether a normalized vertex attribute's value is the device's fixed-function conversion of
|
||||
/// its codes (the default) or Metal's, divided exactly in the shader.
|
||||
pub vertex_normalized: VertexNormalizedPolicy,
|
||||
/// Whether a NaN result's bits, and the operand Metal's minimum and maximum functions
|
||||
/// (`fmin`, `fmax`, `min3`, `max3`, `clamp`, `saturate`) pick at a NaN or a signed zero, are
|
||||
/// the device's own (the default) or Metal's.
|
||||
pub nan_and_min_max: NanMinMaxPolicy,
|
||||
|
||||
/// Whether a texture whose format the device lacks, held in a carrier (an ASTC LDR texture,
|
||||
/// or an EAC 11-bit one), samples a decoded twin of compact codes (the default) or of Metal's
|
||||
@@ -80,10 +76,10 @@ pub struct DevicePolicy {
|
||||
impl DevicePolicy {
|
||||
/// The untrusted-guest production policy: containment and isolation on, Metal's 8-bit linear
|
||||
/// filter emulated exactly where the emulation runs, native device sampling (a two-plane YCbCr texture's samples among them),
|
||||
/// the device's own texel conversions, the device's NaN and minimum and maximum, compact
|
||||
/// codes in a carried texture's decoded twin, the driver's compressed image of a heap's texture
|
||||
/// Metal keeps compressed, command buffers ready together in one kernel submission, batches of
|
||||
/// one queue ordered by their ends where the driver runs them one after another, and a sampled
|
||||
/// the device's own texel conversions, compact codes in a carried texture's decoded twin, the
|
||||
/// driver's compressed image of a heap's texture Metal keeps compressed, command buffers ready
|
||||
/// together in one kernel submission, batches of one queue ordered by their ends where the
|
||||
/// driver runs them one after another, and a sampled
|
||||
/// texture over host pages in place where the device's check passed.
|
||||
pub const UNTRUSTED: DevicePolicy = DevicePolicy {
|
||||
pointer_domain: PointerDomain::ResidentTable,
|
||||
@@ -95,7 +91,6 @@ impl DevicePolicy {
|
||||
ycbcr_filter: YCbCrFilterPolicy::Device,
|
||||
texel_conversion: TexelConversionPolicy::Device,
|
||||
vertex_normalized: VertexNormalizedPolicy::Device,
|
||||
nan_and_min_max: NanMinMaxPolicy::Native,
|
||||
decoded_texels: DecodedTexelsPolicy::Compact,
|
||||
heap_compression: HeapCompressionPolicy::Compressed,
|
||||
completion: CompletionPolicy::Grouped,
|
||||
@@ -106,8 +101,7 @@ impl DevicePolicy {
|
||||
|
||||
/// This policy with Metal's answer wherever the choices offer it: its texel conversions
|
||||
/// ([`TexelConversionPolicy::Exact`]), its normalized vertex attributes
|
||||
/// ([`VertexNormalizedPolicy::Exact`]), its NaN and minimum and maximum
|
||||
/// ([`NanMinMaxPolicy::Exact`]), its filter of a
|
||||
/// ([`VertexNormalizedPolicy::Exact`]), its filter of a
|
||||
/// two-plane YCbCr texture
|
||||
/// ([`YCbCrFilterPolicy::Exact`]), its decode of a carried texture's texels
|
||||
/// ([`DecodedTexelsPolicy::Exact`]), a heap's texture whose bytes alias the heap's
|
||||
@@ -124,7 +118,6 @@ impl DevicePolicy {
|
||||
ycbcr_filter: YCbCrFilterPolicy::Exact,
|
||||
texel_conversion: TexelConversionPolicy::Exact,
|
||||
vertex_normalized: VertexNormalizedPolicy::Exact,
|
||||
nan_and_min_max: NanMinMaxPolicy::Exact,
|
||||
decoded_texels: DecodedTexelsPolicy::Exact,
|
||||
heap_compression: HeapCompressionPolicy::Uncompressed,
|
||||
completion: CompletionPolicy::Exact,
|
||||
@@ -297,39 +290,6 @@ pub enum VertexNormalizedPolicy {
|
||||
Exact,
|
||||
}
|
||||
|
||||
/// Whose NaN a `float` or `half` result answers, and which operand Metal's minimum and maximum
|
||||
/// functions (`fmin`, `fmax`, `min3`, `max3`, `clamp`, and `saturate`, Metal's
|
||||
/// `clamp(x, +0, 1)`) pick at a NaN, a signed zero or an `f32` denormal, on a device not measured
|
||||
/// to answer Metal's (the owner's "the bit pattern of NaN values, and min and max when NaN or
|
||||
/// signed zero is involved" of 2026-10-11). A device measured to answer Metal's canonical NaN
|
||||
/// (`DriverDeviation::MetalCanonicalNans`) keeps it, and one measured to compute Metal's minimum
|
||||
/// and maximum (`DriverDeviation::MetalMinMax`) or whose functions are Metal's own
|
||||
/// (`DriverDeviation::MetalFloatFunctions`, MoltenVK on an Apple GPU) keeps Metal's picks, under
|
||||
/// either setting.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
pub enum NanMinMaxPolicy {
|
||||
/// The device's own (the default): every NaN Metal answers is the device's (its sign and
|
||||
/// payload; no select of Metal's bits), and those functions are the device's `NMin`, `NMax`
|
||||
/// and `NClamp`. On a device that rounds a `half` through its conversion under the float
|
||||
/// controls (ANV, RADV), a `half` read from its bits is the device's widening of them, and a
|
||||
/// `half` texel takes that conversion's NaN. Such a module records
|
||||
/// [`PrecisionNote::NativeNanEncoding`](crate::pipeline::PrecisionNote::NativeNanEncoding)
|
||||
/// or [`NativeMinMax`](crate::pipeline::PrecisionNote::NativeMinMax), whose docs state the
|
||||
/// bound.
|
||||
#[default]
|
||||
Native,
|
||||
/// Metal's: the translation selects Metal's NaN where the device may answer another, and
|
||||
/// Metal's operand where the device's instructions may pick another; a `half` widened to
|
||||
/// `float` answers `0x7fc00000` for every NaN, as Metal does. A `half` texel read, sampled or
|
||||
/// gathered keeps the NaN the device decoded through native half rounding too and through the
|
||||
/// conversion under the float controls, and a
|
||||
/// `half` read from its bits is decoded in integer arithmetic where the default takes the
|
||||
/// device's widening (a `half` stored back unchanged keeps its bits under either).
|
||||
Exact,
|
||||
}
|
||||
|
||||
/// What texels the runtime holds in the decoded twin of a texture whose blocks it holds in a
|
||||
/// carrier on a device without the format (the runtime's `texture/decoded_twin.rs`), which the
|
||||
/// texture's samples, reads and gathers read: an ASTC LDR texture's (`bind::AstcDecode`), and an
|
||||
|
||||
@@ -536,14 +536,10 @@ pub struct ProfileFields {
|
||||
/// Metal's own, in the math mode Metal's compile of the module takes, or the device's. The
|
||||
/// module takes the device's instructions on either; the notes it records differ.
|
||||
pub float_functions: FloatFunctions,
|
||||
/// Which NaN the device's `float` and `half` arithmetic answers: Metal's canonical NaN, so the
|
||||
/// translation leaves it to the device, or the device's own, so the translation selects Metal's
|
||||
/// where a result's bits are observed.
|
||||
/// Which NaN the device's `float` and `half` arithmetic answers: Metal's canonical NaN, measured,
|
||||
/// or the device's own, which the module records where Metal answers a NaN. Either way the
|
||||
/// translation leaves every NaN's bits to the device.
|
||||
pub nan_encoding: NanEncoding,
|
||||
/// Whose NaN a `half` read, sample or gather hands back for a NaN texel: Metal's, by the
|
||||
/// class of the texture bound, where the policy's `NanMinMaxPolicy::Exact` asks for it, on
|
||||
/// every device, or the device's decode (the default).
|
||||
pub texel_nans: TexelNanRoute,
|
||||
/// Whether a linear sample the device's sampler answers (`DeviceProfile::device_samples`)
|
||||
/// takes Metal's filter of a two-plane YCbCr texture bound at its slot, through the slot's
|
||||
/// YCbCr variant (`RuntimeFact::YCbCrTexture`): under the policy's `YCbCrFilterPolicy::Exact`,
|
||||
@@ -560,11 +556,6 @@ pub struct ProfileFields {
|
||||
/// which its refresh reads across the bus once per encoder where the in-place form would read
|
||||
/// the planes there at every pass. Both forms read Metal's texels exactly.
|
||||
pub ycbcr_in_place: bool,
|
||||
/// Whose operand Metal's minimum and maximum functions pick (`lower::arith::native_min_max`):
|
||||
/// Metal's, or the device's `NMin`, `NMax` and `NClamp` as they are (the policy's
|
||||
/// `NanMinMaxPolicy::Native`). Derived, so a device that keeps Metal's picks keys the same
|
||||
/// under both policies.
|
||||
pub min_max: MinMaxRoute,
|
||||
/// The Function storage a thread holds correctly (`device::function_storage`): a stage's
|
||||
/// private memory, its call stacks included, may take this much a thread
|
||||
/// (`VkLimit::FunctionStorageBytesPerThread`), and a vertex or fragment function on a device
|
||||
@@ -685,54 +676,20 @@ pub enum FloatFunctions {
|
||||
Native,
|
||||
}
|
||||
|
||||
/// Whose operand Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate` on `float` and
|
||||
/// `half` pick ([`ProfileFields::min_max`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum MinMaxRoute {
|
||||
/// Metal's: the device's `NMin`, `NMax` and `NClamp` where they are measured to be Metal's
|
||||
/// (`DriverDeviation::MetalMinMax`), else the translation's selects of Metal's operand, as on a
|
||||
/// device whose functions are Metal's own (`DriverDeviation::MetalFloatFunctions`) or under
|
||||
/// `NanMinMaxPolicy::Exact`.
|
||||
Metal,
|
||||
/// The device's `NMin`, `NMax` and `NClamp` as they are (`NanMinMaxPolicy::Native`, the
|
||||
/// default), noted `PrecisionNote::NativeMinMax` with its bound.
|
||||
Native,
|
||||
}
|
||||
|
||||
/// Which NaN a device's `float` and `half` arithmetic answers ([`ProfileFields::nan_encoding`]),
|
||||
/// decided by the driver's measured deviation [`DriverDeviation::MetalCanonicalNans`].
|
||||
/// decided by the driver's measured deviation [`DriverDeviation::MetalCanonicalNans`]. The
|
||||
/// translation selects no NaN under either: every NaN's bits are the device's.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum NanEncoding {
|
||||
/// Metal's canonical NaN, `0x7FC00000` (`0x7E00` as `half`), for every NaN result of the
|
||||
/// arithmetic and of the functions whose NaN Metal canonicalizes.
|
||||
/// arithmetic and of the functions whose NaN Metal canonicalizes, measured: such a result
|
||||
/// records nothing.
|
||||
MetalCanonical,
|
||||
/// The device's own: an operand's bits, quieted or not, or another NaN, which the
|
||||
/// translation answers Metal's in place of (the policy's `NanMinMaxPolicy::Exact`).
|
||||
Device,
|
||||
/// The device's own, taken as it is (`NanMinMaxPolicy::Native`, the default), noted
|
||||
/// `PrecisionNote::NativeNanEncoding` with its bound.
|
||||
/// The device's own, unmeasured, noted `PrecisionNote::NativeNanEncoding` with its bound.
|
||||
Native,
|
||||
}
|
||||
|
||||
/// Whose NaN a `half` texel access hands back for a NaN texel ([`ProfileFields::texel_nans`]).
|
||||
/// A texel's NaN is the image's decode, which the access narrows itself, not a result of the
|
||||
/// device's arithmetic, so [`ProfileFields::nan_encoding`] does not decide it: a device measured
|
||||
/// to answer Metal's canonical NaN in its arithmetic (`NanEncoding::MetalCanonical`) need not
|
||||
/// answer it for a texel, and MoltenVK on the Apple M3 Max does not (a 32-bit float texel's NaN
|
||||
/// read as `half` keeps its payload's top bits).
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum TexelNanRoute {
|
||||
/// Metal's rule (`NanMinMaxPolicy::Exact`): a 16-bit float texel's own NaN where the access
|
||||
/// reads one texel, and `0x7e00` for every other NaN, by the class of the texture bound
|
||||
/// (`lower::texture::texel_nans_class`).
|
||||
Metal,
|
||||
/// The device's decode (`NanMinMaxPolicy::Native`, the default), noted
|
||||
/// `PrecisionNote::DeviceNanEncoding`.
|
||||
Device,
|
||||
}
|
||||
|
||||
/// What the consumer enabled, as the capability vocabulary `Requirements` uses
|
||||
/// ([`DeviceProfile::enabled`]). Selection reads the typed caps above; the finalize check
|
||||
/// (`requirements ⊆ profile`) reads these.
|
||||
|
||||
@@ -189,7 +189,6 @@ fn every_fact() -> Vec<RuntimeFact> {
|
||||
multisampled: true,
|
||||
planes: true,
|
||||
},
|
||||
RuntimeFact::StorageTextureHalfChannels { slot },
|
||||
RuntimeFact::StorageTextureIntegerChannels { slot },
|
||||
RuntimeFact::CapturedPositions {
|
||||
form: crate::pipeline::CaptureForm::Indexed(crate::metal::IndexType::UInt16),
|
||||
@@ -268,7 +267,6 @@ fn every_fact() -> Vec<RuntimeFact> {
|
||||
RuntimeFact::ExactFormsOverCompilerLimit {
|
||||
sampling: true,
|
||||
texel_conversion: false,
|
||||
nan_and_min_max: true,
|
||||
},
|
||||
]
|
||||
}
|
||||
@@ -348,7 +346,6 @@ fn variant(f: &RuntimeFact) -> usize {
|
||||
RuntimeFact::CubicSampler { .. } => 68,
|
||||
RuntimeFact::CubicArgumentSampler { .. } => 69,
|
||||
RuntimeFact::ShaderTests { .. } => 70,
|
||||
RuntimeFact::StorageTextureHalfChannels { .. } => 71,
|
||||
RuntimeFact::CapturedPositions { .. } => 72,
|
||||
RuntimeFact::HeapRawSamples { .. } => 73,
|
||||
RuntimeFact::ShaderStencilTest { .. } => 74,
|
||||
@@ -371,7 +368,7 @@ fn variant(f: &RuntimeFact) -> usize {
|
||||
RuntimeFact::RotatedWeights => 91,
|
||||
RuntimeFact::PrivateList => 92,
|
||||
RuntimeFact::MeshLastFirst => 93,
|
||||
RuntimeFact::YCbCrInPlace { .. } => 94,
|
||||
RuntimeFact::YCbCrInPlace { .. } => 71,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -379,7 +376,7 @@ fn variant(f: &RuntimeFact) -> usize {
|
||||
fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
let facts = every_fact();
|
||||
let covered: std::collections::BTreeSet<usize> = facts.iter().map(variant).collect();
|
||||
assert_eq!(covered, (0..95).collect(), "every_fact misses a variant");
|
||||
assert_eq!(covered, (0..94).collect(), "every_fact misses a variant");
|
||||
for (stem, _) in super::committed_profiles() {
|
||||
let dev = device(&stem);
|
||||
let p = dev.profile();
|
||||
@@ -510,7 +507,6 @@ fn mechanism_is_total_over_every_fact_and_profile() {
|
||||
RuntimeFact::StageInRegion
|
||||
| RuntimeFact::StageInStride { .. }
|
||||
| RuntimeFact::StorageTextureLevels { .. }
|
||||
| RuntimeFact::StorageTextureHalfChannels { .. }
|
||||
| RuntimeFact::StorageTextureIntegerChannels { .. }
|
||||
| RuntimeFact::AccelerationStructureInstanceCount { .. }
|
||||
| RuntimeFact::ViewportCount
|
||||
|
||||
@@ -307,12 +307,11 @@ fn below_1_2_and_contradictory_policies_are_refused() {
|
||||
}
|
||||
|
||||
/// Each of the policy's choices between the device's answer and Metal's, with a function that
|
||||
/// flips it alone: the texel conversions, a normalized vertex attribute's conversion, the NaN and
|
||||
/// minimum and maximum, and the filter of a two-plane YCbCr texture.
|
||||
fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 4] {
|
||||
/// flips it alone: the texel conversions, a normalized vertex attribute's conversion, and the filter
|
||||
/// of a two-plane YCbCr texture.
|
||||
fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 3] {
|
||||
use crate::device::{
|
||||
NanMinMaxPolicy as N, TexelConversionPolicy as T, VertexNormalizedPolicy as V,
|
||||
YCbCrFilterPolicy as Y,
|
||||
TexelConversionPolicy as T, VertexNormalizedPolicy as V, YCbCrFilterPolicy as Y,
|
||||
};
|
||||
[
|
||||
("texel_conversion", |p| DevicePolicy {
|
||||
@@ -329,13 +328,6 @@ fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 4] {
|
||||
},
|
||||
..p
|
||||
}),
|
||||
("nan_and_min_max", |p| DevicePolicy {
|
||||
nan_and_min_max: match p.nan_and_min_max {
|
||||
N::Native => N::Exact,
|
||||
N::Exact => N::Native,
|
||||
},
|
||||
..p
|
||||
}),
|
||||
("ycbcr_filter", |p| DevicePolicy {
|
||||
ycbcr_filter: match p.ycbcr_filter {
|
||||
Y::Device => Y::Exact,
|
||||
@@ -346,11 +338,8 @@ fn exactness_flips() -> [(&'static str, fn(DevicePolicy) -> DevicePolicy); 4] {
|
||||
]
|
||||
}
|
||||
|
||||
/// On MoltenVK on the M3, whose functions, NaN, minimum and maximum are measured to be Metal's,
|
||||
/// each choice still moves the key: the texel conversions' is the policy's own field there, the
|
||||
/// NaN and minimum and maximum's moves the texel
|
||||
/// NaN route (`TexelNanRoute`): a texel's NaN is the image's decode, which no arithmetic fact
|
||||
/// covers, and the YCbCr filter's moves whether a two-plane YCbCr slot takes its variant
|
||||
/// On MoltenVK on the M3, each choice still moves the key: the texel conversions' is the policy's
|
||||
/// own field there, and the YCbCr filter's moves whether a two-plane YCbCr slot takes its variant
|
||||
/// (`ProfileFields::ycbcr_variant`), Metal's sampler filtering such a texture's converted texels
|
||||
/// otherwise.
|
||||
#[test]
|
||||
|
||||
@@ -42,7 +42,7 @@ use crate::error::Error;
|
||||
use crate::lower::arith::legal::{self, chunk_lanes, not_lowered, Form, Held};
|
||||
use crate::lower::arith::libm::Lib;
|
||||
use crate::lower::arith::math::{self, FloatFn};
|
||||
use crate::lower::arith::nan::{self, NanAnswer, NanTest};
|
||||
use crate::lower::arith::nan::NanTest;
|
||||
use crate::lower::arith::{denormal, fma};
|
||||
use crate::lower::arith::{narrow, operands_of, ops, wide, ArithStrategy};
|
||||
use crate::lower::emit::EmitCx;
|
||||
@@ -290,7 +290,7 @@ pub fn select(
|
||||
InstKind::Call(call) if is_math(call, MathFn::SinCos) => {
|
||||
super::select_sincos(cx, at, inst, call, m)
|
||||
}
|
||||
InstKind::Call(call) if is_math(call, MathFn::Dot) => select_dot(cx, at, inst, call),
|
||||
InstKind::Call(call) if is_math(call, MathFn::Dot) => select_dot(cx, inst, call),
|
||||
InstKind::Cast {
|
||||
op: CastOp::Bitcast,
|
||||
v,
|
||||
@@ -368,13 +368,8 @@ fn is_math(call: &Call, f: MathFn) -> bool {
|
||||
/// denormals the device's (`super::leave_denormals`). Elsewhere the sum of each chunk's dot
|
||||
/// product, rounded once to a narrow format:
|
||||
/// `dot`'s device precision (`DeviceArithmetic`) covers the order of the sum, which Vulkan leaves
|
||||
/// to the device for `OpDot` too. Its NaN is Metal's.
|
||||
fn select_dot(
|
||||
cx: &mut SelectCx<'_>,
|
||||
at: InstId,
|
||||
inst: &Inst,
|
||||
call: &Call,
|
||||
) -> Result<ArithStrategy, Error> {
|
||||
/// to the device for `OpDot` too. Its NaN is the device's.
|
||||
fn select_dot(cx: &mut SelectCx<'_>, inst: &Inst, call: &Call) -> Result<ArithStrategy, Error> {
|
||||
let (Some(&a), Some(&b)) = (call.args.first(), call.args.get(1)) else {
|
||||
return Err(cx.invariant("air.dot without its operands"));
|
||||
};
|
||||
@@ -404,7 +399,7 @@ fn select_dot(
|
||||
elem,
|
||||
fma,
|
||||
};
|
||||
return Ok(super::with_nan(cx, at, s, answer, elem));
|
||||
return Ok(super::with_nan(cx, s, answer));
|
||||
}
|
||||
}
|
||||
super::note(cx, FloatFn::Dot.precision());
|
||||
@@ -415,7 +410,7 @@ fn select_dot(
|
||||
elem,
|
||||
contract: super::contraction(call.fmf),
|
||||
};
|
||||
Ok(super::with_nan(cx, at, s, answer, elem))
|
||||
Ok(super::with_nan(cx, s, answer))
|
||||
}
|
||||
|
||||
/// The dot product of chunked vectors `a` and `b` of `lanes` lanes of `elem`: each chunk's `OpDot`
|
||||
@@ -490,30 +485,22 @@ pub fn dot_chain_words(lanes: u16, elem: Form, fma_words: u32) -> u32 {
|
||||
|
||||
/// The sine and cosine of `x` of shape `s`: per chunk for a chunked vector, Metal's fast ones for
|
||||
/// `air.fast_sincos` on `float` (`fast`, [`sin_cos_fns`]), each the device's instruction as `lib`
|
||||
/// reads it, with the entry's NaN `test` ([`math::float_fn`]), then Metal's
|
||||
/// NaN `answers` of each selected ([`nan::select`]).
|
||||
/// reads it, with the entry's NaN `test` ([`math::float_fn`]).
|
||||
pub fn sin_cos(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
s: Shape,
|
||||
x: SValue,
|
||||
fast: bool,
|
||||
answers: [Option<NanAnswer>; 2],
|
||||
test: NanTest,
|
||||
lib: &Lib,
|
||||
) -> BResult<(SValue, SValue)> {
|
||||
let (sin, cos) = sin_cos_fns(fast);
|
||||
let one = |fb: &mut FunctionBuilder<'_>, f: Form, x: SValue| -> BResult<(SValue, SValue)> {
|
||||
let c = Contraction::Forbidden;
|
||||
let mut r = [
|
||||
Ok((
|
||||
math::float_fn(fb, sin, f, c, test, &[x], lib)?,
|
||||
math::float_fn(fb, cos, f, c, test, &[x], lib)?,
|
||||
];
|
||||
for (v, answer) in r.iter_mut().zip(answers) {
|
||||
if let Some(answer) = answer {
|
||||
*v = nan::select(fb, f, answer, test, *v, Some(x))?;
|
||||
}
|
||||
}
|
||||
Ok((r[0], r[1]))
|
||||
))
|
||||
};
|
||||
if !s.chunked {
|
||||
return one(fb, s.form(), x);
|
||||
@@ -549,19 +536,9 @@ pub fn sin_cos_fns(fast: bool) -> (FloatFn, FloatFn) {
|
||||
}
|
||||
|
||||
/// The words of [`sin_cos`] on shape `s`.
|
||||
pub fn sin_cos_words(s: Shape, fast: bool, answers: [Option<NanAnswer>; 2]) -> u32 {
|
||||
pub fn sin_cos_words(s: Shape, fast: bool) -> u32 {
|
||||
let (sin, cos) = sin_cos_fns(fast);
|
||||
let per = |f: Form| {
|
||||
let selects = answers
|
||||
.iter()
|
||||
.flatten()
|
||||
.map(|a| a.words(f))
|
||||
.fold(0u32, u32::saturating_add);
|
||||
sin.words(f)
|
||||
.saturating_add(cos.words(f))
|
||||
.saturating_add(8)
|
||||
.saturating_add(selects)
|
||||
};
|
||||
let per = |f: Form| sin.words(f).saturating_add(cos.words(f)).saturating_add(8);
|
||||
if !s.chunked {
|
||||
return per(s.form());
|
||||
}
|
||||
|
||||
@@ -30,8 +30,8 @@ use crate::lower::arith::ops::{fsplat, splat, ty};
|
||||
use crate::pipeline::lower_inputs::ChannelWrite;
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
use crate::spirv::error::{BResult, BuildError, OperandRule};
|
||||
use crate::spirv::ids::{TypeId, Value};
|
||||
use crate::spirv::ir::{BinOp, ConvOp, GlslOp, Type, UnOp};
|
||||
use crate::spirv::ids::Value;
|
||||
use crate::spirv::ir::{BinOp, ConvOp, GlslOp, UnOp};
|
||||
|
||||
/// An upper estimate of the SPIR-V words of one channel's rounding by `rule`.
|
||||
pub fn channel_words(rule: ChannelWrite) -> u64 {
|
||||
@@ -59,77 +59,6 @@ pub fn words(rules: &[Option<ChannelWrite>; 4]) -> u64 {
|
||||
+ written.saturating_add(1).saturating_mul(6)
|
||||
}
|
||||
|
||||
/// An upper estimate of the SPIR-V words of [`half_bits`]: about 20 instructions on the whole
|
||||
/// vector, its constants, 16-bit types and their capabilities included (192 words measured on four
|
||||
/// lanes, two widening conversions with them).
|
||||
pub const HALF_BITS_WORDS: u64 = 34 * 6;
|
||||
|
||||
/// The `half` lanes whose bits hold `x` (float lanes of form `f`, a 32-bit container), each lane
|
||||
/// a value a half holds exactly (a half widened, or a value [`round`] rounded to one), on a
|
||||
/// profile whose conversion to 16 bits, of an operand its compiler cannot fold into the
|
||||
/// instruction computing it, is Metal's `half(float)` (`DriverDeviation::MetalHalfConversion`,
|
||||
/// `narrow::QuantizeForm::Converted`): that conversion of `x + -0.0` (an `OpFAdd` decorated
|
||||
/// `NoContraction`, as `narrow` converts), exact for every value but a NaN, whose half the
|
||||
/// conversion makes `0x7e00`; a NaN lane is [`nan_codes`]'s code instead, chosen as 16-bit
|
||||
/// integers, and the lanes bitcast to `half` once (`Int16` and `Float16`), so no conversion on
|
||||
/// the device chooses a NaN's encoding.
|
||||
pub fn half_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value> {
|
||||
let lanes = |fb: &mut FunctionBuilder<'_>, elem: Type| -> BResult<TypeId> {
|
||||
let elem = fb.module().ty(elem)?;
|
||||
match f.lanes {
|
||||
1 => Ok(elem),
|
||||
len => fb.module().ty(Type::Vector { elem, len }),
|
||||
}
|
||||
};
|
||||
let u16_ = lanes(
|
||||
fb,
|
||||
Type::Int {
|
||||
width: 16,
|
||||
signed: false,
|
||||
},
|
||||
)?;
|
||||
let h = lanes(fb, Type::Float { width: 16 })?;
|
||||
let minus_zero = fsplat(fb, f.with(Held::Float(FloatFmt::F32)), -0.0)?;
|
||||
let held = fb.binary_no_contraction(BinOp::FAdd, x, minus_zero)?;
|
||||
let converted = fb.convert(ConvOp::FConvert, held, h)?;
|
||||
let converted = fb.convert(ConvOp::Bitcast, converted, u16_)?;
|
||||
let nan = nan_codes(fb, f, x)?;
|
||||
let nan = fb.convert(ConvOp::UConvert, nan, u16_)?;
|
||||
let is_nan = fb.unary(UnOp::IsNan, x)?;
|
||||
let code = fb.select(is_nan, nan, converted)?;
|
||||
fb.convert(ConvOp::Bitcast, code, h)
|
||||
}
|
||||
|
||||
/// The 16-bit `half` NaN codes (in `u32` lanes) of `x` (float lanes of form `f`, a 32-bit
|
||||
/// container) where a lane is a NaN, by integer operations on the bits: the sign, every exponent
|
||||
/// bit, and the top ten fraction bits, a widened half NaN's own payload, `0x200` where those are
|
||||
/// zero (a NaN no half widens to). A lane that is not a NaN gives a code [`half_bits`] does not
|
||||
/// choose.
|
||||
pub fn nan_codes(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value> {
|
||||
let u = f.with(Held::Int {
|
||||
bits: 32,
|
||||
container: 32,
|
||||
});
|
||||
let k = |fb: &mut FunctionBuilder<'_>, bits: u32| splat(fb, u, u64::from(bits));
|
||||
let ut = ty(fb, u)?;
|
||||
let bits = fb.convert(ConvOp::Bitcast, x, ut)?;
|
||||
let k16 = k(fb, 16)?;
|
||||
let sign = fb.binary(BinOp::ShiftRightLogical, bits, k16)?;
|
||||
let sign_bit = k(fb, 0x8000)?;
|
||||
let sign = fb.binary(BinOp::BitwiseAnd, sign, sign_bit)?;
|
||||
let k13 = k(fb, 13)?;
|
||||
let top = fb.binary(BinOp::ShiftRightLogical, bits, k13)?;
|
||||
let payload_mask = k(fb, 0x3ff)?;
|
||||
let top = fb.binary(BinOp::BitwiseAnd, top, payload_mask)?;
|
||||
let zero = k(fb, 0)?;
|
||||
let low = fb.binary(BinOp::IEqual, top, zero)?;
|
||||
let quiet = k(fb, 0x200)?;
|
||||
let payload = fb.select(low, quiet, top)?;
|
||||
let infinity = k(fb, 0x7c00)?;
|
||||
let special = fb.binary(BinOp::BitwiseOr, infinity, payload)?;
|
||||
fb.binary(BinOp::BitwiseOr, sign, special)
|
||||
}
|
||||
|
||||
fn malformed() -> BuildError {
|
||||
BuildError::Operand {
|
||||
op: crate::spv::Op::ExtInst,
|
||||
|
||||
@@ -450,7 +450,7 @@ pub(super) fn select(
|
||||
negate: fusion.negate,
|
||||
inner: inner.into_boxed_slice(),
|
||||
};
|
||||
Ok(Some(super::with_nan(cx, at, s, nan, f)))
|
||||
Ok(Some(super::with_nan(cx, s, nan)))
|
||||
}
|
||||
|
||||
/// Whether `v` is a sum: the result of a float addition or subtraction (fused or not) or of a
|
||||
|
||||
@@ -336,42 +336,19 @@ pub fn use_words(lanes: u8, arity: usize) -> u32 {
|
||||
}
|
||||
|
||||
/// What an entry's calls take, as emission reads them: the mode Metal compiles the entry's
|
||||
/// functions in where the device's are Metal's, the routine of precise `fmod` where the module
|
||||
/// defines one, and whether Metal's minimum and maximum functions are the device's.
|
||||
/// functions in where the device's are Metal's, and the routine of precise `fmod` where the module
|
||||
/// defines one.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Lib {
|
||||
metal: Option<Mode>,
|
||||
fmod: Option<FuncId>,
|
||||
/// Whether the device's `NMin`, `NMax` and `NClamp` are Metal's `fmin`, `fmax` and `clamp`
|
||||
/// ([`Lib::with_min_max`]).
|
||||
min_max: bool,
|
||||
}
|
||||
|
||||
impl Lib {
|
||||
/// The library of an entry whose `float` functions are Metal's in mode `metal` (`None`: the
|
||||
/// device's), whose module defines precise `fmod`'s routine as `fmod` where it takes one.
|
||||
pub fn new(metal: Option<Mode>, fmod: Option<FuncId>) -> Lib {
|
||||
Lib {
|
||||
metal,
|
||||
fmod,
|
||||
min_max: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// This library, where the device's `GLSL.std.450` `NMin`, `NMax` and `NClamp` are Metal's
|
||||
/// own `fmin`, `fmax` and `clamp` if `device` (`ArithPlan::device_min_max`): Metal's minimum
|
||||
/// and maximum family on `float` and `half` then takes those instructions
|
||||
/// (`math::metal_min_max` otherwise).
|
||||
pub fn with_min_max(self, device: bool) -> Lib {
|
||||
Lib {
|
||||
min_max: device,
|
||||
..self
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the device's `NMin`, `NMax` and `NClamp` are Metal's ([`Lib::with_min_max`]).
|
||||
pub fn device_min_max(&self) -> bool {
|
||||
self.min_max
|
||||
Lib { metal, fmod }
|
||||
}
|
||||
|
||||
/// A library that leaves every function to its instruction (a unit test's view of the
|
||||
|
||||
@@ -710,20 +710,18 @@ pub enum FloatFn {
|
||||
FlaggedFract,
|
||||
/// Metal's `sign` (`metal_sign`), with and without fast math.
|
||||
Sign,
|
||||
/// Metal's `saturate` (`metal_saturate`).
|
||||
/// Metal's `saturate`, `clamp(x, +0, 1)`: the device's `NClamp(x, 0, 1)`.
|
||||
Saturate,
|
||||
/// `fmin` (`air.fmin`, `air.fast_fmin`, `air.min`; `llvm.minnum` where [`FloatFn::MinNum`]
|
||||
/// refines to it): Metal's on `float` and `half` (`metal_min_max`), the device's `NMin` on the
|
||||
/// other formats.
|
||||
/// refines to it): the device's `NMin`.
|
||||
Min,
|
||||
/// `fmax`, as [`FloatFn::Min`] with the order reversed.
|
||||
/// `fmax`, as [`FloatFn::Min`] with the order reversed: the device's `NMax`.
|
||||
Max,
|
||||
/// `clamp(x, lo, hi)`: `fmin(fmax(x, lo), hi)` with Metal's `fmin` and `fmax` on `float` and
|
||||
/// `half`, the device's `NClamp` on the other formats.
|
||||
/// `clamp(x, lo, hi)`: the device's `NClamp`.
|
||||
Clamp,
|
||||
/// `min3(a, b, c)`: `fmin(fmin(a, b), c)`, Metal's on `float` and `half`.
|
||||
/// `min3(a, b, c)`: the device's `NMin(NMin(a, b), c)`.
|
||||
Min3,
|
||||
/// `max3(a, b, c)`: `fmax(fmax(a, b), c)`, Metal's on `float` and `half`.
|
||||
/// `max3(a, b, c)`: the device's `NMax(NMax(a, b), c)`.
|
||||
Max3,
|
||||
/// `llvm.minnum`: LLVM's function, the device's `NMin`, on the formats other than `float`.
|
||||
/// Metal's compiler emits it for `a < b ? a : b` under fast math, with every flag; on `float`
|
||||
@@ -1005,10 +1003,13 @@ impl FloatFn {
|
||||
}
|
||||
|
||||
/// Whether the lowering answers Metal at `f32` denormal operands and results itself, whatever
|
||||
/// the device's denormal mode, so it records no `PrecisionNote::DeviceDenormals`: the functions
|
||||
/// that read the operand's exponent field (`sign`, `saturate`, `fract`, `median3`, `fmin`,
|
||||
/// `fmax`, `min3`, `max3`, and `clamp`, which compare a denormal as zero and return the
|
||||
/// operand, and `atan2`, which also flushes a denormal generic result), `copysign` and `fabs`
|
||||
/// the device's denormal mode, or records the device's answer under another note, so it records
|
||||
/// no `PrecisionNote::DeviceDenormals`: the functions that read the operand's exponent field
|
||||
/// (`sign`, `fract` and `median3`, which compare a denormal as zero and return the operand, and
|
||||
/// `atan2`, which also flushes a denormal generic result), `fmin`, `fmax`, `min3`, `max3`,
|
||||
/// `clamp` and `saturate`, the device's `NMin`, `NMax` and `NClamp`, whose comparison of a
|
||||
/// denormal is Metal's where measured (`DriverDeviation::MetalMinMax`) and else
|
||||
/// `PrecisionNote::NativeMinMax`'s bound, `copysign` and `fabs`
|
||||
/// (on `float`, [`sign_on_bits`]), which move bits, `ldexp` (on `float`, [`ldexp_bits`]), which
|
||||
/// reads a denormal operand as the zero of its sign and flushes a denormal result on the bits,
|
||||
/// and `fast::sqrt`, which selects the zero of a denormal operand's sign and has no denormal
|
||||
@@ -1102,12 +1103,13 @@ impl FloatFn {
|
||||
}
|
||||
|
||||
/// Whether the lowering on lanes of format `fmt` answers Metal's NaN bit pattern itself, so it
|
||||
/// records no `PrecisionNote::DeviceNanEncoding` and needs no select: the functions that select
|
||||
/// their NaN (or answer a number for one: `sign`, `saturate`, `fast::sin`, `fast::cos`),
|
||||
/// `median3`, and on `float` and `half`
|
||||
/// `fmin`, `fmax`, `min3`, `max3`, and `clamp` (`metal_min_max`), which return an operand,
|
||||
/// `copysign`, which moves bits, and `fabs` on `float`, which clears the sign bit on the bits
|
||||
/// ([`sign_on_bits`]; a `half` `fabs` answers its canonical NaN by a select).
|
||||
/// records no NaN note of its own: the functions that select their NaN (or answer a number for
|
||||
/// one: `sign`, `saturate`, `fast::sin`, `fast::cos`), `median3`, and on `float` and `half`
|
||||
/// `fmin`, `fmax`, `min3`, `max3`, and
|
||||
/// `clamp`, which return an operand (two NaNs' answer is `PrecisionNote::NativeMinMax`'s where
|
||||
/// the device is not measured to pick Metal's), `copysign`, which moves bits, and `fabs` on
|
||||
/// `float`, which clears the sign bit on the bits ([`sign_on_bits`]; a `half` `fabs` answers
|
||||
/// the device's NaN, noted `NativeNanEncoding`).
|
||||
pub fn metal_nans(self, fmt: FloatFmt) -> bool {
|
||||
use FloatFn as F;
|
||||
if self == F::Abs {
|
||||
@@ -1303,10 +1305,9 @@ impl FloatFn {
|
||||
|
||||
/// Emit float function `op` on `args` (floats of form `f`; `Ldexp`'s exponent is a held `i32` and
|
||||
/// `Dot` gives the scalar), by the device's instructions, and precise `fmod` by `lib`'s routine
|
||||
/// where the module defines it. Metal's operand-picking functions (`metal_min_max`,
|
||||
/// `metal_median3`) test their operands for NaNs by `test`, the test the entry's float modes leave
|
||||
/// exact ([`NanTest::for_modes`]). A `half` `fmod` answers Metal's zero remainder
|
||||
/// (`half_fmod_zero`).
|
||||
/// where the module defines it. Metal's `median3` (`metal_median3`) tests its operands for NaNs by
|
||||
/// `test`, the test the entry's float modes leave exact ([`NanTest::for_modes`]). A `half` `fmod`
|
||||
/// answers Metal's zero remainder (`half_fmod_zero`).
|
||||
pub fn float_fn(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
op: FloatFn,
|
||||
@@ -1584,21 +1585,13 @@ fn float_fn_core(
|
||||
nonfinite_below_one(fb, f, a, r)
|
||||
}
|
||||
F::Sign => metal_sign(fb, f, a),
|
||||
// Metal's `clamp(x, +0, 1)` at every operand: the device's `NClamp` where the minimum and
|
||||
// maximum functions take it (measured to be Metal's, or the device's own,
|
||||
// `PrecisionNote::NativeMinMax`).
|
||||
F::Saturate if metal_picks(f.float_fmt()) && lib.device_min_max() => {
|
||||
// Metal's `clamp(x, +0, 1)`: the device's `NClamp`, Metal's where measured
|
||||
// (`DriverDeviation::MetalMinMax`), else noted `PrecisionNote::NativeMinMax`, as the
|
||||
// minimum and maximum functions below.
|
||||
F::Saturate => {
|
||||
let (z, one) = (fsplat(fb, f, 0.0)?, fsplat(fb, f, 1.0)?);
|
||||
glsl(fb, GlslOp::NClamp, &[a, z, one])
|
||||
}
|
||||
F::Saturate => metal_saturate(fb, f, a),
|
||||
// The device's `NMin`, `NMax` and `NClamp` where they are measured to be Metal's, the arms
|
||||
// below.
|
||||
F::Min | F::Max | F::Clamp | F::Min3 | F::Max3
|
||||
if metal_picks(f.float_fmt()) && !lib.device_min_max() =>
|
||||
{
|
||||
metal_min_max(fb, op, f, test, args)
|
||||
}
|
||||
F::Min | F::MinNum => glsl(fb, GlslOp::NMin, &[a, arg(args, 1)?]),
|
||||
F::Max | F::MaxNum => glsl(fb, GlslOp::NMax, &[a, arg(args, 1)?]),
|
||||
F::Clamp => glsl(fb, GlslOp::NClamp, &[a, arg(args, 1)?, arg(args, 2)?]),
|
||||
@@ -2234,18 +2227,6 @@ fn metal_fract(
|
||||
fb.select(nan, n, r)
|
||||
}
|
||||
|
||||
/// Metal's `saturate(x)` (A1 case aed3faaa, precise and fast alike): `x` clamped to `[0, 1]`,
|
||||
/// with `+0` for either zero, a NaN, and an `f32` denormal ([`flushed`]); a `half` denormal is
|
||||
/// kept. `NClamp` leaves the sign of a zero result to the device.
|
||||
fn metal_saturate(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value> {
|
||||
let (z, one) = (fsplat(fb, f, 0.0)?, fsplat(fb, f, 1.0)?);
|
||||
let lt = bin(fb, BinOp::FOrdLessThan, x, one)?;
|
||||
let r = fb.select(lt, x, one)?;
|
||||
let gt = bin(fb, BinOp::FOrdGreaterThan, x, z)?;
|
||||
let r = fb.select(gt, r, z)?;
|
||||
zero_where_flushed(fb, f, x, r)
|
||||
}
|
||||
|
||||
/// An operand of [`metal_median3`] with the value it compares as.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Compared {
|
||||
@@ -2305,79 +2286,15 @@ fn metal_median3(
|
||||
fb.select(both, b, r)
|
||||
}
|
||||
|
||||
/// Whether Metal's `fmin` and `fmax` family is measured on lanes of format `fmt`, so
|
||||
/// `metal_min_max` emits it: `float` (`nan_minmax` without fast math, `nan_minmax_fast` with
|
||||
/// every flag, and both at zeros and denormals) and `half` (`nan_half`, `nan_half_fast`). `bfloat`
|
||||
/// and `double` keep the device's `NMin`, `NMax`, and `NClamp`.
|
||||
/// Whether Metal's `fmin` and `fmax` family is measured on lanes of format `fmt`: `float`
|
||||
/// (`nan_minmax` without fast math, `nan_minmax_fast` with every flag, and both at zeros and
|
||||
/// denormals) and `half` (`nan_half`, `nan_half_fast`), where the device's `NMin`, `NMax` and
|
||||
/// `NClamp`, which every format takes, record `PrecisionNote::NativeMinMax` unless measured to be
|
||||
/// Metal's. On `bfloat` and `double` Metal's is not measured.
|
||||
pub fn metal_picks(fmt: Option<FloatFmt>) -> bool {
|
||||
matches!(fmt, Some(FloatFmt::F32 | FloatFmt::Half))
|
||||
}
|
||||
|
||||
/// Metal's `fmin(p, q)` (`order` less) or `fmax(p, q)` (greater): `q` where `p` is NaN, else
|
||||
/// [`pick`]'s `p` where `q` is NaN or `p` compares before `q`, else `q`. So two NaNs answer `q`'s
|
||||
/// bits and a tie (`±0`, or an `f32` denormal beside a zero, which compares as one) answers `q`.
|
||||
fn metal_fmin(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
f: Form,
|
||||
test: NanTest,
|
||||
order: BinOp,
|
||||
p: Compared,
|
||||
q: Compared,
|
||||
) -> BResult<Compared> {
|
||||
let p_nan = nan::is_nan(fb, f, test, p.value)?;
|
||||
let r = pick(fb, f, test, order, p, q)?;
|
||||
Ok(Compared {
|
||||
value: fb.select(p_nan, q.value, r.value)?,
|
||||
as_: fb.select(p_nan, q.as_, r.as_)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Metal's `fmin`, `fmax`, `min3`, `max3`, and `clamp` (`op`) of `args` on `float` or `half`
|
||||
/// lanes of form `f` ([`metal_picks`]), the NaN tests by `test`. Measured on every lane of
|
||||
/// `nan_minmax` and `nan_minmax_fast` (`float`, without fast math and with every flag, the same
|
||||
/// answers), their zeros-and-denormals cases, and `nan_half` and `nan_half_fast`: the result is an
|
||||
/// operand, bit for bit ([`metal_fmin`]: a NaN loses, two NaNs and a tie answer the second);
|
||||
/// `min3(a, b, c)` is `fmin(fmin(a, b), c)`, `max3` likewise, and `clamp(x, lo, hi)` is
|
||||
/// `fmin(fmax(x, lo), hi)`. `float` compares the operands [`flushed`] (an `f32` denormal compares
|
||||
/// as a zero) but returns the operand itself. `NMin` and `NMax` leave two NaNs, a tie of zeros,
|
||||
/// and a denormal's comparison to the device.
|
||||
pub(super) fn metal_min_max(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
op: FloatFn,
|
||||
f: Form,
|
||||
test: NanTest,
|
||||
args: &[Value],
|
||||
) -> BResult<Value> {
|
||||
use FloatFn as F;
|
||||
let compared = |fb: &mut FunctionBuilder<'_>, i: usize| -> BResult<Compared> {
|
||||
let x = arg(args, i)?;
|
||||
Ok(Compared {
|
||||
value: x,
|
||||
as_: zero_where_flushed(fb, f, x, x)?,
|
||||
})
|
||||
};
|
||||
let (less, greater) = (BinOp::FOrdLessThan, BinOp::FOrdGreaterThan);
|
||||
let (a, b) = (compared(fb, 0)?, compared(fb, 1)?);
|
||||
let r = match op {
|
||||
F::Min => metal_fmin(fb, f, test, less, a, b)?,
|
||||
F::Max => metal_fmin(fb, f, test, greater, a, b)?,
|
||||
F::Min3 | F::Max3 => {
|
||||
let order = if op == F::Min3 { less } else { greater };
|
||||
let ab = metal_fmin(fb, f, test, order, a, b)?;
|
||||
let c = compared(fb, 2)?;
|
||||
metal_fmin(fb, f, test, order, ab, c)?
|
||||
}
|
||||
F::Clamp => {
|
||||
let low = metal_fmin(fb, f, test, greater, a, b)?;
|
||||
let c = compared(fb, 2)?;
|
||||
metal_fmin(fb, f, test, less, low, c)?
|
||||
}
|
||||
// Not one of Metal's minimum and maximum functions.
|
||||
_ => return Err(BuildError::Type(TypeRule::FunctionSignature)),
|
||||
};
|
||||
Ok(r.value)
|
||||
}
|
||||
|
||||
/// The largest magnitude Metal's `fast::sin` and `fast::cos` evaluate: `float(π/2) · 2^22`
|
||||
/// (`0x4ac90fdb`), past which the quadrant index no longer fits in 22 bits.
|
||||
pub(super) const FAST_TRIG_LIMIT: f32 = 6_588_397.5;
|
||||
|
||||
@@ -60,12 +60,10 @@
|
||||
//! `f32` denormals whatever the device's modes, and the normalized and sRGB `air.unpack`/`air.pack`
|
||||
//! conversions are exact integer sequences and Metal's tables.
|
||||
//!
|
||||
//! A NaN result is Metal's ([`nan`]): `float` `+ - * /`, the fused multiply-add on `OpFmaKHR`, and
|
||||
//! the functions whose NaN Metal canonicalizes answer `0x7FC00000`, and `half` `+`, `*`, fused
|
||||
//! multiply-add, and a `float` narrowed to `half` the canonical `half` NaN `0x7E00`, which the
|
||||
//! lowering selects where the result's bits are observed unless the profile's measured device fact
|
||||
//! leaves it to the device (`NanEncoding::MetalCanonical`); the functions whose NaN carries an
|
||||
//! operand's sign or bits answer it on every profile.
|
||||
//! A NaN result's bits are the device's ([`nan`]): where Metal answers one the device is not
|
||||
//! measured to answer (its canonical `0x7FC00000` or `0x7E00` on a device without
|
||||
//! `NanEncoding::MetalCanonical`, and a NaN that carries an operand's sign or bits on every
|
||||
//! device), the module records `PrecisionNote::NativeNanEncoding`.
|
||||
|
||||
pub mod aggregate;
|
||||
pub mod chunk;
|
||||
@@ -104,7 +102,7 @@ use crate::air::ir::{
|
||||
};
|
||||
use crate::air::Entry;
|
||||
use crate::budget::Meter;
|
||||
use crate::device::profile::{DriverWorkaround, FloatFunctions, MinMaxRoute, NanEncoding};
|
||||
use crate::device::profile::{DriverWorkaround, FloatFunctions, NanEncoding};
|
||||
use crate::device::{DeviceProfile, FloatWidth};
|
||||
use crate::error::Error;
|
||||
use crate::lower::access;
|
||||
@@ -397,10 +395,6 @@ pub enum ArithStrategy {
|
||||
/// `air.fast_sincos` on `float`: [`FloatFn::FastSin`] and [`FloatFn::FastCos`], which
|
||||
/// flush past the last evaluated quadrant as Metal's `fast::sincos` does.
|
||||
fast: bool,
|
||||
/// Metal's NaN selected for the sine and for the cosine, where Metal answers one the
|
||||
/// device may not: the answers of the `sin` and `cos` the call computes, as `with_nan`
|
||||
/// selects them for those calls.
|
||||
nan: [Option<nan::NanAnswer>; 2],
|
||||
},
|
||||
/// `air.dot` of chunked vectors of `lanes` lanes of `elem` ([`chunk::dot`]).
|
||||
ChunkedDot {
|
||||
@@ -417,13 +411,6 @@ pub enum ArithStrategy {
|
||||
elem: Form,
|
||||
fma: fma::Fma,
|
||||
},
|
||||
/// A float result with Metal's NaN selected where it is a NaN ([`nan`]): the value of `of`, a
|
||||
/// result of `form`, then [`nan::select`] of `answer`. Named as `of`.
|
||||
Nan {
|
||||
of: Box<ArithStrategy>,
|
||||
answer: nan::NanAnswer,
|
||||
form: Form,
|
||||
},
|
||||
/// An operation with a wide integer operand or result on a profile without `shaderInt64`,
|
||||
/// on the two words of each value ([`wide`]).
|
||||
Wide(wide::WideOp),
|
||||
@@ -454,12 +441,7 @@ pub enum ArithStrategy {
|
||||
impl FamilyStrategy for ArithStrategy {
|
||||
fn name(&self, _: &FamilyPlans) -> Cow<'static, str> {
|
||||
use ArithStrategy as S;
|
||||
// The NaN select is its operation's: the census names the operation.
|
||||
let mut s = self;
|
||||
while let S::Nan { of, .. } = s {
|
||||
s = of;
|
||||
}
|
||||
Cow::Borrowed(match s {
|
||||
Cow::Borrowed(match self {
|
||||
S::Int { form, .. } | S::IntCompare { form, .. } if form.legalized() => {
|
||||
"arith.int.legalized"
|
||||
}
|
||||
@@ -549,8 +531,6 @@ impl FamilyStrategy for ArithStrategy {
|
||||
S::Forward(_) => "arith.aggregate.forward",
|
||||
S::Null(_) => "arith.aggregate.null",
|
||||
S::Member { .. } => "arith.aggregate.member",
|
||||
// Named as its operation: unwrapped above.
|
||||
S::Nan { .. } => "arith.nan",
|
||||
})
|
||||
}
|
||||
|
||||
@@ -642,12 +622,9 @@ impl FamilyStrategy for ArithStrategy {
|
||||
let lanes = u32::from(floats.lanes);
|
||||
64 + srgb + 400 + 24 * lanes + narrow::round_words(*floats)
|
||||
}
|
||||
S::SinCos {
|
||||
shape,
|
||||
store,
|
||||
fast,
|
||||
nan,
|
||||
} => chunk::sin_cos_words(*shape, *fast, *nan).saturating_add(store.words()),
|
||||
S::SinCos { shape, store, fast } => {
|
||||
chunk::sin_cos_words(*shape, *fast).saturating_add(store.words())
|
||||
}
|
||||
S::ChunkedDot { lanes, elem, .. } => chunk::dot_words(*lanes, *elem),
|
||||
S::ChunkedChain { lanes, elem, fma } => {
|
||||
chunk::dot_chain_words(*lanes, *elem, fma.words())
|
||||
@@ -681,7 +658,6 @@ impl FamilyStrategy for ArithStrategy {
|
||||
S::LaneShuffle { out, .. } => chunk::move_words(*out, chunk::LaneMove::Shuffle, false),
|
||||
S::WordBitcast { from, to } => chunk::bitcast_words(*from, *to),
|
||||
S::Wide(w) => w.words(),
|
||||
S::Nan { of, answer, form } => of.words().saturating_add(answer.words(*form)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -821,26 +797,18 @@ pub struct ArithPlan {
|
||||
/// Whether [`ArithPlan::quantize`] is the device's own rounding (native half rounding,
|
||||
/// [`narrow::native_rounding`]), decided with it by [`finish`].
|
||||
pub native_half: bool,
|
||||
/// Whether a `half` texel keeps the NaN the device decoded under that native rounding too
|
||||
/// (`narrow::round_texel`): where the profile's NaN is the translation's to answer as Metal's
|
||||
/// (`NanEncoding::Device`, the policy's `NanMinMaxPolicy::Exact`), decided by [`finish`].
|
||||
pub texel_nans: bool,
|
||||
/// Whether a `half`'s NaN bits are left to the device's conversion where the module rounds
|
||||
/// through the conversion under the float controls ([`QuantizeForm::Controlled`]): a `half`
|
||||
/// read from its bits is the device's widening of them (`narrow::from_bits`), and a `half`
|
||||
/// texel takes the rounding's NaN (`narrow::round_texel`). Where the profile's NaN is the
|
||||
/// device's own (`NanEncoding::Native`, the policy's `NanMinMaxPolicy::Native`, the default),
|
||||
/// decided by [`finish`].
|
||||
/// texel takes the rounding's NaN (`narrow::round_texel`). Decided by [`finish`], on every
|
||||
/// profile that rounds so.
|
||||
pub native_half_nans: bool,
|
||||
/// Whether Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` on `float` or `half`
|
||||
/// takes the device's `NMin`, `NMax` or `NClamp`, measured to be Metal's
|
||||
/// takes the device's `NMin`, `NMax` or `NClamp` measured to be Metal's
|
||||
/// (`DriverDeviation::MetalMinMax`), recorded at selection: the module then requires
|
||||
/// `VkProperty::MetalMinMax`, and every such call in it takes those instructions.
|
||||
/// `VkProperty::MetalMinMax`. Every such call takes those instructions on every profile; one
|
||||
/// not measured so records `NativeMinMax` ([`native_min_max`]).
|
||||
pub device_min_max: bool,
|
||||
/// Whether those functions take the device's `NMin`, `NMax` or `NClamp` as native device
|
||||
/// maths ([`native_min_max`]), recorded at selection: the module records `NativeMinMax` and
|
||||
/// requires no property.
|
||||
pub native_min_max: bool,
|
||||
/// Whether a `half` `+`, `-` or `*` takes the device's 16-bit arithmetic
|
||||
/// ([`ArithStrategy::F16`]), measured to be Metal's (`DriverDeviation::MetalHalfArithmetic`),
|
||||
/// recorded at selection: the module then requires `VkProperty::MetalHalfArithmetic`.
|
||||
@@ -944,12 +912,8 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
cx.families.arith.quantize = narrow::quantize_form(cx.profile);
|
||||
cx.families.arith.native_half =
|
||||
narrow::native_rounding(cx.profile, cx.families.arith.quantize).is_some();
|
||||
// Where the NaN switch asks for Metal's NaN, a texel's NaN is its own through that rounding.
|
||||
cx.families.arith.texel_nans = nan::encoding(cx.profile) == NanEncoding::Device;
|
||||
// Under the float controls a `half`'s NaN is the device's conversion's where the profile
|
||||
// leaves NaN bits to the device.
|
||||
cx.families.arith.native_half_nans = cx.families.arith.quantize == QuantizeForm::Controlled
|
||||
&& nan::encoding(cx.profile) == NanEncoding::Native;
|
||||
// Under the float controls a `half`'s NaN is the device's conversion's.
|
||||
cx.families.arith.native_half_nans = cx.families.arith.quantize == QuantizeForm::Controlled;
|
||||
cx.families.arith.mask = if cx
|
||||
.profile
|
||||
.fields()
|
||||
@@ -1368,8 +1332,8 @@ pub fn float_binop_notes(
|
||||
p.fields().float_functions == FloatFunctions::Metal,
|
||||
));
|
||||
}
|
||||
// A `float` `+ - *` and remainder answer Metal's NaN: the device's, where the profile states
|
||||
// it is, else selected ([`nan`]), and leave their denormals to the device: `+ - *` but where it
|
||||
// A `float` `+ - *` and remainder answer the device's NaN, noted where the profile does not
|
||||
// state it is Metal's ([`nan`]), and leave their denormals to the device: `+ - *` but where it
|
||||
// is measured to read them as Metal does ([`leave_denormals`]), a remainder on every device.
|
||||
// Metal's `half` and `bfloat` remainders are not measured.
|
||||
let answer = binop_answer(op, fmt);
|
||||
@@ -1383,8 +1347,9 @@ pub fn float_binop_notes(
|
||||
Some(OpNotes::everywhere(notes))
|
||||
}
|
||||
|
||||
/// The NaN Metal answers for the float binary operator `op` on format `fmt` that its lowering
|
||||
/// selects ([`with_nan`]): `float` `frem`'s canonical NaN beside [`nan::binary_answer`]'s.
|
||||
/// The NaN Metal answers for the float binary operator `op` on format `fmt`, which its lowering
|
||||
/// leaves to the device ([`with_nan`]): `float` `frem`'s canonical NaN beside
|
||||
/// [`nan::binary_answer`]'s.
|
||||
fn binop_answer(op: AirBin, fmt: FloatFmt) -> Option<nan::NanAnswer> {
|
||||
match (op, fmt) {
|
||||
(AirBin::FRem, FloatFmt::F32) => Some(nan::NanAnswer::Canonical),
|
||||
@@ -1392,36 +1357,22 @@ fn binop_answer(op: AirBin, fmt: FloatFmt) -> Option<nan::NanAnswer> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Strategy `s` of instruction `at`, a result of form `form`, with Metal's NaN `answer` selected
|
||||
/// ([`nan`]): where Metal answers one the lowering does not, the profile does not leave it to the
|
||||
/// device, and the result's NaN bits may be observed. Under native device maths
|
||||
/// ([`NanEncoding::Native`]) every answer is left to the device, noted `NativeNanEncoding`.
|
||||
/// Strategy `s`, whose result's NaN Metal answers as `answer` where the lowering does not answer
|
||||
/// it itself, with that NaN left to the device ([`nan`]): noted `NativeNanEncoding` where the
|
||||
/// device is not measured to answer it ([`nan::NanAnswer::device_answers`]).
|
||||
fn with_nan(
|
||||
cx: &mut SelectCx<'_>,
|
||||
at: InstId,
|
||||
s: ArithStrategy,
|
||||
answer: Option<nan::NanAnswer>,
|
||||
form: Form,
|
||||
) -> ArithStrategy {
|
||||
note_native_nan(cx, answer);
|
||||
match answer {
|
||||
Some(answer)
|
||||
if !answer.left_to(nan::encoding(cx.profile)) && cx.nan_payload_observed(at) =>
|
||||
{
|
||||
ArithStrategy::Nan {
|
||||
of: Box::new(s),
|
||||
answer,
|
||||
form,
|
||||
}
|
||||
}
|
||||
_ => s,
|
||||
}
|
||||
s
|
||||
}
|
||||
|
||||
/// Record `NativeNanEncoding` where Metal answers a NaN (`answer`) that native device maths
|
||||
/// leaves to the device ([`NanEncoding::Native`]).
|
||||
/// Record `NativeNanEncoding` where Metal answers a NaN (`answer`) the device is not measured to
|
||||
/// answer ([`nan::NanAnswer::device_answers`]).
|
||||
fn note_native_nan(cx: &mut SelectCx<'_>, answer: Option<nan::NanAnswer>) {
|
||||
if answer.is_some() && nan::encoding(cx.profile) == NanEncoding::Native {
|
||||
if answer.is_some_and(|a| !a.device_answers(nan::encoding(cx.profile))) {
|
||||
cx.precision.insert(PrecisionNote::NativeNanEncoding);
|
||||
}
|
||||
}
|
||||
@@ -1549,14 +1500,15 @@ fn select_in(
|
||||
// `x - y * trunc(x / y)` of its precise quotient, which the device's `OpFRem` is at
|
||||
// the device's precision, below.
|
||||
Held::Float(FloatFmt::F32) if *op == AirBin::FRem && every_flag(*fmf) => {
|
||||
return select_float_fn(cx, at, (FloatFn::Fmod, true), *fmf, f);
|
||||
return select_float_fn(cx, (FloatFn::Fmod, true), *fmf, f);
|
||||
}
|
||||
// Metal divides `float` without `arcp` correctly rounded, a denormal operand
|
||||
// read as a zero and a denormal quotient flushed (a probe cases 914cc4d2, 711cc190,
|
||||
// and c10cba13, every lane), and `half` under every flag set rounded once from the
|
||||
// exact quotient (4c363561, 54f0fe8e, every lane): the device's quotient, its
|
||||
// divisor kept in Vulkan's range ([`divide::native`]), its NaN Metal's canonical
|
||||
// one. No device is measured to read a quotient's denormals as Metal does.
|
||||
// divisor kept in Vulkan's range ([`divide::native`]), its NaN the device's (Metal
|
||||
// answers its canonical one). No device is measured to read a quotient's denormals
|
||||
// as Metal does.
|
||||
Held::Float(fmt) if divide::precise(*op, fmt, *fmf) => {
|
||||
let notes = float_binop_notes(*op, fmt, *fmf, cx.profile);
|
||||
record(cx, notes.unwrap_or_default());
|
||||
@@ -1564,7 +1516,7 @@ fn select_in(
|
||||
fp_env(cx, *fmf, f);
|
||||
leave_denormals(cx, f, denormal::Covered::Never);
|
||||
let s = S::NativeDivide { form: f };
|
||||
with_nan(cx, at, s, Some(nan::NanAnswer::Canonical), f)
|
||||
with_nan(cx, s, Some(nan::NanAnswer::Canonical))
|
||||
}
|
||||
Held::Float(fmt) if op.is_float() => {
|
||||
let notes = float_binop_notes(*op, fmt, *fmf, cx.profile);
|
||||
@@ -1586,15 +1538,15 @@ fn select_in(
|
||||
// (a probe cases 914cc4d2 and 711cc190, every flag set measured, every lane),
|
||||
// its reciprocal flushing past `2^126` and at a denormal `y`: the device's
|
||||
// `OpFDiv(x, y)`, Metal's own where the device's functions are Metal's in an
|
||||
// entry Metal compiles with fast math. Its NaN is the device's where the
|
||||
// profile leaves NaNs to it, else Metal's canonical one, selected; its `f32`
|
||||
// denormals the device's ([`float_binop_notes`]).
|
||||
// entry Metal compiles with fast math. Its NaN is the device's, noted where it
|
||||
// is not measured to be Metal's canonical one; its `f32` denormals the
|
||||
// device's ([`float_binop_notes`]).
|
||||
if *op == AirBin::FDiv
|
||||
&& fmf.contains(FastMath::ARCP)
|
||||
&& f.float_fmt() == Some(FloatFmt::F32)
|
||||
{
|
||||
let s = S::FastDivide { form: f, contract };
|
||||
with_nan(cx, at, s, Some(nan::NanAnswer::Canonical), f)
|
||||
with_nan(cx, s, Some(nan::NanAnswer::Canonical))
|
||||
} else if let Some(basis) = f16_arithmetic(cx.profile, *op, f) {
|
||||
// The device's own `half` arithmetic, Metal's in the forms that keep it
|
||||
// apart, which the AIR's flags allow whatever they are. Only the measured
|
||||
@@ -1602,7 +1554,7 @@ fn select_in(
|
||||
// its entry declares.
|
||||
cx.families.arith.f16_arith |= basis == F16Basis::Measured;
|
||||
let s = S::F16 { op: *op, form: f };
|
||||
with_nan(cx, at, s, nan::binary_answer(*op, fmt), f)
|
||||
with_nan(cx, s, nan::binary_answer(*op, fmt))
|
||||
} else {
|
||||
let s = S::Float {
|
||||
op: *op,
|
||||
@@ -1615,7 +1567,7 @@ fn select_in(
|
||||
if matches!(op, AirBin::FAdd | AirBin::FSub | AirBin::FMul) {
|
||||
leave_denormals(cx, f, denormal::Covered::Deviation);
|
||||
}
|
||||
with_nan(cx, at, s, binop_answer(*op, fmt), f)
|
||||
with_nan(cx, s, binop_answer(*op, fmt))
|
||||
}
|
||||
}
|
||||
_ => return Err(cx.invariant("a binary operator on mismatched operands")),
|
||||
@@ -1631,7 +1583,7 @@ fn select_in(
|
||||
fp_env(cx, *fmf, f);
|
||||
// Metal's `half` `fneg` answers the canonical NaN.
|
||||
let nan = f.float_fmt().and_then(nan::fneg_answer);
|
||||
with_nan(cx, at, S::FNeg { form: f, bits }, nan, f)
|
||||
with_nan(cx, S::FNeg { form: f, bits }, nan)
|
||||
}
|
||||
InstKind::ICmp { pred, a, .. } => {
|
||||
let f = form_in(cx, *a, chunk)?;
|
||||
@@ -1654,7 +1606,7 @@ fn select_in(
|
||||
form: f,
|
||||
}
|
||||
}
|
||||
InstKind::Cast { op, v } => select_cast(cx, at, *op, *v, inst, chunk)?,
|
||||
InstKind::Cast { op, v } => select_cast(cx, *op, *v, inst, chunk)?,
|
||||
InstKind::Select { .. } => S::Select,
|
||||
InstKind::Freeze(v) => match cx.constant(*v) {
|
||||
Some(LoweredConst::Undef(_)) => S::Zero(result),
|
||||
@@ -1715,11 +1667,10 @@ fn select_in(
|
||||
})
|
||||
}
|
||||
|
||||
/// Select the cast `op` of `v`, instruction `at`; with `chunk`, for one chunk (as
|
||||
/// Select the cast `op` of `v`, instruction `inst`; with `chunk`, for one chunk (as
|
||||
/// [`select_in`]).
|
||||
fn select_cast(
|
||||
cx: &mut SelectCx<'_>,
|
||||
at: InstId,
|
||||
op: CastOp,
|
||||
v: Value,
|
||||
inst: &Inst,
|
||||
@@ -1747,7 +1698,7 @@ fn select_cast(
|
||||
(Some(a), Some(b)) => nan::cast_answer(op, a, b),
|
||||
_ => None,
|
||||
};
|
||||
return Ok(with_nan(cx, at, s, answer, to));
|
||||
return Ok(with_nan(cx, s, answer));
|
||||
}
|
||||
CastOp::FPToUI => CastKind::FpToUi,
|
||||
CastOp::FPToSI => CastKind::FpToSi,
|
||||
@@ -2057,7 +2008,7 @@ fn select_call(
|
||||
Callee::Air {
|
||||
op: AirIntrinsic::Convert(c),
|
||||
..
|
||||
} => return select_convert(cx, at, inst, call, c, chunk),
|
||||
} => return select_convert(cx, inst, call, c, chunk),
|
||||
Callee::Air {
|
||||
op: AirIntrinsic::Pack(p),
|
||||
..
|
||||
@@ -2097,16 +2048,14 @@ fn select_call(
|
||||
}
|
||||
ArithStrategy::IntFn { f: op, form: f }
|
||||
}
|
||||
Fun::Float(op) => select_float_fn(cx, at, (op, fast), call.fmf, f)?,
|
||||
Fun::Float(op) => select_float_fn(cx, (op, fast), call.fmf, f)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// The strategy of float function `op` (`fast` its `fast_` variant) with fast-math flags `fmf`
|
||||
/// on operands of form `f`, the result of instruction `at`: a math call's, or LLVM's `frem`'s,
|
||||
/// which is `fmod`.
|
||||
/// on operands of form `f`: a math call's, or LLVM's `frem`'s, which is `fmod`.
|
||||
fn select_float_fn(
|
||||
cx: &mut SelectCx<'_>,
|
||||
at: InstId,
|
||||
(op, fast): (FloatFn, bool),
|
||||
fmf: FastMath,
|
||||
f: Form,
|
||||
@@ -2120,7 +2069,6 @@ fn select_float_fn(
|
||||
let arith = &mut cx.families.arith;
|
||||
arith.fmod_uses |= fmod;
|
||||
arith.device_min_max |= device_min_max(cx.profile, op, f);
|
||||
arith.native_min_max |= native_min_max(cx.profile, op, f);
|
||||
}
|
||||
if let FloatLowering::Fma(fma)
|
||||
| FloatLowering::FastFmod(fma)
|
||||
@@ -2129,11 +2077,6 @@ fn select_float_fn(
|
||||
{
|
||||
cx.families.arith.take_fma(fma);
|
||||
}
|
||||
// `dot`'s result is a scalar.
|
||||
let result = match lowered.how {
|
||||
FloatLowering::Fn(FloatFn::Dot) | FloatLowering::Dot(_) => f.scalar_form(),
|
||||
_ => f,
|
||||
};
|
||||
let s = match lowered.how {
|
||||
FloatLowering::Fma(fma) => ArithStrategy::Fma(fma),
|
||||
FloatLowering::FastFmod(fma) => ArithStrategy::FastFmod { fma },
|
||||
@@ -2150,7 +2093,7 @@ fn select_float_fn(
|
||||
if let Some(covered) = call_coverage(lowered.how, facts) {
|
||||
leave_denormals(cx, f, covered);
|
||||
}
|
||||
Ok(with_nan(cx, at, s, lowered.nan, result))
|
||||
Ok(with_nan(cx, s, lowered.nan))
|
||||
}
|
||||
|
||||
/// Where the device reads the `f32` denormals of a float function call lowered as `how` on a
|
||||
@@ -2188,9 +2131,9 @@ fn coverage_left(how: FloatLowering, f: Form, facts: FloatFacts) -> bool {
|
||||
}
|
||||
|
||||
/// Whether Metal's minimum and maximum function `op` on lanes of form `f` takes the device's
|
||||
/// `NMin`, `NMax` or `NClamp`: `fmin`, `fmax`, `min3`, `max3`, `clamp` and `saturate`
|
||||
/// ([`min_max_family`]) on `float` and `half` ([`math::metal_picks`]) where profile `p` takes
|
||||
/// `DriverDeviation::MetalMinMax`.
|
||||
/// `NMin`, `NMax` or `NClamp` measured to be Metal's: `fmin`, `fmax`, `min3`, `max3`, `clamp` and
|
||||
/// `saturate` ([`min_max_family`]) on `float` and `half` ([`math::metal_picks`]) where profile `p`
|
||||
/// takes `DriverDeviation::MetalMinMax`.
|
||||
fn device_min_max(p: &DeviceProfile, op: FloatFn, f: Form) -> bool {
|
||||
use crate::error::DriverDeviation;
|
||||
min_max_family(op)
|
||||
@@ -2215,13 +2158,13 @@ fn min_max_family(op: FloatFn) -> bool {
|
||||
}
|
||||
|
||||
/// Whether Metal's minimum and maximum function `op` on lanes of form `f` takes the device's
|
||||
/// `NMin`, `NMax` or `NClamp` as they are: one of [`device_min_max`]'s functions on a profile whose
|
||||
/// picks are the device's (`MinMaxRoute::Native`: not measured to be Metal's, and the policy's
|
||||
/// `NanMinMaxPolicy::Native`), noted `NativeMinMax`.
|
||||
fn native_min_max(p: &DeviceProfile, op: FloatFn, f: Form) -> bool {
|
||||
min_max_family(op)
|
||||
&& math::metal_picks(f.float_fmt())
|
||||
&& p.fields().min_max == MinMaxRoute::Native
|
||||
/// `NMin`, `NMax` or `NClamp` as they are, not measured to be Metal's, noted `NativeMinMax`: one of
|
||||
/// [`device_min_max`]'s functions on a profile that does not take `DriverDeviation::MetalMinMax`
|
||||
/// (`native_min_max`, [`FloatFacts::native_min_max`]), and `saturate` on every other float
|
||||
/// format, which no device is measured to answer as Metal's `clamp(x, +0, 1)`.
|
||||
fn native_min_max(op: FloatFn, f: Form, native_min_max: bool) -> bool {
|
||||
let picks = math::metal_picks(f.float_fmt());
|
||||
min_max_family(op) && ((picks && native_min_max) || (op == FloatFn::Saturate && !picks))
|
||||
}
|
||||
|
||||
/// Why the device's 16-bit `+ - *` answers as Metal's `half` arithmetic ([`f16_arithmetic`]).
|
||||
@@ -2295,10 +2238,10 @@ struct FloatFacts {
|
||||
metal_functions: bool,
|
||||
/// Whether the device reads `f32` denormals as Metal does ([`denormal::device_flushes`]).
|
||||
device_denormals: bool,
|
||||
/// Whether the profile leaves Metal's NaN to the device ([`NanEncoding::Native`]).
|
||||
nan_native: bool,
|
||||
/// Whether Metal's minimum and maximum functions are the device's as they are
|
||||
/// (`MinMaxRoute::Native`, [`native_min_max`]).
|
||||
/// Which NaN the device's arithmetic answers ([`nan::encoding`]).
|
||||
nans: NanEncoding,
|
||||
/// Whether Metal's minimum and maximum functions are the device's not measured to be Metal's:
|
||||
/// the profile does not take `DriverDeviation::MetalMinMax` ([`native_min_max`]).
|
||||
native_min_max: bool,
|
||||
}
|
||||
|
||||
@@ -2309,8 +2252,8 @@ impl FloatFacts {
|
||||
routes: fma::routes(p),
|
||||
metal_functions: p.fields().float_functions == FloatFunctions::Metal,
|
||||
device_denormals: denormal::device_flushes(p),
|
||||
nan_native: nan::encoding(p) == NanEncoding::Native,
|
||||
native_min_max: p.fields().min_max == MinMaxRoute::Native,
|
||||
nans: nan::encoding(p),
|
||||
native_min_max: !p.takes_driver_deviation(crate::error::DriverDeviation::MetalMinMax),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2439,10 +2382,10 @@ fn native_fma(fma: fma::Fma) -> OpNotes {
|
||||
/// The lowering of float function `op` called with the `fast_` prefix if `fast` and with
|
||||
/// fast-math flags `fmf`, on operands of form `f`, on a profile with float facts `facts`
|
||||
/// ([`FloatFacts`]); `None` where the form refuses the function (it is not a float, or a `double`
|
||||
/// the function does not take). Where the profile leaves NaNs to the device a Metal NaN the call
|
||||
/// answers is the device's, noted `NativeNanEncoding` (as [`with_nan`] records it), and where its
|
||||
/// picks are the device's Metal's minimum and maximum functions are the device's
|
||||
/// ([`native_min_max`]), noted `NativeMinMax`; the `f32` denormals the device reads where the
|
||||
/// the function does not take). A Metal NaN the call answers is the device's, noted
|
||||
/// `NativeNanEncoding` where the device is not measured to answer it (as [`with_nan`] records it),
|
||||
/// and Metal's minimum and maximum functions are the device's, noted `NativeMinMax` where they are
|
||||
/// not measured to be Metal's ([`native_min_max`]); the `f32` denormals the device reads where the
|
||||
/// table covers the call but the profile lacks the deviation are noted `DeviceDenormals`
|
||||
/// ([`coverage_left`]).
|
||||
fn float_call(
|
||||
@@ -2454,12 +2397,11 @@ fn float_call(
|
||||
) -> Option<FloatCall> {
|
||||
let mut call = float_call_of(op, fast, fmf, f, facts)?;
|
||||
let mut native = BTreeSet::new();
|
||||
if call.nan.is_some() && facts.nan_native {
|
||||
if call.nan.is_some_and(|a| !a.device_answers(facts.nans)) {
|
||||
native.insert(PrecisionNote::NativeNanEncoding);
|
||||
}
|
||||
if let FloatLowering::Fn(op) = call.how {
|
||||
let picks = min_max_family(op) && math::metal_picks(f.float_fmt());
|
||||
if picks && facts.native_min_max {
|
||||
if native_min_max(op, f, facts.native_min_max) {
|
||||
native.insert(PrecisionNote::NativeMinMax);
|
||||
}
|
||||
}
|
||||
@@ -2496,9 +2438,9 @@ fn float_call_of(
|
||||
// `FastMathRewrites`.
|
||||
if matches!(op, FloatFn::Fma | FloatFn::MulAdd) {
|
||||
if let Some(fma) = fma::Fma::by(routes, f) {
|
||||
// The device's `float` instruction answers the device's NaN, so Metal's is selected; a
|
||||
// `half` result's rounding answers the device's `half` NaN on every route, so Metal's
|
||||
// is selected where it is measured.
|
||||
// The device's `float` instruction answers the device's NaN, noted; a `half` result's
|
||||
// rounding answers the device's `half` NaN on every route, noted where Metal's is
|
||||
// measured.
|
||||
let khr = fma.route.device_float();
|
||||
let nan = match f.float_fmt() {
|
||||
Some(FloatFmt::Half) => {
|
||||
@@ -2516,7 +2458,7 @@ fn float_call_of(
|
||||
// Metal's `mix(x, y, t)` on `float` and `half` is `fma(t, y, fma(-t, x, x))`, with and without
|
||||
// fast-math flags. Where the device's functions are Metal's, and on `half` by the measured
|
||||
// 16-bit fused multiply-add, Metal's own form of its own fused multiply-adds answers it, whose
|
||||
// NaN is the device's `float` instruction's, which is selected, and a `half` result's as the
|
||||
// NaN is the device's `float` instruction's, which is noted, and a `half` result's as the
|
||||
// `half` `fma`'s.
|
||||
if op == FloatFn::Mix {
|
||||
if let Some(fma) = fma::Fma::by(routes, f) {
|
||||
@@ -2557,8 +2499,8 @@ fn float_call_of(
|
||||
// fast-math flags, `b * (a + c)` for `dot(float2(a, b), float2(b, c))`, `NativeDot`). Where the
|
||||
// profile's `float` functions are Metal's, a `float` `OpDot` reaches Metal's own `dot`, the
|
||||
// same chain; a `half` there would be summed in its `float` container, so it takes the chain,
|
||||
// as a `half` one by the measured 16-bit fused multiply-add does. Metal's NaN is selected as
|
||||
// for any function.
|
||||
// as a `half` one by the measured 16-bit fused multiply-add does. Its NaN is the device's,
|
||||
// noted as for any function.
|
||||
if op == FloatFn::Dot {
|
||||
if let Some(fma) = fma::Fma::by(routes, f.scalar_form()) {
|
||||
let nan = f
|
||||
@@ -2602,7 +2544,7 @@ fn float_call_of(
|
||||
});
|
||||
}
|
||||
}
|
||||
// The NaN Metal answers, selected where the lowering does not answer it itself.
|
||||
// The NaN Metal answers, where the lowering does not answer it itself.
|
||||
let answer = f
|
||||
.float_fmt()
|
||||
.and_then(|fmt| nan::function_answer(op, fast, every_flag(fmf), fmt));
|
||||
@@ -2746,14 +2688,11 @@ pub(super) fn select_sincos(
|
||||
);
|
||||
let fast = symbol_fast && f.float_fmt() == Some(FloatFmt::F32);
|
||||
let (sin, cos) = chunk::sin_cos_fns(fast);
|
||||
// Each result takes the NaN its function answers as a call of its own (`float_call`'s rule):
|
||||
// Metal's `sincos` answers its `sin` and `cos`, word for word (cases 7b283404 and f6524207,
|
||||
// every pair), so where Metal's answer is measured it is selected; otherwise the device's NaN
|
||||
// is noted. The cosine is stored, so its bits are observed. Each records its notes as a call of
|
||||
// its own (`function_notes`).
|
||||
// Each result's NaN is the device's, noted as a call of its own's (`float_call`'s rule): Metal's
|
||||
// `sincos` answers its `sin` and `cos`, word for word (cases 7b283404 and f6524207, every
|
||||
// pair). Each records its notes as a call of its own (`function_notes`).
|
||||
let metal_functions = cx.profile.fields().float_functions == FloatFunctions::Metal;
|
||||
let mut nans = [None; 2];
|
||||
for (slot, (op, stored)) in nans.iter_mut().zip([(sin, false), (cos, true)]) {
|
||||
for op in [sin, cos] {
|
||||
let answer = f
|
||||
.float_fmt()
|
||||
.and_then(|fmt| nan::function_answer(op, symbol_fast, every_flag(call.fmf), fmt));
|
||||
@@ -2766,9 +2705,7 @@ pub(super) fn select_sincos(
|
||||
(!op.metal_denormals(), !metal_nans && answer.is_none()),
|
||||
);
|
||||
record(cx, notes);
|
||||
let observed = stored || cx.nan_payload_observed(at);
|
||||
note_native_nan(cx, answer.filter(|_| !metal_nans));
|
||||
*slot = answer.filter(|a| !metal_nans && !a.left_to(nan::encoding(cx.profile)) && observed);
|
||||
}
|
||||
fp_env(cx, call.fmf, f);
|
||||
let align = cx
|
||||
@@ -2791,7 +2728,6 @@ pub(super) fn select_sincos(
|
||||
shape,
|
||||
store: Box::new(store),
|
||||
fast,
|
||||
nan: nans,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -2842,7 +2778,6 @@ fn select_pack(
|
||||
|
||||
fn select_convert(
|
||||
cx: &mut SelectCx<'_>,
|
||||
at: InstId,
|
||||
inst: &Inst,
|
||||
call: &crate::air::ir::Call,
|
||||
c: &Convert,
|
||||
@@ -2928,7 +2863,7 @@ fn select_convert(
|
||||
(ConvertKind::Float, Some(a), Some(b)) => nan::convert_answer(a, b),
|
||||
_ => None,
|
||||
};
|
||||
Ok(with_nan(cx, at, s, nan, to))
|
||||
Ok(with_nan(cx, s, nan))
|
||||
}
|
||||
|
||||
// ---- Emission ----
|
||||
@@ -3001,16 +2936,11 @@ pub fn emit(
|
||||
}
|
||||
}
|
||||
S::IndexWord(w) => access::index::emit_word(cx, fb, w)?,
|
||||
S::SinCos {
|
||||
shape,
|
||||
store,
|
||||
fast,
|
||||
nan,
|
||||
} => {
|
||||
S::SinCos { shape, store, fast } => {
|
||||
let p = nth(cx, &xs, 0)?;
|
||||
let test = nan::NanTest::for_modes(&cx.plan.families.arith.modes);
|
||||
let lib = lib(cx);
|
||||
let (sin, cos) = chunk::sin_cos(fb, *shape, p, *fast, *nan, test, &lib)?;
|
||||
let (sin, cos) = chunk::sin_cos(fb, *shape, p, *fast, test, &lib)?;
|
||||
// The access family's store reads the stored value as the call's result.
|
||||
cx.define(result, cos);
|
||||
access::emit(cx, fb, at, store)?;
|
||||
@@ -3026,7 +2956,6 @@ pub fn emit(
|
||||
pub(crate) fn lib(cx: &EmitCx<'_>) -> libm::Lib {
|
||||
let arith = &cx.plan.families.arith;
|
||||
libm::Lib::new(arith.metal_functions, cx.decl.families.arith.fmod)
|
||||
.with_min_max(arith.device_min_max || arith.native_min_max)
|
||||
}
|
||||
|
||||
/// The operands strategy `s` reads (a prefix of the instruction's; all when `None`).
|
||||
@@ -3062,7 +2991,6 @@ fn arity(s: &ArithStrategy) -> Option<usize> {
|
||||
| S::Member { .. } => Some(0),
|
||||
S::Chunked { parts, .. } => parts.first().and_then(|(_, p)| arity(p)),
|
||||
S::Wide(w) => w.arity(),
|
||||
S::Nan { of, .. } => arity(of),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -3093,11 +3021,6 @@ fn value(
|
||||
wide,
|
||||
result,
|
||||
} => chunk::emit_chunked(cx, fb, *lanes, parts, wide, result, xs)?,
|
||||
S::Nan { of, answer, form } => {
|
||||
let r = value(cx, fb, of, xs)?;
|
||||
let test = nan::NanTest::for_modes(&cx.plan.families.arith.modes);
|
||||
nan::select(fb, *form, *answer, test, r, xs.first().copied())?
|
||||
}
|
||||
S::ChunkedDot {
|
||||
lanes,
|
||||
elem,
|
||||
|
||||
@@ -12,51 +12,35 @@
|
||||
//! widened as `0x7FC00000`; its widening of a `half` NaN to `float`, and its `half` `fneg` and
|
||||
//! `fabs`, answer the canonical NaN too ([`NanAnswer::CanonicalExact`]). Its `float` `fneg` and
|
||||
//! `fabs` keep a NaN operand's payload, which the lowering moves on the bits
|
||||
//! (`math::sign_on_bits`), no select needed. Vulkan states no NaN encoding, and the devices
|
||||
//! (`math::sign_on_bits`). Vulkan states no NaN encoding, and the devices
|
||||
//! measured answer their own:
|
||||
//! an operand's bits, quieted or not, `0xFFC00000`, or `0x7FFFFFFF`, and for `half` `0xFE00`, the
|
||||
//! operand's payload, or `0x7FFF`. Each device answers a NaN on exactly the lanes Metal does for
|
||||
//! these classes, so selecting Metal's NaN where the result is a NaN ([`select`]) is exact on
|
||||
//! every device.
|
||||
//! these classes.
|
||||
//!
|
||||
//! The select is applied where the result's bits can be observed: a result whose every use
|
||||
//! drops its operands' NaN bits ([`drops_payload`]: a float comparison, or an operation that
|
||||
//! itself answers the canonical NaN) needs none, so a chain of arithmetic selects once, at its
|
||||
//! end, and the device may still contract an `fmul` into the `fadd` that uses it
|
||||
//! ([`observed_payloads`]). Where the profile states that the device's arithmetic answers Metal's
|
||||
//! canonical NaN ([`NanEncoding::MetalCanonical`], a measured device fact), the canonical class
|
||||
//! of its arithmetic is left to the device; the other classes, and the canonical NaN of an
|
||||
//! operation the device computes exactly, are selected on every profile.
|
||||
//! The module leaves every NaN's bits to the device, and records
|
||||
//! `PrecisionNote::NativeNanEncoding` where Metal answers a NaN the device is not measured to
|
||||
//! answer: every answer these tables give, but the canonical class of the arithmetic on a device
|
||||
//! measured to answer Metal's canonical NaN ([`NanEncoding::MetalCanonical`],
|
||||
//! [`NanAnswer::device_answers`]).
|
||||
//!
|
||||
//! The NaN test is `OpIsNan` where the entry declares `SignedZeroInfNanPreserve` for 32-bit
|
||||
//! floats, without which a device may assume that no operand is a NaN and fold the test; the
|
||||
//! module then tests the bits instead (`(bits & 0x7FFFFFFF) > 0x7F800000`), which no float mode
|
||||
//! reaches. The translation decorates no value `FPFastMathMode`. The select itself is a `float`
|
||||
//! `OpSelect`, which such a device may still fold to its operand, since the condition holds
|
||||
//! exactly where the operand is a NaN; where the answer is read bit for bit the module answers on
|
||||
//! the bits alone instead ([`canonical_on_bits`]).
|
||||
//! [`is_nan`] tests a value for a NaN, by `OpIsNan` where the entry declares
|
||||
//! `SignedZeroInfNanPreserve` for the width, without which a device may assume that no operand is a
|
||||
//! NaN and fold the test, and on the bits elsewhere (`(bits & 0x7FFFFFFF) > 0x7F800000`), which no
|
||||
//! float mode reaches: the conversions and functions whose answer at a NaN is a number test so.
|
||||
|
||||
use crate::air::intrinsics::{AirIntrinsic, NumKind, Precision};
|
||||
use crate::air::ir::{
|
||||
BinOp as AirBin, Body, Callee, CastOp, FastMath, FuncId, Inst, InstKind, Type, TypeId, Value,
|
||||
};
|
||||
use crate::air::Entry;
|
||||
use crate::budget::Meter;
|
||||
use crate::air::ir::{BinOp as AirBin, CastOp, FastMath};
|
||||
use crate::device::profile::NanEncoding;
|
||||
use crate::device::DeviceProfile;
|
||||
use crate::error::Error;
|
||||
use crate::lower::arith::legal::{FloatFmt, Form, Held};
|
||||
use crate::lower::arith::math::FloatFn;
|
||||
use crate::lower::arith::narrow::u32_form;
|
||||
use crate::lower::arith::ops::{splat, ty};
|
||||
use crate::spirv::builder::FunctionBuilder;
|
||||
use crate::spirv::error::{BResult, BuildError, TypeRule};
|
||||
use crate::spirv::error::BResult;
|
||||
use crate::spirv::ids::Value as SValue;
|
||||
use crate::spirv::ir::{BinOp, ConvOp, UnOp};
|
||||
|
||||
/// Metal's canonical `float` NaN.
|
||||
pub const CANONICAL: u64 = 0x7FC0_0000;
|
||||
|
||||
/// Which NaN Metal answers where an operation's result is a NaN.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub enum NanAnswer {
|
||||
@@ -80,38 +64,20 @@ pub enum NanAnswer {
|
||||
}
|
||||
|
||||
impl NanAnswer {
|
||||
/// Whether the answer is left to the device under `encoding`: on a device whose arithmetic
|
||||
/// answers Metal's canonical NaN ([`NanEncoding::MetalCanonical`]) the canonical class of the
|
||||
/// arithmetic, which the device fact covers, and not [`NanAnswer::CanonicalExact`]; under
|
||||
/// native device maths ([`NanEncoding::Native`]) every answer, the device's NaN noted
|
||||
/// `PrecisionNote::NativeNanEncoding`.
|
||||
pub fn left_to(self, encoding: NanEncoding) -> bool {
|
||||
/// Whether the device is measured to answer this NaN under `encoding`: on a device whose
|
||||
/// arithmetic answers Metal's canonical NaN ([`NanEncoding::MetalCanonical`]) the canonical
|
||||
/// class of the arithmetic, which the device fact covers, and not
|
||||
/// [`NanAnswer::CanonicalExact`]; nothing on another ([`NanEncoding::Native`]). The device's
|
||||
/// NaN of an answer it is not measured to give is noted `PrecisionNote::NativeNanEncoding`.
|
||||
pub fn device_answers(self, encoding: NanEncoding) -> bool {
|
||||
match encoding {
|
||||
NanEncoding::MetalCanonical => self == NanAnswer::Canonical,
|
||||
NanEncoding::Native => true,
|
||||
_ => false,
|
||||
NanEncoding::Native => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the answer reads the first operand.
|
||||
pub fn reads_operand(self) -> bool {
|
||||
!matches!(self, NanAnswer::Canonical | NanAnswer::CanonicalExact)
|
||||
}
|
||||
|
||||
/// An upper estimate of the SPIR-V words of [`select`] on a result of form `f`: the bits tests,
|
||||
/// the selects, and the constants' share.
|
||||
pub fn words(self, f: Form) -> u32 {
|
||||
let lanes = u32::from(f.lanes);
|
||||
let base = match self {
|
||||
NanAnswer::Canonical | NanAnswer::CanonicalExact => 32,
|
||||
NanAnswer::Operand => 56,
|
||||
NanAnswer::OperandSign | NanAnswer::DomainSign => 80,
|
||||
};
|
||||
base + 4 * lanes
|
||||
}
|
||||
}
|
||||
|
||||
/// How [`select`] tests a value for a NaN.
|
||||
/// How [`is_nan`] tests a value for a NaN.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum NanTest {
|
||||
/// `OpIsNan`: the entry declares `SignedZeroInfNanPreserve` for the width.
|
||||
@@ -216,8 +182,7 @@ fn precise_of(op: FloatFn) -> FloatFn {
|
||||
/// The answer Metal gives for a NaN result of `float` function `op` (refined as in
|
||||
/// [`function_answer`]) in the state measured: a precise symbol without fast-math flags
|
||||
/// (`nan_functions`), a `fast_` one (`fast`) with every flag (`nan_functions_fast`). Functions
|
||||
/// whose lowering answers it itself ([`FloatFn::metal_nans`]) are listed too: their result drops
|
||||
/// its operands' NaN bits ([`drops_payload`]). `None` where Metal answers a number for a NaN
|
||||
/// whose lowering answers it itself ([`FloatFn::metal_nans`]) are listed too. `None` where Metal answers a number for a NaN
|
||||
/// operand (`sign`, `saturate`, `fast::sin`, `fast::cos`), where the result is an operand
|
||||
/// (`fmin`, `fmax`, `median3`, `copysign`, `fabs`, and precise `pow`, whose `pow(x, 1)` is `x`).
|
||||
/// `sinpi`, `cospi`, and `tanpi` answer the canonical NaN in both modes for an infinity or a NaN.
|
||||
@@ -408,76 +373,6 @@ pub fn convert_answer(from: FloatFmt, to: FloatFmt) -> Option<NanAnswer> {
|
||||
}
|
||||
}
|
||||
|
||||
/// `r` (a result of form `f`, `float` lanes) with Metal's NaN `answer` where it is a NaN; `a`
|
||||
/// is the operation's first operand, which every answer but the canonical ones reads.
|
||||
pub fn select(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
f: Form,
|
||||
answer: NanAnswer,
|
||||
test: NanTest,
|
||||
r: SValue,
|
||||
a: Option<SValue>,
|
||||
) -> BResult<SValue> {
|
||||
let r_nan = is_nan(fb, f, test, r)?;
|
||||
let canonical = splat(fb, f, CANONICAL)?;
|
||||
let a = match (answer.reads_operand(), a) {
|
||||
(false, _) => return fb.select(r_nan, canonical, r),
|
||||
(true, Some(a)) => a,
|
||||
(true, None) => return Err(BuildError::Type(TypeRule::FunctionSignature)),
|
||||
};
|
||||
let a_nan = is_nan(fb, f, test, a)?;
|
||||
match answer {
|
||||
NanAnswer::Canonical | NanAnswer::CanonicalExact => fb.select(r_nan, canonical, r),
|
||||
NanAnswer::Operand => {
|
||||
let r = fb.select(r_nan, canonical, r)?;
|
||||
fb.select(a_nan, a, r)
|
||||
}
|
||||
NanAnswer::OperandSign | NanAnswer::DomainSign => {
|
||||
let u = u32_form(f);
|
||||
let (ut, ft) = (ty(fb, u)?, ty(fb, f)?);
|
||||
let bits = fb.convert(ConvOp::Bitcast, a, ut)?;
|
||||
let sign_bit = splat(fb, u, 0x8000_0000)?;
|
||||
let sign = fb.binary(BinOp::BitwiseAnd, bits, sign_bit)?;
|
||||
let zero = splat(fb, u, 0)?;
|
||||
let sign = if answer == NanAnswer::OperandSign {
|
||||
fb.select(a_nan, sign, zero)?
|
||||
} else {
|
||||
fb.select(a_nan, zero, sign)?
|
||||
};
|
||||
let quiet = splat(fb, u, CANONICAL)?;
|
||||
let nan = fb.binary(BinOp::BitwiseOr, sign, quiet)?;
|
||||
let nan = fb.convert(ConvOp::Bitcast, nan, ft)?;
|
||||
fb.select(r_nan, nan, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `x`, 32-bit `float` lanes of form `f`, with Metal's canonical NaN `0x7FC00000` where a lane is
|
||||
/// a NaN, on the bits alone: the test, the select and the answer are integer operations, and the
|
||||
/// one float value is the result of an `OpBitcast`, which carries no float mode.
|
||||
///
|
||||
/// [`select`] with [`NanAnswer::CanonicalExact`] answers the same value through a `float`
|
||||
/// `OpSelect` whose condition holds exactly where its operand is a NaN: a compiler that assumes no
|
||||
/// operand is a NaN may fold that select to its operand, and the module declares no
|
||||
/// `SignedZeroInfNanPreserve` for it to rely on. This form leaves it nothing to fold, so a
|
||||
/// widening whose answer is read bit for bit (the vertex and stage-in fetches,
|
||||
/// `lower::stage_io::fetch`) uses it.
|
||||
pub fn canonical_on_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: SValue) -> BResult<SValue> {
|
||||
if f.float_fmt() != Some(FloatFmt::F32) {
|
||||
return Err(BuildError::Type(TypeRule::FunctionSignature));
|
||||
}
|
||||
let u = u32_form(f);
|
||||
let (ut, ft) = (ty(fb, u)?, ty(fb, f)?);
|
||||
let bits = fb.convert(ConvOp::Bitcast, x, ut)?;
|
||||
let magnitude = splat(fb, u, 0x7FFF_FFFF)?;
|
||||
let infinity = splat(fb, u, 0x7F80_0000)?;
|
||||
let m = fb.binary(BinOp::BitwiseAnd, bits, magnitude)?;
|
||||
let is_nan = fb.binary(BinOp::UGreaterThan, m, infinity)?;
|
||||
let canonical = splat(fb, u, CANONICAL)?;
|
||||
let answered = fb.select(is_nan, canonical, bits)?;
|
||||
fb.convert(ConvOp::Bitcast, answered, ft)
|
||||
}
|
||||
|
||||
/// Whether lanes of `x` (form `f`) are NaNs, by `test`. The bits of a 64-bit container are read
|
||||
/// as two words per lane ([`is_nan_wide`]), so the test needs no 64-bit integers.
|
||||
pub fn is_nan(fb: &mut FunctionBuilder<'_>, f: Form, test: NanTest, x: SValue) -> BResult<SValue> {
|
||||
@@ -541,77 +436,6 @@ fn is_nan_wide(fb: &mut FunctionBuilder<'_>, f: Form, x: SValue) -> BResult<SVal
|
||||
fb.binary(BinOp::LogicalOr, above, at)
|
||||
}
|
||||
|
||||
/// Whether instruction `inst` reads its float operands' NaN bits nowhere into its result: a
|
||||
/// float comparison, or an operation whose every NaN result Metal answers as the canonical NaN
|
||||
/// whatever its operands' NaNs, which the lowering selects (or the device answers). Its operands
|
||||
/// then need no select of their own.
|
||||
pub fn drops_payload(e: &Entry, func: FuncId, inst: &Inst) -> bool {
|
||||
match &inst.kind {
|
||||
InstKind::FCmp { .. } => true,
|
||||
InstKind::FNeg { v, .. } => float_fmt_of(e, func, *v).and_then(fneg_answer).is_some(),
|
||||
InstKind::BinOp { op, a, .. } => float_fmt_of(e, func, *a)
|
||||
.and_then(|fmt| binary_answer(*op, fmt))
|
||||
.is_some(),
|
||||
InstKind::Cast { op, v } => {
|
||||
match (float_fmt_of(e, func, *v), float_fmt_of_ty(e, inst.ty)) {
|
||||
(Some(from), Some(to)) => cast_answer(*op, from, to).is_some(),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
InstKind::Call(call) => {
|
||||
if let Callee::Air {
|
||||
op: AirIntrinsic::Convert(c),
|
||||
..
|
||||
} = &call.callee
|
||||
{
|
||||
let float = c.src_kind == NumKind::Float && c.dst_kind == NumKind::Float;
|
||||
let from = call.args.first().and_then(|x| float_fmt_of(e, func, *x));
|
||||
return match (
|
||||
float && c.src_fp8.is_none(),
|
||||
from,
|
||||
float_fmt_of_ty(e, inst.ty),
|
||||
) {
|
||||
(true, Some(from), Some(to)) => convert_answer(from, to).is_some(),
|
||||
_ => false,
|
||||
};
|
||||
}
|
||||
let (op, fast) = match &call.callee {
|
||||
Callee::Air {
|
||||
op: AirIntrinsic::Math(m),
|
||||
..
|
||||
} => (super::air_math(m.f).ok(), m.precision == Precision::Fast),
|
||||
Callee::Llvm { op, .. } => (super::llvm_math(op).ok(), false),
|
||||
_ => (None, false),
|
||||
};
|
||||
let Some(super::Fun::Float(op)) = op else {
|
||||
return false;
|
||||
};
|
||||
let Some(first) = call.args.first() else {
|
||||
return false;
|
||||
};
|
||||
let Some(fmt) = float_fmt_of(e, func, *first) else {
|
||||
return false;
|
||||
};
|
||||
let f = Form {
|
||||
held: Held::Float(fmt),
|
||||
lanes: 1,
|
||||
};
|
||||
// `air.fast_fmod` on `float` is Metal's fused multiply-add composition, whose NaN is
|
||||
// the fused multiply-add's: canonical.
|
||||
if fast && op == FloatFn::Fmod && fmt == FloatFmt::F32 {
|
||||
return true;
|
||||
}
|
||||
// The reciprocal a refinement divides by does not decide its NaN.
|
||||
let op = super::refine_float(op, fast, call.fmf, f);
|
||||
matches!(
|
||||
function_answer(op, fast, super::every_flag(call.fmf), fmt),
|
||||
Some(NanAnswer::Canonical | NanAnswer::CanonicalExact)
|
||||
)
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether precise `float` function `op` called with every fast-math flag is measured to answer
|
||||
/// the NaN it answers without them ([`measured`]'s precise state): `sin`, `cos` (and `sincos`'s
|
||||
/// two results), `tan`, `asin`, `acos`, `atan`, `asinh`, `atanh` and `atan2` at NaN operands of
|
||||
@@ -628,60 +452,6 @@ fn flagged_precise(op: FloatFn) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
/// The float format of `v`'s scalar or vector type, if it is one.
|
||||
fn float_fmt_of(e: &Entry, func: FuncId, v: Value) -> Option<FloatFmt> {
|
||||
float_fmt_of_ty(e, e.module.value_ty(func, v)?)
|
||||
}
|
||||
|
||||
/// The float format of scalar or vector type `t`, if it is one.
|
||||
fn float_fmt_of_ty(e: &Entry, mut t: TypeId) -> Option<FloatFmt> {
|
||||
let types = e.module.types();
|
||||
if let Some(Type::Vector { elem, .. }) = types.get(t) {
|
||||
t = *elem;
|
||||
}
|
||||
match types.get(t)? {
|
||||
Type::Float => Some(FloatFmt::F32),
|
||||
Type::Half => Some(FloatFmt::Half),
|
||||
Type::BFloat => Some(FloatFmt::BFloat),
|
||||
Type::Double => Some(FloatFmt::F64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether each instruction's result may carry its NaN's bits to an observation, by `InstId`:
|
||||
/// read by an instruction or terminator that does not [`drops_payload`] (a phi, which moves the
|
||||
/// value on, included). One pass over the body's instructions; the bitmap is charged to `m` and
|
||||
/// released by the caller (`insts.len()` bytes).
|
||||
pub fn observed_payloads(
|
||||
e: &Entry,
|
||||
func: FuncId,
|
||||
body: &Body,
|
||||
m: &mut Meter,
|
||||
) -> Result<Vec<bool>, Error> {
|
||||
let n = body.insts.len();
|
||||
m.charge(n)?;
|
||||
let mut observed = vec![false; n];
|
||||
for (_, block) in body.blocks.iter() {
|
||||
for id in block.inst_ids() {
|
||||
m.tick(1)?;
|
||||
let Some(inst) = body.insts.get(id) else {
|
||||
continue;
|
||||
};
|
||||
if drops_payload(e, func, inst) {
|
||||
continue;
|
||||
}
|
||||
inst.kind.for_each_value(|v| {
|
||||
if let Value::Inst(i) = v {
|
||||
if let Some(o) = observed.get_mut(i.raw() as usize) {
|
||||
*o = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(observed)
|
||||
}
|
||||
|
||||
/// The profile's NaN encoding.
|
||||
pub fn encoding(p: &DeviceProfile) -> NanEncoding {
|
||||
p.fields().nan_encoding
|
||||
|
||||
@@ -342,15 +342,12 @@ pub fn round_texel_words(f: Form) -> u32 {
|
||||
/// `OpQuantizeToF16` may return another NaN; it is told by its bits, so the test holds whatever
|
||||
/// float modes the device compiles the module under. Under native half rounding
|
||||
/// ([`native_rounding`]) the rounding's own NaN stands instead: the note the module records bounds
|
||||
/// a NaN's encoding to the device's, so the keep's four instructions a texel are left out, but
|
||||
/// where the NaN switch asks for Metal's NaN (`NanMinMaxPolicy::Exact`;
|
||||
/// `ModuleBuilder::texel_nans`), which keeps them. So too under the float controls
|
||||
/// ([`QuantizeForm::Controlled`]) where the profile leaves a NaN's bits to the device
|
||||
/// (`ModuleBuilder::native_half_nans`, `NanMinMaxPolicy::Native`): the conversion keeps a NaN a
|
||||
/// NaN, its bits the device's, as the texel's decode is (`PrecisionNote::DeviceNanEncoding`, which
|
||||
/// the access records). Another form is [`round`]ed.
|
||||
/// a NaN's encoding to the device's, so the keep's four instructions a texel are left out. So too
|
||||
/// under the float controls ([`QuantizeForm::Controlled`], `ModuleBuilder::native_half_nans`): the
|
||||
/// conversion keeps a NaN a NaN, its bits the device's, as the texel's decode is
|
||||
/// (`PrecisionNote::DeviceNanEncoding`, which the access records). Another form is [`round`]ed.
|
||||
pub fn round_texel(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult<Value> {
|
||||
let native = fb.module().native_half() && !fb.module().texel_nans();
|
||||
let native = fb.module().native_half();
|
||||
match f.held {
|
||||
Held::Float(FloatFmt::Half) if native || fb.module().native_half_nans() => round(fb, f, x),
|
||||
Held::Float(FloatFmt::Half) => {
|
||||
@@ -983,9 +980,9 @@ fn f32_bits_to_half_bits(fb: &mut FunctionBuilder<'_>, u: Form, b: Value) -> BRe
|
||||
/// Under native half rounding through the device's conversion ([`native_decode`]) a `half`'s exact
|
||||
/// decode is offered the device's ([`native_from_bits`]) where no loop holds it
|
||||
/// (`FunctionBuilder::offer_outside_loops`): NVIDIA's compiler makes a module faster with the
|
||||
/// device's widening outside loops and slower with it inside one. Under the float controls, where
|
||||
/// the profile leaves a NaN's bits to the device (`ModuleBuilder::native_half_nans`), a `half` is
|
||||
/// the device's widening of its bits wherever it is ([`device_from_bits`]); so is the `half` of a
|
||||
/// device's widening outside loops and slower with it inside one. Under the float controls
|
||||
/// (`ModuleBuilder::native_half_nans`), a `half` is the device's widening of its bits wherever it
|
||||
/// is ([`device_from_bits`]); so is the `half` of a
|
||||
/// load whose uses read no NaN's bits, where the device's widening is Metal's
|
||||
/// (`ModuleBuilder::widens_halves`, [`widening`](super::widening)): exact, a NaN `0x7FC00000` as
|
||||
/// Metal widens it, the bits noted as for the integer decode.
|
||||
@@ -1063,8 +1060,8 @@ fn native_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult<
|
||||
/// `SignedZeroInfNanPreserve`. A NaN widens to a NaN whose bits are the device's (the SPIR-V
|
||||
/// spec's `SignedZeroInfNanPreserve`: "Bit patterns for NaNs might not be preserved"). Metal widens
|
||||
/// every `half` NaN to `0x7FC00000` and every other `half` to its value (the M3 Max, every bit
|
||||
/// pattern, loaded from device and constant memory, safe and fast math), which the NaN switch
|
||||
/// answers at the widening to `float` (`nan::cast_answer`) on [`half_bits_to_f32_bits`]'s decode.
|
||||
/// pattern, loaded from device and constant memory, safe and fast math), which no form answers: the
|
||||
/// device's NaN is noted (`PrecisionNote::NativeNanEncoding`).
|
||||
fn device_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult<Value> {
|
||||
let e = fb.module().ty(Type::Float { width: 16 })?;
|
||||
let pair = fb.module().ty(Type::Vector { elem: e, len: 2 })?;
|
||||
|
||||
@@ -287,8 +287,7 @@ pub fn f16_binary_words(f: Form) -> u32 {
|
||||
/// alternative, [`float_binary`]): `float`'s 24-bit significand is at least `2 · 11 + 2` bits, so
|
||||
/// rounding its correctly rounded sum, difference or product to `half` rounds the exact result once
|
||||
/// (the double rounding is innocuous). A NaN's bits are the device's, as the controlled rounding's
|
||||
/// are; Metal's NaN, where the profile asks for it, is selected around the instruction
|
||||
/// (`ArithStrategy::Nan`).
|
||||
/// are.
|
||||
///
|
||||
/// The instruction is always kept apart, whatever the AIR's flags allow: a sum or difference
|
||||
/// decorated `NoContraction` (SPIRV-Cross writes its `[[clang::optnone]]` `spvFAdd` or `spvFSub`),
|
||||
|
||||
@@ -1796,40 +1796,6 @@ fn median3_ref(b: [u64; 3], val: &dyn Fn(u64) -> f64, fast: bool) -> u64 {
|
||||
pick(pick(c, lo, false), hi, true)
|
||||
}
|
||||
|
||||
/// Metal's `fmin`, `fmax`, `min3`, `max3`, or `clamp` (`op`) of operand bits `b`: `fmin(p, q)` is
|
||||
/// `q` for a NaN `p`, else `p` for a NaN `q` or `p < q`, else `q` (and `fmax` with `>`), comparing
|
||||
/// the operands' values `val` (an `f32` denormal as zero) but returning their bits; `min3` and
|
||||
/// `max3` nest it, and `clamp(x, lo, hi)` is `fmin(fmax(x, lo), hi)`.
|
||||
fn metal_min_max_ref(op: FloatFn, b: &[u64], val: &dyn Fn(u64) -> f64) -> u64 {
|
||||
let pick = |p: u64, q: u64, less: bool| {
|
||||
let (vp, vq) = (val(p), val(q));
|
||||
if vp.is_nan() {
|
||||
q
|
||||
} else if vq.is_nan() || (less && vp < vq) || (!less && vp > vq) {
|
||||
p
|
||||
} else {
|
||||
q
|
||||
}
|
||||
};
|
||||
match op {
|
||||
FloatFn::Min => pick(b[0], b[1], true),
|
||||
FloatFn::Max => pick(b[0], b[1], false),
|
||||
FloatFn::Min3 => pick(pick(b[0], b[1], true), b[2], true),
|
||||
FloatFn::Max3 => pick(pick(b[0], b[1], false), b[2], false),
|
||||
FloatFn::Clamp => pick(pick(b[0], b[1], false), b[2], true),
|
||||
_ => panic!("{op:?} is not a minimum or maximum"),
|
||||
}
|
||||
}
|
||||
|
||||
/// An `f32` operand's value as Metal's `float` comparisons read it: a denormal as zero.
|
||||
fn f32_compared(b: u64) -> f64 {
|
||||
if b & 0x7F80_0000 == 0 {
|
||||
0.0
|
||||
} else {
|
||||
f64::from(f32::from_bits(b as u32))
|
||||
}
|
||||
}
|
||||
|
||||
fn float_ref(op: FloatFn, bits: u8, a: &[u64]) -> Option<u64> {
|
||||
let x = |i: usize| fval(bits, a[i]);
|
||||
// An `f32` zero or denormal, which Metal's `float` functions read as zero.
|
||||
@@ -1882,19 +1848,8 @@ fn float_ref(op: FloatFn, bits: u8, a: &[u64]) -> Option<u64> {
|
||||
-1.0
|
||||
})
|
||||
}
|
||||
FloatFn::Saturate => {
|
||||
let v = x(0);
|
||||
r(if flushed(0) || v.is_nan() || v <= 0.0 {
|
||||
0.0
|
||||
} else {
|
||||
v.min(1.0)
|
||||
})
|
||||
}
|
||||
FloatFn::Min | FloatFn::Max | FloatFn::Clamp | FloatFn::Min3 | FloatFn::Max3
|
||||
if bits == 32 =>
|
||||
{
|
||||
Some(metal_min_max_ref(op, a, &f32_compared))
|
||||
}
|
||||
// The device's `NClamp(x, 0, 1)`: a NaN answers 0, a denormal is the device's.
|
||||
FloatFn::Saturate => r(min(max(x(0), 0.0), 1.0)),
|
||||
FloatFn::Min | FloatFn::MinNum => r(min(x(0), x(1))),
|
||||
FloatFn::Max | FloatFn::MaxNum => r(max(x(0), x(1))),
|
||||
FloatFn::Clamp => r(min(max(x(0), x(1)), x(2))),
|
||||
@@ -2049,15 +2004,18 @@ fn exact_float_functions_match_metal() {
|
||||
}
|
||||
c
|
||||
};
|
||||
// The device's `NMin` and `NMax` may give either zero; Metal's (`float`) gives the
|
||||
// second operand.
|
||||
let loose = match op {
|
||||
FloatFn::MinNum | FloatFn::MaxNum => true,
|
||||
FloatFn::Min | FloatFn::Max | FloatFn::Clamp | FloatFn::Min3 | FloatFn::Max3 => {
|
||||
bits == 64
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
// The device's `NMin`, `NMax` and `NClamp` may give either zero.
|
||||
let loose = matches!(
|
||||
op,
|
||||
FloatFn::MinNum
|
||||
| FloatFn::MaxNum
|
||||
| FloatFn::Min
|
||||
| FloatFn::Max
|
||||
| FloatFn::Clamp
|
||||
| FloatFn::Min3
|
||||
| FloatFn::Max3
|
||||
| FloatFn::Saturate
|
||||
);
|
||||
check(
|
||||
&format!("{op:?} f{bits}"),
|
||||
&vec![f; arity],
|
||||
@@ -2109,176 +2067,6 @@ fn nan_operands() -> Vec<u64> {
|
||||
]
|
||||
}
|
||||
|
||||
/// [`nan::select`] answers Metal's NaN bit for bit, by either test, on scalars and vectors: the
|
||||
/// canonical NaN for every NaN result (`Canonical`, `CanonicalExact`); with a NaN operand's sign or `+` for a domain error
|
||||
/// (`OperandSign`); `+` for a NaN operand and the operand's sign for a domain error
|
||||
/// (`DomainSign`); the NaN operand itself, else the canonical NaN (`Operand`); and every other
|
||||
/// result untouched. The kernel's first input is the operand, its second the result.
|
||||
#[test]
|
||||
fn nan_select_answers_metals_nan_exactly() {
|
||||
use super::nan::{self, NanAnswer};
|
||||
let f32_nan = |b: u64| f32::from_bits(b as u32).is_nan();
|
||||
let vals = nan_operands();
|
||||
let cases = pairs(&vals, &vals);
|
||||
for answer in [
|
||||
NanAnswer::Canonical,
|
||||
NanAnswer::CanonicalExact,
|
||||
NanAnswer::OperandSign,
|
||||
NanAnswer::DomainSign,
|
||||
NanAnswer::Operand,
|
||||
] {
|
||||
for test in [NanTest::IsNan, NanTest::Bits] {
|
||||
for lanes in [1, 3] {
|
||||
let f = vec(float(32), lanes);
|
||||
let lane_cases: Vec<Case> = cases
|
||||
.iter()
|
||||
.map(|c| c.iter().map(|o| vec![o[0]; usize::from(lanes)]).collect())
|
||||
.collect();
|
||||
check_accept(
|
||||
&format!("{answer:?} {test:?} x{lanes}"),
|
||||
&[f, f],
|
||||
f,
|
||||
&|fb, x| nan::select(fb, f, answer, test, x[1], Some(x[0])),
|
||||
&lane_cases,
|
||||
&|c| {
|
||||
let (a, r) = (arg(c, 0), arg(c, 1));
|
||||
let sign = a & 0x8000_0000;
|
||||
let want = match answer {
|
||||
NanAnswer::Operand if f32_nan(a) => a,
|
||||
_ if !f32_nan(r) => r,
|
||||
NanAnswer::Canonical
|
||||
| NanAnswer::CanonicalExact
|
||||
| NanAnswer::Operand => nan::CANONICAL,
|
||||
NanAnswer::OperandSign if f32_nan(a) => sign | nan::CANONICAL,
|
||||
NanAnswer::OperandSign => nan::CANONICAL,
|
||||
NanAnswer::DomainSign if f32_nan(a) => nan::CANONICAL,
|
||||
NanAnswer::DomainSign => sign | nan::CANONICAL,
|
||||
};
|
||||
Some(vec![want; usize::from(lanes)])
|
||||
},
|
||||
&|g, w| g == w,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Class B: on a `half` result, held widened, [`nan::select`] of the canonical answer gives Metal's
|
||||
/// `half` NaN `0x7E00` for every NaN lane, quiet or signaling, of either sign and any payload, by
|
||||
/// either test, and keeps every other lane, infinities and zeros included.
|
||||
#[test]
|
||||
fn nan_select_answers_metals_half_nan() {
|
||||
use super::nan::{self, NanAnswer};
|
||||
let halves: [u64; 16] = [
|
||||
0x7E00, 0xFE00, 0x7C01, 0xFC01, 0x7DFF, 0xFFFF, 0x7FFF, 0x7E55, 0x7C00, 0xFC00, 0, 0x8000,
|
||||
0x3C00, 0xBC00, 0x0001, 0x7BFF,
|
||||
];
|
||||
for test in [NanTest::IsNan, NanTest::Bits] {
|
||||
for lanes in [1u8, 3] {
|
||||
let f = vec(float(16), lanes);
|
||||
let cases: Vec<Case> = halves
|
||||
.iter()
|
||||
.map(|&h| vec![vec![h; usize::from(lanes)]])
|
||||
.collect();
|
||||
check_accept(
|
||||
&format!("half {test:?} x{lanes}"),
|
||||
&[f],
|
||||
f,
|
||||
&|fb, x| nan::select(fb, f, NanAnswer::Canonical, test, x[0], None),
|
||||
&cases,
|
||||
&|c| {
|
||||
let h = arg(c, 0);
|
||||
let want = if is_nan(float(16), h) { 0x7E00 } else { h };
|
||||
Some(vec![want; usize::from(lanes)])
|
||||
},
|
||||
&|g, w| g == w,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Class F: Metal's `fmin`, `fmax`, `min3`, `max3`, and `clamp` on `float` and `half`
|
||||
/// ([`math::metal_min_max`]) answer an operand bit for bit, by either NaN test, on scalars and
|
||||
/// vectors: a NaN loses, two NaNs and a tie of zeros answer the second operand, and a `float`
|
||||
/// denormal compares as zero but is returned itself (`fmin(2^-149, +0)` is `+0`, `fmin(+0,
|
||||
/// 2^-149)` is `2^-149`), as `nan_minmax`, `nan_minmax_fast`, their zeros-and-denormals cases,
|
||||
/// `nan_half`, and `nan_half_fast` read on every lane.
|
||||
#[test]
|
||||
fn min_max_answer_metals_operand_bit_for_bit() {
|
||||
let mut floats = nan_operands();
|
||||
floats.extend([
|
||||
0x8000_0001,
|
||||
0x007F_FFFF,
|
||||
0x0080_0000,
|
||||
0x8080_0000,
|
||||
0x4000_0000,
|
||||
]);
|
||||
let halves: Vec<u64> = vec![
|
||||
0x7E00, 0xFE00, 0x7C01, 0xFC01, 0x7E55, 0x7C00, 0xFC00, 0, 0x8000, 0x3C00, 0xBC00, 0x0001,
|
||||
0x8001, 0x03FF, 0x0400,
|
||||
];
|
||||
let half_compared = |b: u64| f16_to_f64(b as u16);
|
||||
let formats: [(u8, Vec<u64>, &dyn Fn(u64) -> f64); 2] =
|
||||
[(32, floats, &f32_compared), (16, halves, &half_compared)];
|
||||
for (bits, vals, val) in formats {
|
||||
let few: Vec<u64> = vals.iter().copied().step_by(2).collect();
|
||||
let triples: Vec<Case> = few
|
||||
.iter()
|
||||
.flat_map(|&a| {
|
||||
let few = &few;
|
||||
few.iter()
|
||||
.flat_map(move |&b| few.iter().map(move |&c| vec![vec![a], vec![b], vec![c]]))
|
||||
})
|
||||
.collect();
|
||||
for op in [
|
||||
FloatFn::Min,
|
||||
FloatFn::Max,
|
||||
FloatFn::Min3,
|
||||
FloatFn::Max3,
|
||||
FloatFn::Clamp,
|
||||
] {
|
||||
let arity = op.arity();
|
||||
let cases = if arity == 2 {
|
||||
pairs(&vals, &vals)
|
||||
} else {
|
||||
triples.clone()
|
||||
};
|
||||
for test in [NanTest::IsNan, NanTest::Bits] {
|
||||
for lanes in [1u8, 3] {
|
||||
let f = vec(float(bits), lanes);
|
||||
let n = usize::from(lanes);
|
||||
let lane_cases: Vec<Case> = cases
|
||||
.iter()
|
||||
.map(|c| c.iter().map(|o| vec![o[0]; n]).collect())
|
||||
.collect();
|
||||
check_accept(
|
||||
&format!("{op:?} f{bits} {test:?} x{lanes}"),
|
||||
&vec![f; arity],
|
||||
f,
|
||||
&|fb, x| {
|
||||
math::float_fn(
|
||||
fb,
|
||||
op,
|
||||
f,
|
||||
Contraction::Forbidden,
|
||||
test,
|
||||
x,
|
||||
&Lib::instructions(),
|
||||
)
|
||||
},
|
||||
&lane_cases,
|
||||
&|c| {
|
||||
let b: Vec<u64> = c.iter().map(|l| l[0]).collect();
|
||||
Some(vec![metal_min_max_ref(op, &b, val); n])
|
||||
},
|
||||
&|g, w| g == w,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Class H: Metal's `half` `fmod` answers `+0` for a zero remainder of a nonzero dividend and the
|
||||
/// dividend itself for a zero one (`fmod(-2, 0.5)` and `fmod(-65504, 65504)` are `+0`, `fmod(-0,
|
||||
/// 1)` and `fmod(-0, inf)` are `-0`), as `nan_fmod_zero` and `nan_fmod_zero_fast` read on every
|
||||
@@ -2494,14 +2282,11 @@ fn half_nan_answers_follow_the_measured_states() {
|
||||
assert_eq!(cast_answer(op, from, to), None, "{op:?} {from:?} {to:?}");
|
||||
}
|
||||
use crate::device::profile::NanEncoding;
|
||||
assert!(A::Canonical.left_to(NanEncoding::MetalCanonical));
|
||||
assert!(A::Canonical.device_answers(NanEncoding::MetalCanonical));
|
||||
for a in [A::CanonicalExact, A::Operand, A::OperandSign, A::DomainSign] {
|
||||
assert!(!a.left_to(NanEncoding::MetalCanonical), "{a:?}");
|
||||
assert!(!a.device_answers(NanEncoding::MetalCanonical), "{a:?}");
|
||||
}
|
||||
for a in [A::Canonical, A::CanonicalExact] {
|
||||
assert!(!a.left_to(NanEncoding::Device), "{a:?}");
|
||||
}
|
||||
// Native device maths leaves every answer to the device.
|
||||
// A device not measured to answer Metal's canonical NaN answers none of Metal's NaNs.
|
||||
for a in [
|
||||
A::Canonical,
|
||||
A::CanonicalExact,
|
||||
@@ -2509,7 +2294,7 @@ fn half_nan_answers_follow_the_measured_states() {
|
||||
A::OperandSign,
|
||||
A::DomainSign,
|
||||
] {
|
||||
assert!(a.left_to(NanEncoding::Native), "{a:?}");
|
||||
assert!(!a.device_answers(NanEncoding::Native), "{a:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2522,7 +2307,7 @@ const KHR_FACTS: super::FloatFacts = super::FloatFacts {
|
||||
},
|
||||
metal_functions: false,
|
||||
device_denormals: false,
|
||||
nan_native: false,
|
||||
nans: crate::device::profile::NanEncoding::Native,
|
||||
native_min_max: false,
|
||||
};
|
||||
|
||||
@@ -4140,16 +3925,15 @@ fn the_minimum_and_maximum_family_follows_the_profile() {
|
||||
assert!(taken >= 1, "the MoltenVK capture takes it");
|
||||
}
|
||||
|
||||
/// Where the library says the device's `NMin`, `NMax` and `NClamp` are Metal's
|
||||
/// (`Lib::with_min_max`), each of the family is those instructions alone, with no NaN test;
|
||||
/// elsewhere it is `math::metal_min_max`'s picks, with NaN tests and no such instruction.
|
||||
/// Each of the minimum and maximum family is the device's `NMin`, `NMax` and `NClamp` alone, with
|
||||
/// no NaN test.
|
||||
#[test]
|
||||
fn the_minimum_and_maximum_family_takes_the_device_instructions_where_measured() {
|
||||
fn the_minimum_and_maximum_family_takes_the_device_instructions() {
|
||||
// SPIR-V `OpExtInst`, `OpIsNan`; GLSL.std.450 `NMin`, `NMax`, `NClamp`.
|
||||
const OP_EXT_INST: u32 = 12;
|
||||
const OP_IS_NAN: u32 = 156;
|
||||
const DEVICE: [u32; 3] = [79, 80, 81];
|
||||
let counts = |op: FloatFn, f: Form, device: bool| -> (usize, usize) {
|
||||
let counts = |op: FloatFn, f: Form| -> (usize, usize) {
|
||||
let m = kernel(&vec![f; op.arity()], f, &|fb, a| {
|
||||
math::float_fn(
|
||||
fb,
|
||||
@@ -4158,7 +3942,7 @@ fn the_minimum_and_maximum_family_takes_the_device_instructions_where_measured()
|
||||
Contraction::Forbidden,
|
||||
NanTest::IsNan,
|
||||
a,
|
||||
&Lib::instructions().with_min_max(device),
|
||||
&Lib::instructions(),
|
||||
)
|
||||
})
|
||||
.expect("kernel");
|
||||
@@ -4185,16 +3969,12 @@ fn the_minimum_and_maximum_family_takes_the_device_instructions_where_measured()
|
||||
FloatFn::Max3,
|
||||
] {
|
||||
for f in [float(32), float(16), vec(float(32), 4)] {
|
||||
let (ext, nan) = counts(op, f, true);
|
||||
let want = if matches!(op, FloatFn::Min3 | FloatFn::Max3) {
|
||||
2
|
||||
} else {
|
||||
1
|
||||
};
|
||||
assert_eq!((ext, nan), (want, 0), "{op:?} on {f:?}, the device's");
|
||||
let (ext, nan) = counts(op, f, false);
|
||||
assert_eq!(ext, 0, "{op:?} on {f:?}, picked");
|
||||
assert!(nan > 0, "{op:?} on {f:?}, picked: no NaN test");
|
||||
assert_eq!(counts(op, f), (want, 0), "{op:?} on {f:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -434,76 +434,6 @@ fn scalar_and_half_outputs_round() {
|
||||
);
|
||||
}
|
||||
|
||||
/// `color_write::half_bits` writes each half's own bits: every `half` widened (every NaN payload of
|
||||
/// either sign, the denormals, both zeros and infinities), each value but a NaN through the
|
||||
/// conversion to 16 bits and each NaN as `nan_codes`' code; a NaN no half widens to (its top ten
|
||||
/// fraction bits zero) is the quiet NaN of its sign; and `HALF_BITS_WORDS` bounds the emission.
|
||||
#[test]
|
||||
fn half_bits_are_each_halfs_bits() {
|
||||
use crate::spirv::ir::{ConvOp, Type};
|
||||
use crate::spirv::serialize::serialize;
|
||||
// `half_bits`' lanes as their codes, widened to 32-bit integers.
|
||||
let codes = |fb: &mut FunctionBuilder<'_>, f: Form, x: Value| -> BResult<Value> {
|
||||
let h = color_write::half_bits(fb, f, x)?;
|
||||
let lanes = |fb: &mut FunctionBuilder<'_>, width: u8| -> BResult<_> {
|
||||
let elem = fb.module().ty(Type::Int {
|
||||
width,
|
||||
signed: false,
|
||||
})?;
|
||||
fb.module().ty(Type::Vector { elem, len: f.lanes })
|
||||
};
|
||||
let u16_ = lanes(fb, 16)?;
|
||||
let u32_ = lanes(fb, 32)?;
|
||||
let narrow = fb.convert(ConvOp::Bitcast, h, u16_)?;
|
||||
fb.convert(ConvOp::UConvert, narrow, u32_)
|
||||
};
|
||||
let h = vec(float(16), 4);
|
||||
let out = vec(int(32), 4);
|
||||
let cases: Vec<Case> = (0u64..0x10000)
|
||||
.step_by(4)
|
||||
.map(|b| vec![vec![b, b + 1, b + 2, b + 3]])
|
||||
.collect();
|
||||
check_accept(
|
||||
"every half",
|
||||
&[h],
|
||||
out,
|
||||
&|fb, x| codes(fb, h, x[0]),
|
||||
&cases,
|
||||
&|c| Some(c[0].clone()),
|
||||
&|g, w| g == w,
|
||||
);
|
||||
let f = vec(float(32), 4);
|
||||
let low_nans = [0x7f80_0001u32, 0xff80_0001, 0x7f80_1fff, 0xffc0_0000];
|
||||
let cases = vec![vec![low_nans.iter().map(|&b| u64::from(b)).collect()]];
|
||||
check_accept(
|
||||
"NaNs without a half's payload",
|
||||
&[f],
|
||||
out,
|
||||
&|fb, x| codes(fb, f, x[0]),
|
||||
&cases,
|
||||
&|_| Some(vec![0x7e00, 0xfe00, 0x7e00, 0xfe00]),
|
||||
&|g, w| g == w,
|
||||
);
|
||||
// The routine's words, with its codes' widening (two conversions) charged to it too.
|
||||
let size = |with: bool| -> usize {
|
||||
let m = kernel(&[f], out, &|fb, x| match with {
|
||||
true => codes(fb, f, x[0]),
|
||||
false => {
|
||||
let u = crate::lower::arith::ops::ty(fb, out)?;
|
||||
fb.convert(ConvOp::Bitcast, x[0], u)
|
||||
}
|
||||
})
|
||||
.expect("build");
|
||||
serialize(m).expect("serialize").words.len()
|
||||
};
|
||||
let words = size(true) - size(false);
|
||||
assert!(
|
||||
words as u64 <= color_write::HALF_BITS_WORDS,
|
||||
"half_bits is {words} words, bound {}",
|
||||
color_write::HALF_BITS_WORDS
|
||||
);
|
||||
}
|
||||
|
||||
/// A word attachment's encode (`stage_io::word_color::encode`) stores Metal's word for every
|
||||
/// packed 16-bit layout: each lane rounded to `half`, then its code rounded to even
|
||||
/// (`WordAttachment::output_word`, which the M3 Max's draws and clears matched on every texel),
|
||||
|
||||
@@ -750,13 +750,16 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) {
|
||||
}
|
||||
c
|
||||
};
|
||||
// `bfloat` keeps the device's `NMin` and `NMax`, which may give either zero; `half` is
|
||||
// Metal's, bit for bit.
|
||||
let picks = matches!(
|
||||
// The device's `NMin`, `NMax` and `NClamp`, which may give either zero.
|
||||
let loose = matches!(
|
||||
op,
|
||||
FloatFn::Min | FloatFn::Max | FloatFn::Clamp | FloatFn::Min3 | FloatFn::Max3
|
||||
FloatFn::Min
|
||||
| FloatFn::Max
|
||||
| FloatFn::Clamp
|
||||
| FloatFn::Min3
|
||||
| FloatFn::Max3
|
||||
| FloatFn::Saturate
|
||||
);
|
||||
let loose = picks && !is_half;
|
||||
let flush = exact_ok(f);
|
||||
let accept = |g: u64, w: u64| flush(g, w) || (loose && is_zero(f, g) && is_zero(f, w));
|
||||
check_accept(
|
||||
@@ -799,10 +802,6 @@ fn narrow_float_functions_on(f: Form, vals: &[u64]) {
|
||||
FloatFn::Sign => 0.0,
|
||||
FloatFn::Saturate if x(0) > 0.0 => x(0).min(1.0),
|
||||
FloatFn::Saturate => 0.0,
|
||||
_ if picks && is_half => {
|
||||
let b: Vec<u64> = c.iter().map(|l| l[0]).collect();
|
||||
return Some(vec![metal_min_max_ref(op, &b, &|v| nval(f, v))]);
|
||||
}
|
||||
FloatFn::Min => x(0).min(x(1)),
|
||||
FloatFn::Max => x(0).max(x(1)),
|
||||
FloatFn::Clamp => x(0).max(x(1)).min(x(2)),
|
||||
@@ -2887,13 +2886,13 @@ fn half_arithmetic_on_the_device_is_one_16_bit_instruction() {
|
||||
}
|
||||
}
|
||||
|
||||
/// Under the float controls (`QuantizeForm::Controlled`), where the profile leaves a NaN's bits to
|
||||
/// the device (`ModuleBuilder::native_half_nans`, `NanMinMaxPolicy::Native`), `from_bits` is the
|
||||
/// Under the float controls (`QuantizeForm::Controlled`), where the module leaves a NaN's bits to
|
||||
/// the device (`ModuleBuilder::native_half_nans`, every profile so rounding), `from_bits` is the
|
||||
/// device's widening of the bits as a 16-bit float, with no integer decode: every half bit
|
||||
/// pattern, with junk above its 16 bits, reads as its exact `f32` value but a NaN, which reads as
|
||||
/// a NaN, one lane at a time and four at once, and `narrow::widens_bits` finds the widening.
|
||||
/// Without the flag (the NaN switch's `NanMinMaxPolicy::Exact`) the integer decode stands: every
|
||||
/// pattern exact, NaN payloads included, and `widens_bits` finds none.
|
||||
/// Without the flag the integer decode stands: every pattern exact, NaN payloads included, and
|
||||
/// `widens_bits` finds none.
|
||||
#[test]
|
||||
fn a_half_decode_under_the_float_controls_is_the_devices_widening() {
|
||||
use super::super::narrow::{f32_of_half_bits, from_bits, widens_bits};
|
||||
|
||||
@@ -179,85 +179,12 @@ fn unsigned_compares(m: &crate::spirv::ir::TypedModule) -> usize {
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Under native half rounding where the NaN switch asks for Metal's NaN (`NanMinMaxPolicy::Exact`,
|
||||
/// `ModuleBuilder::texel_nans`), a texel's `half` keeps the NaN the device decoded, as under a
|
||||
/// rounding that is Metal's: every half bit pattern, widened as a device that decodes a half-float
|
||||
/// texel exactly hands it over, reads back as itself, bit for bit (NaNs of every sign and payload,
|
||||
/// signalling ones included), in both native forms, one lane at a time and four at once; a wider
|
||||
/// value rounds as the form does, a NaN staying a NaN; and the module holds the keep's one test of
|
||||
/// the texel's bits, which it leaves out where the switch is off (the default).
|
||||
#[test]
|
||||
fn a_texel_keeps_its_nan_under_native_half_rounding_where_the_nan_switch_asks() {
|
||||
use crate::spirv::builder::QuantizeForm;
|
||||
let halves: Vec<Case> = (0..=0xFFFFu16).map(|h| vec![vec![widened(h)]]).collect();
|
||||
let lanes: Vec<Case> = (0..0x1_0000u32)
|
||||
.step_by(4)
|
||||
.map(|h| vec![(h..h + 4).map(|x| widened(x as u16)).collect()])
|
||||
.collect();
|
||||
let wider: Vec<Case> = half_probe_bits()
|
||||
.into_iter()
|
||||
.map(|b| vec![vec![b]])
|
||||
.collect();
|
||||
for q in [QuantizeForm::Converted, QuantizeForm::Device] {
|
||||
let mut compares = [0usize; 2];
|
||||
for keep in [false, true] {
|
||||
let what = format!("{q:?} native, texel NaNs kept {keep}");
|
||||
let body = move |lanes: u8| {
|
||||
move |fb: &mut FunctionBuilder<'_>, x: &[Value]| -> BResult<Value> {
|
||||
fb.module().set_quantize_form(q);
|
||||
fb.module().set_native_half(true);
|
||||
fb.module().set_texel_nans(keep);
|
||||
texel(lanes)(fb, x)
|
||||
}
|
||||
};
|
||||
let m = kernel_with(&[float(32)], half(), &body(1), true, false)
|
||||
.unwrap_or_else(|e| panic!("{what}: build: {e:?}"));
|
||||
compares[usize::from(keep)] = unsigned_compares(&m);
|
||||
if keep {
|
||||
check_accept(
|
||||
&what,
|
||||
&[float(32)],
|
||||
half(),
|
||||
&body(1),
|
||||
&halves,
|
||||
&|c| Some(vec![want(arg(c, 0))]),
|
||||
&|g, w| g == w,
|
||||
);
|
||||
check_accept(
|
||||
&format!("{what}, half4"),
|
||||
&[vec(float(32), 4)],
|
||||
vec(half(), 4),
|
||||
&body(4),
|
||||
&lanes,
|
||||
&|c| Some(c[0].iter().map(|w| want(*w)).collect()),
|
||||
&|g, w| g == w,
|
||||
);
|
||||
}
|
||||
check_accept(
|
||||
&format!("{what}, wider"),
|
||||
&[float(32)],
|
||||
half(),
|
||||
&body(1),
|
||||
&wider,
|
||||
&|c| {
|
||||
Some(vec![u64::from(f64_to_f16(f64::from(f32::from_bits(
|
||||
arg(c, 0) as u32,
|
||||
))))])
|
||||
},
|
||||
&|g, w| g == w || (is_nan(half(), g) && is_nan(half(), w)),
|
||||
);
|
||||
}
|
||||
// The keep's one test of the texel's bits, there only where the switch asks.
|
||||
assert_eq!(compares[1], compares[0] + 1, "{q:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Under the float controls (`QuantizeForm::Controlled`), where the profile leaves a NaN's bits to
|
||||
/// the device (`ModuleBuilder::native_half_nans`, `NanMinMaxPolicy::Native`), a texel's `half` is
|
||||
/// Under the float controls (`QuantizeForm::Controlled`), where the module leaves a NaN's bits to
|
||||
/// the device (`ModuleBuilder::native_half_nans`, every profile so rounding), a texel's `half` is
|
||||
/// the conversion's own rounding: every half-float texel and every wider value but a NaN reads as
|
||||
/// with the keep, to nearest even with half subnormals kept, and a NaN stays a NaN, without the
|
||||
/// keep's unsigned compare of the texel's bits. Without the flag (the NaN switch's
|
||||
/// `NanMinMaxPolicy::Exact`) the keep stands, and every half bit pattern reads back as itself.
|
||||
/// keep's unsigned compare of the texel's bits. Without the flag the keep stands, and every half
|
||||
/// bit pattern reads back as itself.
|
||||
#[test]
|
||||
fn a_texel_under_the_float_controls_takes_the_conversions_nan_by_default() {
|
||||
use crate::spirv::builder::QuantizeForm;
|
||||
|
||||
@@ -662,11 +662,14 @@ fn fract_and_saturate_answer_as_metal() {
|
||||
f32_,
|
||||
&rows(|r| [u64::from(r.0), u64::from(r.2)]),
|
||||
);
|
||||
metal_answers(
|
||||
FloatFn::Saturate,
|
||||
f32_,
|
||||
&rows(|r| [u64::from(r.0), u64::from(r.3)]),
|
||||
);
|
||||
// `saturate` is the device's `NClamp(x, 0, 1)`: an `f32` denormal operand is the device's
|
||||
// (Metal flushes it to `+0`), every other lane Metal's.
|
||||
let normal = |(x, _): &Row| x[0] & 0x7F80_0000 != 0 || x[0] & 0x007F_FFFF == 0;
|
||||
let saturate: Vec<Row> = rows(|r| [u64::from(r.0), u64::from(r.3)])
|
||||
.into_iter()
|
||||
.filter(normal)
|
||||
.collect();
|
||||
metal_answers(FloatFn::Saturate, f32_, &saturate);
|
||||
metal_answers(
|
||||
FloatFn::Fract,
|
||||
half,
|
||||
|
||||
@@ -105,7 +105,6 @@ fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult<Declared> {
|
||||
// And every `half` rounding's quantize the device's form.
|
||||
mb.set_quantize_form(plan.families.arith.quantize);
|
||||
mb.set_native_half(plan.families.arith.native_half);
|
||||
mb.set_texel_nans(plan.families.arith.texel_nans);
|
||||
mb.set_native_half_nans(plan.families.arith.native_half_nans);
|
||||
let mut d = Declared::default();
|
||||
let modes = &mut d.modes;
|
||||
|
||||
@@ -711,7 +711,6 @@ fn data_element(ty: NumTy) -> Result<(Element, IoType), Error> {
|
||||
numeric,
|
||||
components: lanes,
|
||||
source_bits: bits,
|
||||
bits: 32,
|
||||
},
|
||||
))
|
||||
}
|
||||
@@ -846,7 +845,6 @@ fn target_index(cx: &mut SelectCx<'_>, which: TargetIndex) -> Result<MeshStrateg
|
||||
numeric: IoNumeric::Uint,
|
||||
components: 1,
|
||||
source_bits: 32,
|
||||
bits: 32,
|
||||
},
|
||||
};
|
||||
let list = &mut cx.families.stage_io.interface.outputs;
|
||||
|
||||
@@ -121,10 +121,8 @@ pub const fn shape(f: PushField) -> FieldShape {
|
||||
PushField::SlotBindOffset(_) | PushField::VertexBufferStride(_) => FieldShape::U32,
|
||||
// A texture's mipmap level count, an acceleration structure's instance count, the render
|
||||
// encoder's viewport count, the render pass's array length, a kernel stage-in buffer's
|
||||
// bound stride, whether a storage texture's channels are 16-bit floats, its integer
|
||||
// channels' widths.
|
||||
// bound stride, a storage texture's integer channels' widths.
|
||||
PushField::TextureLevels(_)
|
||||
| PushField::TextureHalfChannels(_)
|
||||
| PushField::TextureIntegerChannels(_)
|
||||
| PushField::InstanceCount(_)
|
||||
| PushField::ViewportCount
|
||||
|
||||
@@ -1426,7 +1426,7 @@ pub(super) fn sampled_value(
|
||||
cx,
|
||||
fb,
|
||||
(s, key),
|
||||
(texture, &p.fetch, super::fetched::classes(s), true),
|
||||
(texture, &p.fetch, super::fetched::CLASSES, true),
|
||||
image,
|
||||
&|fb, texels| super::fetched::plain_value(fb, s, texels),
|
||||
&|fb, si| fb.gather(si, coord, component, &ops),
|
||||
@@ -2644,7 +2644,7 @@ pub(super) fn held_value(
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let held = match (half, float) {
|
||||
Ok(match (half, float) {
|
||||
(Some(h), _) => {
|
||||
let access = match s.op {
|
||||
SampleOp::Gather { .. } => HalfForm::Read,
|
||||
@@ -2670,26 +2670,7 @@ pub(super) fn held_value(
|
||||
held_texel(fb, image.texel, form, x)?
|
||||
}
|
||||
(None, None) => held_texel(fb, image.texel, form, texel)?,
|
||||
};
|
||||
// Under the NaN switch, Metal's NaN: the texel's own where the sample reads one texel of a
|
||||
// texture of 16-bit float channels, else `0x7e00`.
|
||||
let Some(class) = s.half_nans else {
|
||||
return Ok(held);
|
||||
};
|
||||
use crate::lower::texture::{NanClass, OneTexel};
|
||||
let (class, one) = match (class, s.one_texel) {
|
||||
(NanClass::Never, _) | (_, OneTexel::Never) => (NanClass::Never, None),
|
||||
(class, OneTexel::Always) => (class, None),
|
||||
(class, OneTexel::Word(n)) => {
|
||||
let word = sampler_word(cx, fb, Pixel::Spec(n))?;
|
||||
(class, Some(word_reads_one(fb, word)?))
|
||||
}
|
||||
(class, OneTexel::Heap(h)) => {
|
||||
let word = sampler_word(cx, fb, Pixel::Heap(h))?;
|
||||
(class, Some(word_reads_one(fb, word)?))
|
||||
}
|
||||
};
|
||||
crate::lower::texture::metal_texel_nans(cx, fb, (class, one), texel, held)
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether sampler word `word` states a sampler that reads one texel of one level: nearest min and
|
||||
|
||||
@@ -238,8 +238,7 @@ pub(super) fn select(
|
||||
(image, shape): (ImageRef, ImageShape),
|
||||
operand: Option<crate::air::ir::Value>,
|
||||
) -> Result<Option<Plain>, Error> {
|
||||
let half_gather = half_gather(cx, op, form);
|
||||
if form.map(|f| f.conv) != Some(TexelConv::F32) && !half_gather {
|
||||
if form.map(|f| f.conv) != Some(TexelConv::F32) {
|
||||
return Ok(None);
|
||||
}
|
||||
let gather = match op {
|
||||
@@ -256,9 +255,7 @@ pub(super) fn select(
|
||||
};
|
||||
if cx.profile.device_samples() {
|
||||
cx.families.sampler.device_sampling = true;
|
||||
if !half_gather {
|
||||
return Ok(None);
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
let fetch = match (stat.map(|(r, _)| r), argument) {
|
||||
(Some(SamplerRef::Constexpr(words)), _) => {
|
||||
@@ -284,34 +281,9 @@ pub(super) fn select(
|
||||
Ok(fetch.map(|fetch| Plain { image, fetch }))
|
||||
}
|
||||
|
||||
/// Whether `op` is a gather with a `half` result whose texels the shader fetches where the bound
|
||||
/// class is a 16-bit float one: where the NaN switch asks for Metal's NaN
|
||||
/// (`NanMinMaxPolicy::Exact`, the profile's `TexelNanRoute::Metal`) on a device without Metal's
|
||||
/// own sampler. Metal's gather hands back a 16-bit float texel's own NaN; a device's gather need
|
||||
/// not (NVIDIA's hands back every NaN as `0x7fffffff`), and its fetch does
|
||||
/// where its read does.
|
||||
fn half_gather(cx: &SelectCx<'_>, op: &SampleOp, form: Option<TexelForm>) -> bool {
|
||||
use crate::device::profile::TexelNanRoute;
|
||||
use crate::device::requirements::VkProperty;
|
||||
matches!(op, SampleOp::Gather { dref: None, .. })
|
||||
&& form.map(|f| f.conv) == Some(TexelConv::F16)
|
||||
&& cx.profile.fields().texel_nans == TexelNanRoute::Metal
|
||||
&& !cx
|
||||
.profile
|
||||
.fields()
|
||||
.enabled
|
||||
.properties
|
||||
.contains(&VkProperty::MetalSampler)
|
||||
}
|
||||
|
||||
/// The format classes (`BicubicTexels` bits) whose texels the shader fetches for plain access
|
||||
/// `s`: the 32-bit float class, or for a `half` gather ([`half_gather`]) the half-float one.
|
||||
pub(super) fn classes(s: &Sampling) -> u32 {
|
||||
match (&s.op, s.texel.map(|f| f.conv)) {
|
||||
(SampleOp::Gather { .. }, Some(TexelConv::F16)) => BicubicTexels::HALF,
|
||||
_ => BicubicTexels::LINEAR,
|
||||
}
|
||||
}
|
||||
/// The format classes (`BicubicTexels` bits) whose texels the shader fetches for a plain access:
|
||||
/// the 32-bit float class.
|
||||
pub(super) const CLASSES: u32 = BicubicTexels::LINEAR;
|
||||
|
||||
/// How the shader fetches the texels of `op` (a gather, a sample through a sampler that reads one
|
||||
/// texel, its comparison taken out, or a comparison through nearest filters under a linear mip
|
||||
@@ -569,7 +541,7 @@ pub(super) fn heap(
|
||||
(_, Some(pixel)) => Some(super::emit::sampler_word(cx, fb, pixel)?),
|
||||
(_, None) => return Err(cx.fail("a word-addressed heap fetch without its word")),
|
||||
};
|
||||
let take = bits.test(fb, &t, classes(s))?;
|
||||
let take = bits.test(fb, &t, CLASSES)?;
|
||||
let take = match word {
|
||||
Some(w) => match word_reach(fb, &t, s, &p.fetch, w)? {
|
||||
Some(r) => fb.binary(BinOp::LogicalAnd, take, r)?,
|
||||
|
||||
@@ -677,10 +677,6 @@ pub struct Sampling {
|
||||
/// A `float` texel of the slot converts by the bound format's class (`float_texel`), where
|
||||
/// [`one_texel`](Self::one_texel) holds.
|
||||
pub float_texel: bool,
|
||||
/// Where the NaN switch asks for Metal's NaN, how the access's `half` texel answers a NaN
|
||||
/// texel (`texture::half_texel_nans`): by the class of the bound texture it names, and
|
||||
/// whether the access reads one texel ([`one_texel`](Self::one_texel)).
|
||||
pub half_nans: Option<crate::lower::texture::NanClass>,
|
||||
/// A [`centred`](Self::centred) sample through a runtime or argument buffer's sampler with a
|
||||
/// texel offset, on a device without `VkProperty::MetalSampler`, which adds the offset to the
|
||||
/// texel it reads before addressing it: the texel's centre moves back by the offset on an
|
||||
@@ -1290,10 +1286,7 @@ impl Sampling {
|
||||
} else {
|
||||
0
|
||||
}
|
||||
+ self.heap_raw.as_ref().map_or(0, heap_raw::HeapRaw::words)
|
||||
+ self
|
||||
.half_nans
|
||||
.map_or(0, crate::lower::texture::NanClass::words))
|
||||
+ self.heap_raw.as_ref().map_or(0, heap_raw::HeapRaw::words))
|
||||
// The code a sampling routine holds is the routine's, counted once in the module.
|
||||
.saturating_sub(self.routed_words())
|
||||
}
|
||||
|
||||
@@ -2443,20 +2443,6 @@ fn select_one(
|
||||
// `half` texel's on every profile, a `float` one's where it converts.
|
||||
let half_converts = half && !raw && !matches!(op, SampleOp::Bicubic(_)) && !device;
|
||||
let converts = half_converts || float_texel;
|
||||
// Under the NaN switch, Metal's NaN of a `half` texel: by the class of the texture bound and,
|
||||
// where a runtime sampler's word decides, whether the word reads one texel. Not of an sRGB
|
||||
// raw texel, which decodes exactly to no NaN (`held_value` takes it first).
|
||||
let half_nans = match half && !raw {
|
||||
true => crate::lower::texture::texel_nans_class(cx, image, shape, one_texel)?,
|
||||
false => None,
|
||||
};
|
||||
// A depth texture's NaN is `0x7e00` whatever the sampler.
|
||||
let by_word = half_nans.is_some_and(|c| c != crate::lower::texture::NanClass::Never);
|
||||
if let (crate::lower::texture::OneTexel::Word(n), true) = (one_texel, by_word) {
|
||||
if let Some(s) = cx.families.sampler.slots.get_mut(&n) {
|
||||
s.texels = true;
|
||||
}
|
||||
}
|
||||
if let (crate::lower::texture::OneTexel::Word(n), true, ImageRef::Slot(_)) =
|
||||
(one_texel, converts, image)
|
||||
{
|
||||
@@ -2833,7 +2819,6 @@ fn select_one(
|
||||
one_texel,
|
||||
half_texel: half_converts && !shape.depth,
|
||||
float_texel,
|
||||
half_nans,
|
||||
centre_offset,
|
||||
unmapped,
|
||||
heap_raw: None,
|
||||
|
||||
@@ -550,9 +550,6 @@ pub struct SelectCx<'a> {
|
||||
func: FuncId,
|
||||
/// Whether each instruction's result is observed, by `InstId` ([`observed_results`]).
|
||||
observed: Vec<bool>,
|
||||
/// Whether each instruction's result may carry its NaN's bits to an observation, by `InstId`
|
||||
/// (`arith::nan::observed_payloads`).
|
||||
nan_payloads: Vec<bool>,
|
||||
}
|
||||
|
||||
impl SelectCx<'_> {
|
||||
@@ -657,15 +654,6 @@ impl SelectCx<'_> {
|
||||
.copied()
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Whether the result of instruction `id` may carry its NaN's bits to an observation: read
|
||||
/// by an instruction or terminator that does not drop them (`arith::nan::drops_payload`).
|
||||
pub fn nan_payload_observed(&self, id: InstId) -> bool {
|
||||
self.nan_payloads
|
||||
.get(id.raw() as usize)
|
||||
.copied()
|
||||
.unwrap_or(true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether each instruction's result is observed, by `InstId`: read by an instruction or
|
||||
@@ -1208,15 +1196,6 @@ pub fn select(
|
||||
}
|
||||
};
|
||||
let root_bytes = root_sets.charged();
|
||||
let nan_payloads = match arith::nan::observed_payloads(e, e.func, body, m) {
|
||||
Ok(n) => n,
|
||||
Err(err) => {
|
||||
m.release(observed_bytes);
|
||||
m.release(root_bytes);
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let nan_bytes = nan_payloads.len();
|
||||
let cx = SelectCx {
|
||||
entry: e,
|
||||
body,
|
||||
@@ -1250,12 +1229,10 @@ pub fn select(
|
||||
phis: access::phis::PhiFacts::default(),
|
||||
func: e.func,
|
||||
observed,
|
||||
nan_payloads,
|
||||
};
|
||||
let result = select_entry(cx, body, func.params.len(), m);
|
||||
m.release(observed_bytes);
|
||||
m.release(root_bytes);
|
||||
m.release(nan_bytes);
|
||||
result
|
||||
}
|
||||
|
||||
|
||||
@@ -28,10 +28,9 @@
|
||||
//! Metal's where the profile takes `DriverDeviation::MetalColorWrites`, and a lane's the function
|
||||
//! rounds to nearest even (its NaN `0x7fc00000`) where it takes `MetalFloatColorNans`; a `half`
|
||||
//! output's (held widened, its payload in the significand's top bits) where it takes
|
||||
//! `MetalHalfColorNans`, or where the function writes it through a 16-bit output (below);
|
||||
//! elsewhere the module records the note (`runtime_lane::color_writes`: ANV and RADV store
|
||||
//! `0xfe00`, from a 16-bit output too, lavapipe quiets or canonicalizes a `half` NaN, MoltenVK
|
||||
//! canonicalizes it from a 32-bit output).
|
||||
//! `MetalHalfColorNans`; elsewhere the module records the note (`runtime_lane::color_writes`:
|
||||
//! ANV and RADV store `0xfe00`, lavapipe quiets or canonicalizes a `half` NaN, MoltenVK
|
||||
//! canonicalizes it).
|
||||
//!
|
||||
//! On a profile that stores Metal's codes itself (`VkProperty::MetalColorWrites`) the map holds
|
||||
//! only half-float channels (`pipeline::color_writes`): only the NaN note is recorded, and the
|
||||
@@ -48,31 +47,14 @@
|
||||
//! as -1.0 (`DriverDeviation::MetalNorm16ColorWrites`: RADV on the Radeon 780M).
|
||||
//!
|
||||
//! An attachment no lane of which rounds is not listed as rounded: it keeps its Vulkan blend of
|
||||
//! one and zero, through which the facts were measured too. A write in the storage form, or
|
||||
//! through a 16-bit output, records the device's conversion: the facts are of the device's
|
||||
//! conversion of an output variable. A storage write the shader blends into a 16-bit float
|
||||
//! attachment gives every NaN as `0x7fc00000`, which the storage image's store converts: Metal's
|
||||
//! `0x7e00` where the profile takes `DriverDeviation::MetalFloatStorageNans` (the module requires
|
||||
//! its property), else the device's NaN, noted `PrecisionNote::DeviceNanEncoding` (ANV stores
|
||||
//! `0xfe00`).
|
||||
//!
|
||||
//! Where the device does not store the output's NaN as Metal does, but is measured to store a
|
||||
//! 16-bit output's bits unchanged (`DriverDeviation::HalfColorOutputBits`: MoltenVK 1.4.1 on the
|
||||
//! M3 Max and the M4), its conversion to 16 bits is Metal's `half(float)`
|
||||
//! (`DriverDeviation::MetalHalfConversion`), and the profile declares 16-bit outputs
|
||||
//! (`storageInputOutput16`, with `shaderInt16` and `shaderFloat16`), an output to an attachment
|
||||
//! whose every channel written is half-float is written as the bits of its half, through a 16-bit
|
||||
//! output variable ([`half_output`]): each lane converted to 16 bits by that conversion, a NaN as
|
||||
//! its own payload's code by integer operations (`arith::color_write::half_bits`), so no
|
||||
//! conversion of the device's chooses the NaN, the NaN note is not recorded, and the module
|
||||
//! requires `VkProperty::HalfColorOutputBits` and `VkProperty::MetalHalfConversion`. An attachment
|
||||
//! a lane of which rounds is listed as rounded (`rounded_colors`), and one whose output is written
|
||||
//! so but rounds nothing as written as a half's bits (`half_bit_colors`), its own notice; either
|
||||
//! takes no Vulkan blend of one and zero. On a device not measured so the output stays 32-bit: ANV
|
||||
//! and RADV store every NaN of a 16-bit output as `0xfe00` too, so the route would change nothing
|
||||
//! there.
|
||||
//! one and zero, through which the facts were measured too. A write in the storage form records
|
||||
//! the device's conversion: the facts are of the device's conversion of an output variable. A
|
||||
//! storage write the shader blends into a 16-bit float attachment gives every NaN as
|
||||
//! `0x7fc00000`, which the storage image's store converts: Metal's `0x7e00` where the profile takes
|
||||
//! `DriverDeviation::MetalFloatStorageNans` (the module requires its property), else the device's
|
||||
//! NaN, noted `PrecisionNote::DeviceNanEncoding` (ANV stores `0xfe00`). An attachment a lane of
|
||||
//! which rounds is listed as rounded (`rounded_colors`), and takes no Vulkan blend of one and zero.
|
||||
|
||||
use crate::air::abi::{AbiInt, OutputRole};
|
||||
use crate::device::requirements::VkProperty;
|
||||
use crate::error::DriverDeviation;
|
||||
use crate::lower::arith::color_write;
|
||||
@@ -106,7 +88,6 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
|
||||
let metal = cx
|
||||
.profile
|
||||
.takes_driver_deviation(DriverDeviation::MetalColorWrites);
|
||||
let half = half_output(cx, color, f);
|
||||
let storage = crate::lower::fragment::writes_through_storage(cx, color);
|
||||
// A storage write the shader blends into a 16-bit float attachment stores the blend's `half`
|
||||
// in every channel, which the device converts exactly, but for a NaN: no conversion of an
|
||||
@@ -122,7 +103,7 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
|
||||
let mut relied = BTreeSet::new();
|
||||
for (slot, rule) in lanes.iter_mut().zip(rules).take(usize::from(f.lanes)) {
|
||||
let Some(rule) = rule else { continue };
|
||||
nans |= !shader_blended && color_writes::half_float(rule) && !nan_kept(cx, rule, f, half);
|
||||
nans |= !shader_blended && color_writes::half_float(rule) && !nan_kept(cx, rule, f);
|
||||
if metal && rule == color_writes::HALF {
|
||||
continue;
|
||||
}
|
||||
@@ -144,7 +125,7 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
|
||||
(rule @ ChannelWrite::FloatNearestEven { .. }, Some(_)) => *slot = Some(rule),
|
||||
(ChannelWrite::BlendedNearestEven { .. }, _) => blended |= !shader_blended,
|
||||
(ChannelWrite::Device, _) => device |= !shader_blended,
|
||||
(rule, Some(fmt)) => match conversion(cx, rule, fmt, half || storage, &mut relied) {
|
||||
(rule, Some(fmt)) => match conversion(cx, rule, fmt, storage, &mut relied) {
|
||||
Conversion::Metal => {}
|
||||
Conversion::MetalButNan => nans |= !shader_blended,
|
||||
Conversion::Device => device |= !shader_blended,
|
||||
@@ -163,24 +144,13 @@ pub(crate) fn plan(cx: &mut SelectCx<'_>, color: u32, f: Form) {
|
||||
if nans {
|
||||
cx.precision.insert(PrecisionNote::DeviceNanEncoding);
|
||||
}
|
||||
if half {
|
||||
cx.families.stage_io.halves.insert(color);
|
||||
relied.extend([
|
||||
VkProperty::HalfColorOutputBits,
|
||||
VkProperty::MetalHalfConversion,
|
||||
]);
|
||||
}
|
||||
cx.families.stage_io.color_properties.extend(relied);
|
||||
let rounds = lanes.iter().any(Option::is_some);
|
||||
let sp = &mut cx.families.stage_io;
|
||||
if rounds {
|
||||
sp.rounded.insert(color, lanes);
|
||||
if !lanes.iter().any(Option::is_some) {
|
||||
return;
|
||||
}
|
||||
let listed = match (rounds, half) {
|
||||
(true, _) => &mut sp.interface.rounded_colors,
|
||||
(false, true) => &mut sp.interface.half_bit_colors,
|
||||
(false, false) => return,
|
||||
};
|
||||
let sp = &mut cx.families.stage_io;
|
||||
sp.rounded.insert(color, lanes);
|
||||
let listed = &mut sp.interface.rounded_colors;
|
||||
if let Err(at) = listed.binary_search(&color) {
|
||||
listed.insert(at, color);
|
||||
}
|
||||
@@ -217,8 +187,7 @@ enum Conversion {
|
||||
|
||||
/// How the device converts a lane of an output of `fmt` to a channel of rule `rule` (`own`: the
|
||||
/// function writes the output otherwise than as a value of its output variable the device
|
||||
/// converts, as a half's bits through a 16-bit output, [`half_output`], or as a texel of a storage
|
||||
/// image, which no fact measures): as Metal does where the profile takes the deviation measuring
|
||||
/// converts, as a texel of a storage image, which no fact measures): as Metal does where the profile takes the deviation measuring
|
||||
/// it, whose property the module then relies on (`relied`), else the device's own:
|
||||
///
|
||||
/// - a `float` output to a half-float or unsigned small float channel where the profile takes
|
||||
@@ -254,14 +223,13 @@ fn conversion(
|
||||
}
|
||||
|
||||
/// Whether the device stores the NaN a fragment function writes to a half-float channel of rule
|
||||
/// `rule` from its output of form `f` as Metal does (the module docs; `half`: written as a half's
|
||||
/// bits, [`half_output`]): a `float` output's where the profile takes
|
||||
/// `rule` from its output of form `f` as Metal does (the module docs): a `float` output's where the
|
||||
/// profile takes
|
||||
/// `DriverDeviation::MetalColorWrites`, or where the function rounds the lane
|
||||
/// (`color_writes::HALF_NEAREST`), whose NaN `0x7fc00000` it then stores as Metal's `0x7e00`
|
||||
/// under `MetalFloatColorNans` (the output's own NaN, unrounded, it is not measured to); a `half`
|
||||
/// output's where it takes `MetalHalfColorNans`, or written as a half's bits. Another output stores
|
||||
/// no NaN of its own there.
|
||||
fn nan_kept(cx: &SelectCx<'_>, rule: ChannelWrite, f: Form, half: bool) -> bool {
|
||||
/// output's where it takes `MetalHalfColorNans`. Another output stores no NaN of its own there.
|
||||
fn nan_kept(cx: &SelectCx<'_>, rule: ChannelWrite, f: Form) -> bool {
|
||||
let takes = |d| cx.profile.takes_driver_deviation(d);
|
||||
match f.float_fmt() {
|
||||
Some(FloatFmt::F32) => {
|
||||
@@ -269,74 +237,11 @@ fn nan_kept(cx: &SelectCx<'_>, rule: ChannelWrite, f: Form, half: bool) -> bool
|
||||
|| (rule == color_writes::HALF_NEAREST
|
||||
&& takes(DriverDeviation::MetalFloatColorNans))
|
||||
}
|
||||
Some(FloatFmt::Half) => half || takes(DriverDeviation::MetalHalfColorNans),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the device stores the NaN of a fragment function's output of form `f` to a
|
||||
/// half-float channel as Metal does, for [`half_output`]: a `float` output's where the profile
|
||||
/// takes `DriverDeviation::MetalFloatColorNans` or `MetalColorWrites`, a `half` output's where it
|
||||
/// takes `MetalHalfColorNans`. Another output stores no NaN of its own there.
|
||||
fn metal_nans(cx: &SelectCx<'_>, f: Form) -> bool {
|
||||
let takes = |d| cx.profile.takes_driver_deviation(d);
|
||||
match f.float_fmt() {
|
||||
Some(FloatFmt::F32) => {
|
||||
takes(DriverDeviation::MetalColorWrites) || takes(DriverDeviation::MetalFloatColorNans)
|
||||
}
|
||||
Some(FloatFmt::Half) => takes(DriverDeviation::MetalHalfColorNans),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a fragment function writes its output of form `f` (dual-source index 0) to color
|
||||
/// attachment `color` as the bits of the half Metal stores, through a 16-bit output variable
|
||||
/// (the module docs): the output is `float` or `half` and the device does not store its NaN as
|
||||
/// Metal does, but stores a 16-bit output's bits unchanged
|
||||
/// (`DriverDeviation::HalfColorOutputBits`); its conversion to 16 bits is Metal's `half(float)`
|
||||
/// (`narrow::QuantizeForm::Converted`: `DriverDeviation::MetalHalfConversion` and `shaderFloat16`,
|
||||
/// not native half rounding's conversion); every channel of the attachment it writes is half-float
|
||||
/// (`color_writes::HALF`), none the device's; the profile declares 16-bit outputs
|
||||
/// (`storageInputOutput16`) and the `Int16` arithmetic that builds a NaN's code (a channel that
|
||||
/// rounds to nearest even, `color_writes::HALF_NEAREST`, is half-float too); and the
|
||||
/// function writes the attachment through an output variable, with no dual-source second
|
||||
/// output beside it.
|
||||
pub(super) fn half_output(cx: &SelectCx<'_>, color: u32, f: Form) -> bool {
|
||||
let Some(rules) = cx.inputs.color_writes.get(&color) else {
|
||||
return false;
|
||||
};
|
||||
let leaf = cx.profile.fields().leaf;
|
||||
let written = || rules.iter().take(usize::from(f.lanes));
|
||||
let dual = cx.entry.ep.outputs.iter().any(|o| {
|
||||
matches!(
|
||||
o.role,
|
||||
OutputRole::RenderTarget {
|
||||
attachment: AbiInt::Const(a),
|
||||
index: 1,
|
||||
..
|
||||
} if a == color
|
||||
)
|
||||
});
|
||||
cx.stage == Stage::Fragment
|
||||
&& matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half))
|
||||
&& !metal_nans(cx, f)
|
||||
&& cx
|
||||
.profile
|
||||
.takes_driver_deviation(DriverDeviation::HalfColorOutputBits)
|
||||
&& crate::lower::arith::narrow::quantize_form(cx.profile)
|
||||
== crate::spirv::builder::QuantizeForm::Converted
|
||||
// The measured conversion, not native half rounding's.
|
||||
&& cx
|
||||
.profile
|
||||
.takes_driver_deviation(DriverDeviation::MetalHalfConversion)
|
||||
&& leaf.input_output_16bit
|
||||
&& leaf.int16
|
||||
&& written().any(Option::is_some)
|
||||
&& written().flatten().all(|&r| color_writes::half_float(r))
|
||||
&& !dual
|
||||
&& !crate::lower::fragment::writes_through_storage(cx, color)
|
||||
}
|
||||
|
||||
/// The words of the planned roundings, each emitted once per return.
|
||||
pub(super) fn words(rounded: impl IntoIterator<Item = [Option<ChannelWrite>; 4]>) -> u64 {
|
||||
rounded.into_iter().map(|r| color_write::words(&r)).sum()
|
||||
|
||||
@@ -87,7 +87,6 @@ pub(super) fn plan(
|
||||
numeric: IoNumeric::Uint,
|
||||
components: e.form.raw_components() as u8,
|
||||
source_bits: 32,
|
||||
bits: 32,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -74,7 +74,7 @@
|
||||
|
||||
use crate::error::{DescriptorError, Error, Feature, LowerFamily, Unsupported};
|
||||
use crate::lower::access::pulled::{self, SourceRead};
|
||||
use crate::lower::arith::{exact_division, nan, narrow, ops, FloatFmt, Form, Held};
|
||||
use crate::lower::arith::{exact_division, narrow, ops, FloatFmt, Form, Held};
|
||||
use crate::lower::dispatch;
|
||||
use crate::lower::emit::EmitCx;
|
||||
use crate::lower::select::SelectCx;
|
||||
@@ -472,6 +472,7 @@ pub(super) fn select(
|
||||
return Err(not_lowered());
|
||||
}
|
||||
class_match(encoding, form.is_float(), attribute)?;
|
||||
narrow_float_nans(cx, encoding, form);
|
||||
let s = slot(Stage::Vertex, buffer);
|
||||
let draw_parameters = cx.profile.fields().draw_parameters;
|
||||
// The indexed capture form's per-vertex element is the vertex its index names.
|
||||
@@ -773,6 +774,18 @@ fn components(fb: &mut FunctionBuilder<'_>, e: Encoding, raw: SValue) -> BResult
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Record `PrecisionNote::DeviceNanEncoding` for a read of an attribute of `encoding` as `float`
|
||||
/// lanes of `form` where the encoding is a narrow float's ([`Encoding::widens_narrow_float`]):
|
||||
/// Metal's fetch answers its canonical NaN, sign and payload dropped, where the decode carries the
|
||||
/// 16-, 11- or 10-bit field's bits up into the payload. A `half` read keeps the field's own bits,
|
||||
/// as Metal's does.
|
||||
pub(super) fn narrow_float_nans(cx: &mut SelectCx<'_>, encoding: Encoding, form: Form) {
|
||||
if encoding.widens_narrow_float() && form.float_fmt() == Some(FloatFmt::F32) {
|
||||
cx.precision
|
||||
.insert(crate::pipeline::artifact::PrecisionNote::DeviceNanEncoding);
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of form `form` of the raw bytes `raw` of `encoding` (see the module docs).
|
||||
pub fn decode(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
@@ -796,19 +809,6 @@ pub fn decode(
|
||||
*c = fb.convert(op, *c, ft)?;
|
||||
}
|
||||
}
|
||||
// A narrow float's widening to `float` answers Metal's canonical NaN, sign and payload
|
||||
// dropped (`nan::NanAnswer::CanonicalExact`, the widening class of Metal's NaN model), where
|
||||
// ours carries the 16-, 11- or 10-bit field's bits up into the payload by construction and a
|
||||
// device whose own widening the module takes may carry them too. Answered on the bits alone
|
||||
// (`nan::canonical_on_bits`), which leaves no float operation for a driver that assumes no
|
||||
// NaNs to fold: the answer here is read bit for bit. A `half` parameter is not widened at
|
||||
// all: it keeps the fetched bits, as Metal's does, and for a field of another width
|
||||
// `narrow::round` answers the canonical `half` NaN.
|
||||
if encoding.widens_narrow_float() && form.float_fmt() == Some(FloatFmt::F32) {
|
||||
for c in &mut comps {
|
||||
*c = nan::canonical_on_bits(fb, f32_scalar(), *c)?;
|
||||
}
|
||||
}
|
||||
let scalar = Form { lanes: 1, ..form };
|
||||
let exact_half =
|
||||
matches!(encoding, Encoding::Half { .. }) && form.float_fmt() == Some(FloatFmt::Half);
|
||||
|
||||
@@ -723,18 +723,13 @@ fn every_ten_and_two_bit_code_is_correctly_rounded() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A narrow float's widening to a `float` parameter answers Metal's canonical NaN, sign and
|
||||
/// payload dropped, while a `half` parameter keeps the fetched `half`'s own bits.
|
||||
///
|
||||
/// Metal's answer, from `vertex-format-float4`'s and `attribute-format-fetches`' recordings of
|
||||
/// plain Metal on an M3 Max under macOS 27.0.1: the `half` codes `0x7E01` and `0xFE01` both reach
|
||||
/// a `float` attribute as `0x7FC00000`, and so does a `FloatRG11B10` field whose 5-bit exponent
|
||||
/// is all ones; the same `half` codes reach a `half` attribute as themselves
|
||||
/// A narrow float's widening to a `float` parameter carries a NaN field's sign and payload up into
|
||||
/// the `f32` NaN (the device's NaN encoding, `PrecisionNote::DeviceNanEncoding`, where Metal answers
|
||||
/// `0x7FC00000`), while a `half` parameter keeps the fetched `half`'s own bits, as Metal's does
|
||||
/// (`vertex-format-half4`). Every finite, zero, subnormal and infinite code is bit-exact either
|
||||
/// way, which `every_format_decodes_exactly` holds.
|
||||
#[test]
|
||||
fn a_narrow_floats_widening_answers_metals_canonical_nan() {
|
||||
const CANONICAL: u32 = 0x7FC0_0000;
|
||||
fn a_narrow_floats_widening_carries_the_fields_nan_bits() {
|
||||
/// The `f32` bits of a `half` whose exponent field is all ones, by the IEEE widening: the
|
||||
/// sign, an all-ones `f32` exponent, and the 10-bit mantissa in the top of the 23-bit one.
|
||||
fn widened(h: u16) -> u32 {
|
||||
@@ -754,11 +749,7 @@ fn a_narrow_floats_widening_answers_metals_canonical_nan() {
|
||||
let e = encoding(VertexFormat::Half4).expect("encoding");
|
||||
let m = module(e, float(4), Elem::Constant, 0, check);
|
||||
let got = run(&m, &data, [0, 0, 0, 0], 4);
|
||||
assert_eq!(
|
||||
got,
|
||||
[CANONICAL, CANONICAL, CANONICAL, f32::INFINITY.to_bits()],
|
||||
"Half4 into float4 {check:?}"
|
||||
);
|
||||
assert_eq!(got, halves.map(widened), "Half4 into float4 {check:?}");
|
||||
// The same codes into a `half` parameter, held widened: their own bits, as Metal's
|
||||
// `half` attribute keeps them.
|
||||
let m = module(e, half_form(4), Elem::Constant, 0, check);
|
||||
@@ -767,9 +758,10 @@ fn a_narrow_floats_widening_answers_metals_canonical_nan() {
|
||||
let e = encoding(VertexFormat::FloatRG11B10).expect("encoding");
|
||||
let m = module(e, float(4), Elem::Constant, 8, check);
|
||||
let got = run(&m, &data, [0, 0, 0, 0], 4);
|
||||
// Each field's mantissa in the top of the `f32` one: six bits, six, then five.
|
||||
assert_eq!(
|
||||
got,
|
||||
[CANONICAL, CANONICAL, CANONICAL, 1.0f32.to_bits()],
|
||||
[0x7FFE_0000, 0x7FFE_0000, 0x7FFC_0000, 1.0f32.to_bits()],
|
||||
"FloatRG11B10 into float4 {check:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -193,9 +193,6 @@ pub enum IoObject {
|
||||
numeric: IoNumeric,
|
||||
components: u8,
|
||||
deco: IoDecor,
|
||||
/// Declared as 16-bit `half` lanes: a color output the function writes as the bits of
|
||||
/// the half Metal stores (`color_write::half_output`).
|
||||
half: bool,
|
||||
},
|
||||
/// A builtin variable.
|
||||
Builtin {
|
||||
@@ -268,12 +265,6 @@ pub enum Source {
|
||||
/// the variable, declared `Flat`, read as Metal's interpolation returns such a value
|
||||
/// ([`metal_interpolated_constant`]).
|
||||
Uniform(Link),
|
||||
/// A fixed-function vertex attribute of a narrow-float Metal format (a `half` format, or
|
||||
/// `FloatRG11B10`; `VertexFetch::FixedFunction`'s `narrow_float`) read as `float`: the
|
||||
/// variable, with Metal's canonical NaN where the device's own widening of the field left a
|
||||
/// NaN, whose payload and sign Metal's fetch drops (`nan::canonical_on_bits`). Every finite,
|
||||
/// zero, subnormal and infinite code the widening delivers passes through.
|
||||
WidenedAttribute(Link),
|
||||
/// A fragment function's `[[primitive_id]]` under `LoweringInputs::quad_primitive_ids`:
|
||||
/// Vulkan's `PrimitiveId` (the variable) shifted right by one, the quad of the list's
|
||||
/// triangle, as Metal counts one primitive a quad of its private quads and quad strip.
|
||||
@@ -409,9 +400,6 @@ pub struct StageIoPlan {
|
||||
/// (`color_write`), through an output variable or in the storage form: each by its rule, a
|
||||
/// half-float channel's under `TextureWriteRoundingMode::NearestEven`.
|
||||
pub rounded: BTreeMap<u32, [Option<crate::pipeline::lower_inputs::ChannelWrite>; 4]>,
|
||||
/// The color attachments whose output the function writes as the bits of the half Metal
|
||||
/// stores, through a 16-bit output variable (`color_write::half_output`).
|
||||
pub halves: BTreeSet<u32>,
|
||||
/// The measured driver deviations, as their properties, a fragment function's color writes
|
||||
/// rely on: channels that record no device conversion because the device converts them as
|
||||
/// Metal does (`color_write`). The module requires them.
|
||||
@@ -1198,7 +1186,6 @@ pub fn emit_entry(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>) -> BResult<
|
||||
| Source::CapturedBaseVertex(_)
|
||||
| Source::Merged { .. }
|
||||
| Source::Uniform(_)
|
||||
| Source::WidenedAttribute(_)
|
||||
| Source::QuadPrimitive(_) => None,
|
||||
})
|
||||
.collect();
|
||||
@@ -1292,12 +1279,6 @@ pub fn param_value(
|
||||
let x = metal_interpolated_constant(fb, link.form, x)?;
|
||||
return narrow::round(fb, link.form, x);
|
||||
}
|
||||
Some(Source::WidenedAttribute(link)) => {
|
||||
let p = pointer(cx, fb, &link)?;
|
||||
let x = fb.load(p, MemAccess::default())?;
|
||||
let x = crate::lower::arith::nan::canonical_on_bits(fb, link.form, x)?;
|
||||
return to_lowered(cx, fb, &link, x);
|
||||
}
|
||||
Some(Source::QuadPrimitive(link)) => {
|
||||
let p = pointer(cx, fb, &link)?;
|
||||
let x = fb.load(p, MemAccess::default())?;
|
||||
@@ -2733,16 +2714,10 @@ fn io_elem(mb: &mut ModuleBuilder, numeric: IoNumeric) -> BResult<TypeId> {
|
||||
}
|
||||
|
||||
/// Store output part `x` (in its lowered representation, which is the interface type, except a
|
||||
/// `bool`, carried as `uint` 1 or 0, a 32-bit integer declared `int`, whose bits are stored by
|
||||
/// `OpBitcast`, and a color output declared `half`, whose half's bits are stored) through `link`.
|
||||
/// `bool`, carried as `uint` 1 or 0, and a 32-bit integer declared `int`, whose bits are stored by
|
||||
/// `OpBitcast`) through `link`.
|
||||
fn store(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, link: &Link, x: SValue) -> BResult<()> {
|
||||
let half = matches!(
|
||||
cx.plan.families.stage_io.objects.get(link.object),
|
||||
Some(IoObject::User { half: true, .. })
|
||||
);
|
||||
let x = if half {
|
||||
crate::lower::arith::color_write::half_bits(fb, link.form, x)?
|
||||
} else if bool_as_uint(cx, link) {
|
||||
let x = if bool_as_uint(cx, link) {
|
||||
let one = ops::splat(fb, uint_lanes(link.form), 1)?;
|
||||
let zero = ops::splat(fb, uint_lanes(link.form), 0)?;
|
||||
fb.select(x, one, zero)?
|
||||
@@ -2818,12 +2793,8 @@ pub fn declare(
|
||||
numeric,
|
||||
components,
|
||||
deco,
|
||||
half,
|
||||
} => {
|
||||
let elem = match half {
|
||||
true => mb.ty(SType::Float { width: 16 })?,
|
||||
false => io_elem(mb, *numeric)?,
|
||||
};
|
||||
let elem = io_elem(mb, *numeric)?;
|
||||
let ty = if *components == 1 {
|
||||
elem
|
||||
} else {
|
||||
|
||||
@@ -171,7 +171,6 @@ pub(super) fn io_type(f: Form) -> IoType {
|
||||
},
|
||||
components: f.lanes,
|
||||
source_bits: f.bits(),
|
||||
bits: 32,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -206,7 +205,6 @@ fn user(
|
||||
numeric: ty.numeric,
|
||||
components: ty.components,
|
||||
deco,
|
||||
half: ty.bits == 16,
|
||||
};
|
||||
// One key per direction: a second, different declaration of the same key is not a Metal
|
||||
// interface.
|
||||
@@ -433,7 +431,6 @@ pub fn param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> {
|
||||
let mut at_loop_sample = false;
|
||||
let mut uniform = false;
|
||||
let mut quad_primitive = false;
|
||||
let mut widened = false;
|
||||
let link = match (&b.role, stage) {
|
||||
// A merged draw's vertex reads its corner's command's draw values.
|
||||
(
|
||||
@@ -486,15 +483,16 @@ pub fn param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> {
|
||||
return Ok(());
|
||||
}
|
||||
// The device's fixed-function input widens a narrow-float format with a widening of
|
||||
// its own, which carries the field's bits up into the `float` payload; Metal's fetch
|
||||
// answers its canonical NaN. A `float` parameter's load is canonicalized
|
||||
// (`Source::WidenedAttribute`); a `half` one keeps the fetched code's own bits, as
|
||||
// Metal's `half` attribute does, so it is loaded as it is.
|
||||
// its own, which may carry the field's bits up into the `float` payload; Metal's fetch
|
||||
// answers its canonical NaN. A `float` parameter's NaN is the device's, noted; a
|
||||
// `half` one keeps the fetched code's own bits, as Metal's `half` attribute does.
|
||||
let narrow_float = matches!(
|
||||
entry,
|
||||
Some(VertexFetch::FixedFunction { narrow_float: true })
|
||||
);
|
||||
widened = narrow_float && f.float_fmt() == Some(FloatFmt::F32);
|
||||
if narrow_float && f.float_fmt() == Some(FloatFmt::F32) {
|
||||
cx.precision.insert(PrecisionNote::DeviceNanEncoding);
|
||||
}
|
||||
let key = VaryingKey::attribute(index);
|
||||
let sp = &mut cx.families.stage_io;
|
||||
let object = user(
|
||||
@@ -845,9 +843,7 @@ pub fn param(cx: &mut SelectCx<'_>, b: &ParamBinding) -> Result<(), Error> {
|
||||
};
|
||||
cx.families.stage_io.params.push(PlannedParam {
|
||||
param: b.param,
|
||||
source: if widened {
|
||||
Source::WidenedAttribute(link)
|
||||
} else if at_loop_sample {
|
||||
source: if at_loop_sample {
|
||||
Source::AtLoopSample(link)
|
||||
} else if at_pixel {
|
||||
Source::PixelCenter(link)
|
||||
@@ -949,7 +945,6 @@ fn zeroed_output(
|
||||
numeric,
|
||||
components: 4,
|
||||
source_bits: 32,
|
||||
bits: 32,
|
||||
};
|
||||
if let Some(rules) = cx.inputs.color_writes.get(&color).copied() {
|
||||
cx.families
|
||||
@@ -1395,7 +1390,6 @@ fn selected_index(sp: &mut StageIoPlan, index: RawIndex) -> Result<usize, Error>
|
||||
numeric: IoNumeric::Uint,
|
||||
components: 1,
|
||||
source_bits: 32,
|
||||
bits: 32,
|
||||
};
|
||||
let deco = IoDecor {
|
||||
packed: true,
|
||||
@@ -1453,7 +1447,6 @@ pub(super) fn window_depth(sp: &mut StageIoPlan, dir: IoDir) -> Result<usize, Er
|
||||
numeric: IoNumeric::Float,
|
||||
components: 1,
|
||||
source_bits: 32,
|
||||
bits: 32,
|
||||
};
|
||||
let mut deco = IoDecor {
|
||||
packed: true,
|
||||
@@ -1556,7 +1549,6 @@ fn barycentric_weights(sp: &mut StageIoPlan, perspective: bool) -> Result<usize,
|
||||
numeric: IoNumeric::Float,
|
||||
components: 2,
|
||||
source_bits: 32,
|
||||
bits: 32,
|
||||
};
|
||||
let deco = IoDecor {
|
||||
interpolation: if perspective {
|
||||
@@ -1649,7 +1641,6 @@ fn flat_uint(
|
||||
numeric: IoNumeric::Uint,
|
||||
components: 1,
|
||||
source_bits: 32,
|
||||
bits: 32,
|
||||
};
|
||||
let mut deco = IoDecor {
|
||||
packed: true,
|
||||
@@ -3063,11 +3054,6 @@ fn output(cx: &mut SelectCx<'_>, o: &OutputBinding, ty: AirTypeId) -> Result<Lin
|
||||
}
|
||||
let f = io_form(cx, ty)?;
|
||||
let io = color_type(cx, attachment, f)?;
|
||||
// Written as a half's bits through 16-bit lanes (`color_write::half_output`).
|
||||
let io = match index == 0 && super::color_write::half_output(cx, attachment, f) {
|
||||
true => IoType { bits: 16, ..io },
|
||||
false => io,
|
||||
};
|
||||
// An extended-range attachment's raw texel, through a variable of its raw components,
|
||||
// and a word attachment's word; the interface keeps the Metal output's type.
|
||||
let declared = match super::word_color::plan(cx, attachment, index, f)? {
|
||||
@@ -3177,9 +3163,6 @@ const UNIFORM_WORDS: u64 = 64;
|
||||
/// The words a use of a [`Source::QuadPrimitive`] parameter adds to a load: the shift and its
|
||||
/// constant.
|
||||
const QUAD_PRIMITIVE_WORDS: u64 = 8;
|
||||
/// The words a use of a [`Source::WidenedAttribute`] parameter adds to a load: the NaN test on the
|
||||
/// bits, the select, and their constants.
|
||||
const CANONICAL_NAN_WORDS: u64 = 32;
|
||||
|
||||
/// The per-stage interface limits and the size estimate.
|
||||
pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
@@ -3357,13 +3340,9 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> {
|
||||
.values()
|
||||
.filter(|i| matches!(i.kind, crate::air::ir::InstKind::Ret(_)))
|
||||
.count() as u64;
|
||||
// Each return also rounds every color output that rounds, writes the halves' bits, and encodes
|
||||
// the extended-range colors' texels.
|
||||
// Each return also rounds every color output that rounds, and encodes the extended-range
|
||||
// colors' texels.
|
||||
let rounding = super::color_write::words(sp.rounded.values().copied())
|
||||
.saturating_add(
|
||||
crate::lower::arith::color_write::HALF_BITS_WORDS
|
||||
.saturating_mul(sp.halves.len() as u64),
|
||||
)
|
||||
.saturating_add(super::extended_color::WORDS.saturating_mul(sp.extended.len() as u64))
|
||||
.saturating_add(
|
||||
(sp.words_written.values())
|
||||
@@ -3461,7 +3440,6 @@ fn param_words(cx: &SelectCx<'_>) -> u64 {
|
||||
loaded.push((p.param, USE_WORDS + PIXEL_WORDS))
|
||||
}
|
||||
Source::Uniform(_) => loaded.push((p.param, USE_WORDS + UNIFORM_WORDS)),
|
||||
Source::WidenedAttribute(_) => loaded.push((p.param, USE_WORDS + CANONICAL_NAN_WORDS)),
|
||||
Source::Pulled(r) => fetch_words = fetch_words.saturating_add(u64::from(r.words())),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,6 +116,7 @@ fn select(
|
||||
if fetch::class_match(encoding, form.is_float(), attribute).is_err() {
|
||||
return Err(not_lowered());
|
||||
}
|
||||
fetch::narrow_float_nans(cx, encoding, form);
|
||||
let layout = f.buffer_index;
|
||||
let rate = |rate: u32| -> Result<u32, Error> {
|
||||
match rate {
|
||||
|
||||
@@ -96,7 +96,6 @@ pub(super) fn plan(
|
||||
numeric: IoNumeric::Uint,
|
||||
components: 1,
|
||||
source_bits: 32,
|
||||
bits: 32,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -631,7 +631,6 @@ fn pulled_read(
|
||||
},
|
||||
components: form.lanes,
|
||||
source_bits: form.bits(),
|
||||
bits: 32,
|
||||
};
|
||||
sp.interface
|
||||
.pulled
|
||||
|
||||
@@ -21,7 +21,7 @@ use super::slice::Slice;
|
||||
use super::{
|
||||
Coord, ImageDecl, ImageRef, QueryKind, QueryOp, Read, TexelClass, TexelConv, TexelForm,
|
||||
};
|
||||
use super::{HalfNans, NullArm, Prelude, Switch, TextureStrategy, Write};
|
||||
use super::{NullArm, Prelude, Switch, TextureStrategy, Write};
|
||||
use crate::memory::handles::{HANDLE_ALPHA_ONE, NEUTRAL_ELEMENT, NULL_HANDLE};
|
||||
|
||||
/// Emit strategy `s` of instruction `at` into the open block.
|
||||
@@ -911,9 +911,7 @@ fn from_image(
|
||||
StorageImageClass::RotateArgb => rotate_argb(fb, x, true)?,
|
||||
StorageImageClass::AlphaInRed => alpha_in_red(fb, x, true)?,
|
||||
// A `YCbCrWrite` slot is only written (`StorageImageClass::YCbCrWrite`).
|
||||
StorageImageClass::HalfQuietNan
|
||||
| StorageImageClass::SmallFloatQuietNan
|
||||
| StorageImageClass::YCbCrWrite => x,
|
||||
StorageImageClass::YCbCrWrite => x,
|
||||
// A half-float texel's bits, through its unsigned integer alias: Metal's read, whole.
|
||||
StorageImageClass::HalfBits => return half_bits_texel(fb, decl, form, x),
|
||||
// An `RGB9E5Float` word, through its `R32_UINT` alias, decoded exactly.
|
||||
@@ -1692,8 +1690,7 @@ fn int_lanes(fb: &mut FunctionBuilder<'_>, elem: TypeId, lanes: &[u32]) -> BResu
|
||||
/// `x` (`f32` lanes of form `f`) rounded to nearest even onto `RG11B10Float`'s channels, as
|
||||
/// Metal's integer store rounds them: red and green to six fraction bits, blue to five, unsigned (a
|
||||
/// negative value to 0), a finite value that rounds past the largest finite one held there (65024,
|
||||
/// 64512), an infinity kept and a NaN quieted, which the float class's write stores as Metal's NaN
|
||||
/// code (`StorageImageClass::SmallFloatQuietNan`).
|
||||
/// 64512), an infinity kept and a NaN quieted, whose store the device converts.
|
||||
fn small_floats_nearest(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
f: crate::lower::arith::legal::Form,
|
||||
@@ -1794,13 +1791,6 @@ pub fn to_image(
|
||||
crate::spirv::error::TypeRule::FunctionSignature,
|
||||
))
|
||||
}
|
||||
StorageImageClass::HalfQuietNan | StorageImageClass::SmallFloatQuietNan => {
|
||||
match form.conv {
|
||||
TexelConv::F32 => half_write(fb, decl.class, form, x)?,
|
||||
// A `half` texel, held widened, is a half already: the device stores it exactly.
|
||||
_ => x,
|
||||
}
|
||||
}
|
||||
StorageImageClass::YCbCrWrite => ycbcr_write_texel(fb, form, x)?,
|
||||
StorageImageClass::HalfBits => half_bits(fb, form, x)?,
|
||||
StorageImageClass::SharedExponentBits => shared_exponent_word(fb, form, x)?,
|
||||
@@ -1867,9 +1857,9 @@ fn ycbcr_write_texel(fb: &mut FunctionBuilder<'_>, form: TexelForm, x: SValue) -
|
||||
/// `uvec4`: each channel of its format a half's bits, a channel it lacks the integer the device's
|
||||
/// read gives, 0 or alpha 1, and Metal's out-of-bounds texel's likewise): each channel's half
|
||||
/// widened exactly (`narrow::from_bits`), Metal's `half` read of the half stored, a NaN's sign
|
||||
/// and payload kept; for a `float` result every NaN `0x7fc00000`, Metal's `float` read of a half
|
||||
/// NaN (the M3 Max: every NaN, fast and safe math); a lane the format lacks its
|
||||
/// integer converted (0.0, alpha 1.0).
|
||||
/// and payload kept, a `float` result's too, where Metal's `float` read of a half NaN is
|
||||
/// `0x7fc00000` (the M3 Max: every NaN, fast and safe math; `PrecisionNote::DeviceNanEncoding`); a
|
||||
/// lane the format lacks its integer converted (0.0, alpha 1.0).
|
||||
fn half_bits_texel(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
decl: &ImageDecl,
|
||||
@@ -1898,13 +1888,6 @@ fn half_bits_texel(
|
||||
let one = f32s(fb, 1, 1.0)?;
|
||||
v = fb.composite_insert(one, v, &[3])?;
|
||||
}
|
||||
if form.conv == TexelConv::F32 {
|
||||
let f = Form {
|
||||
held: Held::Float(FloatFmt::F32),
|
||||
lanes: 4,
|
||||
};
|
||||
v = quiet_nans(fb, f, v)?;
|
||||
}
|
||||
match form.lanes {
|
||||
1 => fb.composite_extract(v, &[0]),
|
||||
_ => Ok(v),
|
||||
@@ -1916,7 +1899,7 @@ fn half_bits_texel(
|
||||
/// payload included). A `half` texel's lanes are halves already, widened exactly; a `float`
|
||||
/// texel's are first rounded to a half, which no conversion of the device's makes through the
|
||||
/// alias: toward zero, as Metal stores it (`color_write::small_float`: past 65504 to 65504, an
|
||||
/// infinity kept, every NaN [`QUIET_NAN`], whose bits are Metal's `0x7e00`). An integer texel is
|
||||
/// infinity kept, every NaN `0x7fc00000`, whose bits are Metal's `0x7e00`). An integer texel is
|
||||
/// not one a half-float slot takes.
|
||||
fn half_bits(fb: &mut FunctionBuilder<'_>, form: TexelForm, x: SValue) -> BResult<SValue> {
|
||||
use crate::lower::arith::legal::{FloatFmt, Form, Held};
|
||||
@@ -2070,77 +2053,6 @@ pub(crate) fn rgb9e5_word(fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult<SV
|
||||
Ok(word)
|
||||
}
|
||||
|
||||
/// The `f32` NaN a written `float`'s NaN becomes under `HalfQuietNan` and in a `HalfBits` slot's
|
||||
/// rounding (`color_write::small_float`'s), which a device of
|
||||
/// `DriverDeviation::MetalFloatStorageNans` stores as Metal's `0x7e00`.
|
||||
const QUIET_NAN: u32 = 0x7fc0_0000;
|
||||
|
||||
/// The words of [`quiet_nans`]: one test and one select of the whole vector, and the constant.
|
||||
const QUIET_NAN_WORDS: u32 = 24;
|
||||
|
||||
/// `x` (`f32` lanes of form `f`) with every NaN lane [`QUIET_NAN`]: one test and one select of
|
||||
/// the whole vector.
|
||||
fn quiet_nans(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
f: crate::lower::arith::legal::Form,
|
||||
x: SValue,
|
||||
) -> BResult<SValue> {
|
||||
let is_nan = fb.unary(crate::spirv::ir::UnOp::IsNan, x)?;
|
||||
let nan = crate::lower::arith::ops::splat(fb, f, u64::from(QUIET_NAN))?;
|
||||
fb.select(is_nan, nan, x)
|
||||
}
|
||||
|
||||
/// The channels of written `float` texel `x` (`f32` lanes of `form`) to a half-float or small
|
||||
/// float image by class `class`: under `HalfQuietNan` and `SmallFloatQuietNan` the value as
|
||||
/// computed, which the device's conversion rounds, but a NaN as [`QUIET_NAN`]. The NaN stores as
|
||||
/// the device's encoding of [`QUIET_NAN`] (Metal's `0x7e00` where measured,
|
||||
/// `DriverDeviation::MetalFloatStorageNans`).
|
||||
fn half_write(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
class: StorageImageClass,
|
||||
form: TexelForm,
|
||||
x: SValue,
|
||||
) -> BResult<SValue> {
|
||||
use crate::lower::arith::legal::{FloatFmt, Form, Held};
|
||||
let f = Form {
|
||||
held: Held::Float(FloatFmt::F32),
|
||||
lanes: form.lanes,
|
||||
};
|
||||
match class {
|
||||
StorageImageClass::HalfQuietNan | StorageImageClass::SmallFloatQuietNan => {
|
||||
quiet_nans(fb, f, x)
|
||||
}
|
||||
_ => Ok(x),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the texel class heap handle `handle` carries (its index in
|
||||
/// `metal::texel_format::heap_classes`) is a half-float format's (a `bool`): the index is one of
|
||||
/// [`heap_half_indices`](crate::metal::texel_format::heap_half_indices), the half-float family
|
||||
/// without a packed field (`R16Float`, `RG16Float`, `RGBA16Float`; a small float's class carries
|
||||
/// the field, and a swizzled texture's is `OTHER`, whose write the device converts). The index
|
||||
/// alone answers it, so the module needs no table of the classes.
|
||||
fn heap_half_format(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
handle: ValueId,
|
||||
) -> BResult<SValue> {
|
||||
let indices = crate::metal::texel_format::heap_half_indices();
|
||||
heap_class_among(cx, fb, handle, &indices)
|
||||
}
|
||||
|
||||
/// Whether the texel class heap handle `handle` carries is a small float's (a `bool`): its index
|
||||
/// is one of [`heap_small_float_indices`](crate::metal::texel_format::heap_small_float_indices),
|
||||
/// as [`heap_half_format`] tests the half-float ones.
|
||||
fn heap_small_float_format(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
handle: ValueId,
|
||||
) -> BResult<SValue> {
|
||||
let indices = crate::metal::texel_format::heap_small_float_indices();
|
||||
heap_class_among(cx, fb, handle, &indices)
|
||||
}
|
||||
|
||||
/// Whether the texel class index heap handle `handle` carries is one of `indices` (a `bool`).
|
||||
fn heap_class_among(
|
||||
cx: &mut EmitCx<'_>,
|
||||
@@ -2170,183 +2082,13 @@ fn heap_class_among(
|
||||
among.ok_or_else(|| cx.fail("no heap class of the family"))
|
||||
}
|
||||
|
||||
/// Whether a `half` texel's write keeps its widened half (a `bool`) where `nans` reads it at run
|
||||
/// time: a heap element's handle class is a half-float format's ([`heap_half_format`]), a slot's
|
||||
/// `PushField::TextureHalfChannels` is not 0. `None` where `nans` decides alone.
|
||||
fn half_kept(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
nans: HalfNans,
|
||||
image: &ImageRef,
|
||||
) -> BResult<Option<SValue>> {
|
||||
match (nans, image) {
|
||||
(HalfNans::HeapClass, ImageRef::Heap { handle, .. }) => {
|
||||
Ok(Some(heap_half_format(cx, fb, *handle)?))
|
||||
}
|
||||
(HalfNans::SlotWord(slot), _) => {
|
||||
let word = cx.push_field(
|
||||
fb,
|
||||
crate::pipeline::sym::PushField::TextureHalfChannels(slot),
|
||||
)?;
|
||||
let zero = u32s(fb, 1, 0)?;
|
||||
Ok(Some(fb.binary(BinOp::INotEqual, word, zero)?))
|
||||
}
|
||||
_ => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// `texel` (`f32` lanes of `form`) as a `half` texel's write stores it under `nans`: every NaN lane
|
||||
/// [`QUIET_NAN`] (`0x7fc00000`) under [`HalfNans::Canonical`], and under a runtime choice where
|
||||
/// `kept` ([`half_kept`]) is false; as it is elsewhere, the half widened.
|
||||
fn half_nan_texel(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
(nans, kept): (HalfNans, Option<SValue>),
|
||||
form: TexelForm,
|
||||
texel: SValue,
|
||||
) -> BResult<SValue> {
|
||||
use crate::lower::arith::legal::{FloatFmt, Form, Held};
|
||||
let f = Form {
|
||||
held: Held::Float(FloatFmt::F32),
|
||||
lanes: form.lanes,
|
||||
};
|
||||
match (nans, kept) {
|
||||
(HalfNans::Canonical, _) => quiet_nans(fb, f, texel),
|
||||
(HalfNans::HeapClass | HalfNans::SlotWord(_), Some(kept)) => {
|
||||
let canonical = quiet_nans(fb, f, texel)?;
|
||||
let cond = match form.lanes {
|
||||
1 => kept,
|
||||
n => {
|
||||
let b = fb.module().ty(SType::Bool)?;
|
||||
let ty = vec(fb, b, n)?;
|
||||
fb.composite_construct(ty, &vec![kept; usize::from(n)])?
|
||||
}
|
||||
};
|
||||
fb.select(cond, texel, canonical)
|
||||
}
|
||||
_ => Ok(texel),
|
||||
}
|
||||
}
|
||||
|
||||
/// Held `half` texel `held` of image texel `x` (`f32` lanes: the device's value, one texel's or
|
||||
/// filtered) with Metal's NaN wherever `x` is a NaN (`texture::half_texel_nans`): `x` itself, the
|
||||
/// device's decode of the texel, where the access reads one texel (`one`: `None` where it always
|
||||
/// does, else a `bool`) of a texture the class says holds 16-bit float channels (`class`: a slot's
|
||||
/// `TexelFormat` class of the half-float family without a packed field,
|
||||
/// `metal::texel_format::half_channels`, or `TexelFormat::OTHER`, a format whose
|
||||
/// conversion is not measured, whose NaN stays the device's decode as the module notes,
|
||||
/// `DeviceNanEncoding`; a heap handle's class index, [`heap_half_format`]); [`QUIET_NAN`]
|
||||
/// elsewhere, the `half` `0x7e00` held. The NaN test reads
|
||||
/// `x`'s bits, as `narrow::round_texel`'s does, so it holds whatever float modes the device
|
||||
/// compiles the module under. A `held` of one lane takes `x`'s first.
|
||||
pub(crate) fn metal_texel_nans(
|
||||
cx: &mut EmitCx<'_>,
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
(class, one): (super::NanClass, Option<SValue>),
|
||||
x: SValue,
|
||||
held: SValue,
|
||||
) -> BResult<SValue> {
|
||||
use super::NanClass;
|
||||
use crate::metal::bicubic::BicubicTexels;
|
||||
use crate::metal::texel_format::TexelFormat;
|
||||
let lanes_of = |fb: &mut FunctionBuilder<'_>, v: SValue| -> BResult<u8> {
|
||||
let ty = fb.value_ty(v)?;
|
||||
Ok(match fb.module().types().get(ty)? {
|
||||
SType::Vector { len, .. } => *len,
|
||||
_ => 1,
|
||||
})
|
||||
};
|
||||
let lanes = lanes_of(fb, held)?;
|
||||
let x = match lanes_of(fb, x)? {
|
||||
n if n == lanes => x,
|
||||
_ if lanes == 1 => fb.composite_extract(x, &[0])?,
|
||||
_ => return Err(cx.fail("Metal's NaN of a texel of fewer lanes than its held value")),
|
||||
};
|
||||
let u = u32_ty(fb)?;
|
||||
let ut = vec(fb, u, lanes)?;
|
||||
let bits = fb.convert(ConvOp::Bitcast, x, ut)?;
|
||||
let abs = u32s(fb, lanes, 0x7FFF_FFFF)?;
|
||||
let mag = fb.binary(BinOp::BitwiseAnd, bits, abs)?;
|
||||
let inf = u32s(fb, lanes, 0x7F80_0000)?;
|
||||
let nan = fb.binary(BinOp::UGreaterThan, mag, inf)?;
|
||||
let f = f32_ty(fb)?;
|
||||
let canonical = splat(fb, f, lanes, u64::from(QUIET_NAN))?;
|
||||
let halves = match class {
|
||||
NanClass::Slot(index) => {
|
||||
let Some(c) = texel_format_const(cx, index) else {
|
||||
return Err(cx.fail(format!("texture slot {index} has no texel class")));
|
||||
};
|
||||
let word = fb.module().const_value(c)?;
|
||||
let mask = u32s(fb, 1, BicubicTexels::HALF | TexelFormat::PACKED_MASK)?;
|
||||
let half = u32s(fb, 1, BicubicTexels::HALF)?;
|
||||
let family = fb.binary(BinOp::BitwiseAnd, word, mask)?;
|
||||
let halves = fb.binary(BinOp::IEqual, family, half)?;
|
||||
// A class whose conversion is not measured keeps the device's decode, as before.
|
||||
let other = u32s(fb, 1, TexelFormat::OTHER.0)?;
|
||||
let other = fb.binary(BinOp::IEqual, word, other)?;
|
||||
Some(fb.binary(BinOp::LogicalOr, halves, other)?)
|
||||
}
|
||||
NanClass::Heap(handle) => Some(heap_half_format(cx, fb, handle)?),
|
||||
NanClass::Never => None,
|
||||
};
|
||||
let own = match (halves, one) {
|
||||
(None, _) => None,
|
||||
(Some(h), None) => Some(h),
|
||||
(Some(h), Some(o)) => Some(fb.binary(BinOp::LogicalAnd, h, o)?),
|
||||
};
|
||||
let kept = match own {
|
||||
None => canonical,
|
||||
Some(own) => {
|
||||
let cond = match lanes {
|
||||
1 => own,
|
||||
n => {
|
||||
let b = fb.module().ty(SType::Bool)?;
|
||||
let ty = vec(fb, b, n)?;
|
||||
fb.composite_construct(ty, &vec![own; usize::from(n)])?
|
||||
}
|
||||
};
|
||||
fb.select(cond, x, canonical)?
|
||||
}
|
||||
};
|
||||
fb.select(nan, kept, held)
|
||||
}
|
||||
|
||||
/// The words [`heap_half_format`] emits, at most: the field's shift and mask, and per half-float
|
||||
/// class its constant, comparison and union.
|
||||
pub(crate) fn heap_half_words() -> u32 {
|
||||
let n = crate::metal::texel_format::heap_half_indices().len() as u32;
|
||||
20 + 14 * n
|
||||
}
|
||||
|
||||
/// `texel` (`f32` lanes of `form`), written through a heap handle whose class is a half-float
|
||||
/// format's where `is_half` ([`heap_half_format`]), as [`half_write`] writes it by class
|
||||
/// `class` there; as it is elsewhere.
|
||||
fn heap_halves(
|
||||
fb: &mut FunctionBuilder<'_>,
|
||||
(is_half, class): (SValue, StorageImageClass),
|
||||
form: TexelForm,
|
||||
texel: SValue,
|
||||
) -> BResult<SValue> {
|
||||
let written = half_write(fb, class, form, texel)?;
|
||||
let cond = match form.lanes {
|
||||
1 => is_half,
|
||||
n => {
|
||||
let b = fb.module().ty(SType::Bool)?;
|
||||
let ty = vec(fb, b, n)?;
|
||||
fb.composite_construct(ty, &vec![is_half; usize::from(n)])?
|
||||
}
|
||||
};
|
||||
fb.select(cond, written, texel)
|
||||
}
|
||||
|
||||
/// The estimated words of a write's conversion by storage class `class` on four lanes: an 8-bit
|
||||
/// sRGB format's codes ([`srgb_codes`]), a half-float image's NaN ([`half_write`]), a half-float
|
||||
/// texel's bits ([`half_bits`]), an `RGB9E5Float` word ([`shared_exponent_word`]), or a YCbCr
|
||||
/// sRGB format's codes ([`srgb_codes`]), a half-float texel's bits ([`half_bits`]), an `RGB9E5Float` word ([`shared_exponent_word`]), or a YCbCr
|
||||
/// texel's bits and mark ([`ycbcr_write_texel`]), none for the other classes' swizzles, which the
|
||||
/// write's base estimate covers.
|
||||
pub(crate) fn class_write_words(class: StorageImageClass) -> u32 {
|
||||
use crate::lower::arith::color_write;
|
||||
match class {
|
||||
StorageImageClass::HalfQuietNan | StorageImageClass::SmallFloatQuietNan => QUIET_NAN_WORDS,
|
||||
StorageImageClass::YCbCrWrite => YCBCR_WRITE_WORDS,
|
||||
StorageImageClass::SrgbEncode | StorageImageClass::SrgbEncodeBgra => SRGB_WRITE_WORDS,
|
||||
StorageImageClass::SharedExponentBits => SHARED_EXPONENT_WORDS,
|
||||
@@ -3296,12 +3038,7 @@ fn read(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult<
|
||||
}
|
||||
(_, float) => float,
|
||||
};
|
||||
let held = from_image(cx, fb, &decl, r.texel, texel, (half, float))?;
|
||||
// Under the NaN switch, Metal's NaN: a read reads one texel.
|
||||
match r.half_nans {
|
||||
Some(class) => metal_texel_nans(cx, fb, (class, None), texel, held)?,
|
||||
None => held,
|
||||
}
|
||||
from_image(cx, fb, &decl, r.texel, texel, (half, float))?
|
||||
}
|
||||
};
|
||||
// A swizzled texture's swizzle at a storage slot, on the converted texel.
|
||||
@@ -3604,7 +3341,8 @@ fn heap_twin(
|
||||
Ok((is_bits, img))
|
||||
}
|
||||
|
||||
/// The words [`heap_twin`]'s class test emits, at most, as [`heap_half_words`] counts its own.
|
||||
/// The words [`heap_twin`]'s class test emits, at most: the field's shift and mask, and per
|
||||
/// member class the twin holds its constant, comparison and union.
|
||||
pub(crate) fn heap_bits_words() -> u32 {
|
||||
let n = crate::metal::texel_format::heap_half_bits_indices().len() as u32;
|
||||
20 + 14 * n
|
||||
@@ -3711,27 +3449,6 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul
|
||||
(true, ImageRef::Heap { handle, .. }) => heap_alpha_in_red(cx, fb, handle, texel, false)?,
|
||||
_ => texel,
|
||||
};
|
||||
// A `float` through a heap handle, rounded where the handle's class is a half-float
|
||||
// format's.
|
||||
let texel = match (w.heap_half, w.image) {
|
||||
(Some(class), ImageRef::Heap { handle, .. }) => {
|
||||
let is_half = heap_half_format(cx, fb, handle)?;
|
||||
heap_halves(fb, (is_half, class), w.texel, texel)?
|
||||
}
|
||||
_ => texel,
|
||||
};
|
||||
// And its NaNs quieted where the handle's class is a small float's.
|
||||
let texel = match (w.heap_small_floats, w.image) {
|
||||
(true, ImageRef::Heap { handle, .. }) => {
|
||||
let is_small = heap_small_float_format(cx, fb, handle)?;
|
||||
let class = StorageImageClass::SmallFloatQuietNan;
|
||||
heap_halves(fb, (is_small, class), w.texel, texel)?
|
||||
}
|
||||
_ => texel,
|
||||
};
|
||||
// A `half` texel's NaN, as Metal stores it in the texture's channels.
|
||||
let kept = half_kept(cx, fb, w.half_nans, &w.image)?;
|
||||
let texel = half_nan_texel(fb, (w.half_nans, kept), w.texel, texel)?;
|
||||
// A half-float member's bits through the group's unsigned integer twin, where the handle's
|
||||
// class names one: its image is the float element's, viewed through its integer alias.
|
||||
let twin = match (w.heap_bits, w.image) {
|
||||
@@ -3908,24 +3625,6 @@ fn slice<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, s: &Slice) -> BR
|
||||
let dims = coord_len(&decl);
|
||||
let s = *s;
|
||||
let mem = texel_memory(cx, fb, &s.image)?;
|
||||
// A `float` slice through a heap handle rounds where the handle's class is a half-float
|
||||
// format's: the class is read once, outside the loop.
|
||||
let is_half = match (s.heap_half, s.image) {
|
||||
(Some(class), ImageRef::Heap { handle, .. }) => {
|
||||
Some((heap_half_format(cx, fb, handle)?, class))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
// And whether its NaNs are quieted, a small float's class: read once too.
|
||||
let is_small = match (s.heap_small_floats, s.image) {
|
||||
(true, ImageRef::Heap { handle, .. }) => Some((
|
||||
heap_small_float_format(cx, fb, handle)?,
|
||||
StorageImageClass::SmallFloatQuietNan,
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
// Whether a `half` element keeps its half, read once, outside the loop.
|
||||
let kept = half_kept(cx, fb, s.half_nans, &s.image)?;
|
||||
// Whether the handle names a member the unsigned integer twin holds, and the twin's image,
|
||||
// read once, outside the loop.
|
||||
let twin = match (s.heap_bits, s.image) {
|
||||
@@ -3969,15 +3668,7 @@ fn slice<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, s: &Slice) -> BR
|
||||
}),
|
||||
None => None,
|
||||
};
|
||||
let texel = match is_half {
|
||||
Some(half) => heap_halves(fb, half, form, texel)?,
|
||||
None => texel,
|
||||
};
|
||||
let texel = match is_small {
|
||||
Some(small) => heap_halves(fb, small, form, texel)?,
|
||||
None => texel,
|
||||
};
|
||||
(half_nan_texel(fb, (s.half_nans, kept), form, texel)?, twin)
|
||||
(texel, twin)
|
||||
}
|
||||
};
|
||||
let ty = vec(fb, u, dims)?;
|
||||
|
||||
@@ -136,11 +136,11 @@ pub use atomic::TexAtomic;
|
||||
pub(crate) use emit::{
|
||||
constant_lanes, constant_lanes_by, dispatch, extended_table, float_class, half_by_class,
|
||||
half_class, heap_element, heap_float_class, heap_half_class, heap_raw_form, heap_raw_image,
|
||||
live_or_zero, metal_texel_nans, reinterpret, resident_access, rgb9e5_word, slot_image,
|
||||
sparse_spec, srgb_filtered_texel, srgb_raw_gather, srgb_raw_tap, srgb_raw_texel,
|
||||
swizzled_float, swizzled_gather, swizzled_held, texel_format_const, tile_map, tiled_word,
|
||||
with_word, HalfClass, NullLeaf, TileLevel, RGB9E5_WORDS, SRGB_FILTERED_WORDS, SRGB_RAW_WORDS,
|
||||
SRGB_TAP_WORDS, SRGB_TEXEL,
|
||||
live_or_zero, reinterpret, resident_access, rgb9e5_word, slot_image, sparse_spec,
|
||||
srgb_filtered_texel, srgb_raw_gather, srgb_raw_tap, srgb_raw_texel, swizzled_float,
|
||||
swizzled_gather, swizzled_held, texel_format_const, tile_map, tiled_word, with_word, HalfClass,
|
||||
NullLeaf, TileLevel, RGB9E5_WORDS, SRGB_FILTERED_WORDS, SRGB_RAW_WORDS, SRGB_TAP_WORDS,
|
||||
SRGB_TEXEL,
|
||||
};
|
||||
pub use emit::{emit, held_texel, to_image};
|
||||
pub(crate) use slot::depth_comparison;
|
||||
@@ -320,9 +320,6 @@ pub struct Read {
|
||||
/// A `float` texel of the slot converts by the bound format's class (`float_texel`): its
|
||||
/// code recovered from the device's value and divided exactly.
|
||||
pub float_texel: bool,
|
||||
/// Where the NaN switch asks for Metal's NaN, how the read's `half` texel answers a NaN
|
||||
/// texel ([`texel_nans_class`]): by the class of the bound texture it names.
|
||||
pub half_nans: Option<NanClass>,
|
||||
/// The read, of a slot's color texture on a profile whose sparse textures are sparse images
|
||||
/// (it enables `shaderResourceResidency`), sets the lanes Metal reads as constants (a channel
|
||||
/// the format lacks, through the swizzle) after it, from the slot's `ConstantLanes`
|
||||
@@ -393,9 +390,8 @@ fn read_words(r: &Read) -> u32 {
|
||||
r.texel.read_words()
|
||||
};
|
||||
let declared = if r.declared.is_some() { 16 } else { 0 };
|
||||
let nans = r.half_nans.map_or(0, NanClass::words);
|
||||
let siblings: u32 = r.heap_cross.iter().map(|x| read_words(x) + 24).sum();
|
||||
own + declared + nans + siblings
|
||||
own + declared + siblings
|
||||
}
|
||||
|
||||
/// A Metal 4.1 `read(sampler s, ...)` through a constexpr clamp-to-edge sampler (MSL 4.1
|
||||
@@ -430,16 +426,8 @@ pub struct Write {
|
||||
/// raw texel ([`extended_range::encode`](crate::lower::arith::extended_range::encode)).
|
||||
pub extended: Option<crate::metal::format::ExtendedRange>,
|
||||
/// The slot's storage class ([`storage_class`]): a converting one moves or encodes the
|
||||
/// written channels (`RotateArgb`'s rotation, `SrgbEncode`'s codes, `HalfQuietNan`'s NaN).
|
||||
/// written channels (`RotateArgb`'s rotation, `SrgbEncode`'s codes).
|
||||
pub class: StorageImageClass,
|
||||
/// A `float` written through a heap handle on a device not measured to store its NaN in a
|
||||
/// half-float texture as Metal does ([`heap_write_class`]): the class (`HalfQuietNan`) the
|
||||
/// write takes where the handle's texel class is a half-float format's (`emit::heap_halves`).
|
||||
pub heap_half: Option<StorageImageClass>,
|
||||
/// A `float` written through a heap handle: its NaN lanes are quieted where the handle's
|
||||
/// texel class is a small float's (`StorageImageClass::SmallFloatQuietNan`,
|
||||
/// `emit::heap_small_float_format`).
|
||||
pub heap_small_floats: bool,
|
||||
/// A `float` or `half` texel written through a heap handle stores its alpha in the image's
|
||||
/// red where the handle's class index is `A8Unorm`'s, on a device that holds such a texture's
|
||||
/// alpha in red ([`heap_alpha_in_red`]).
|
||||
@@ -448,8 +436,6 @@ pub struct Write {
|
||||
/// texture's swizzle on its held value, before converting it, under the slot's
|
||||
/// `TextureSwizzle` specialization (`emit::unswizzled`).
|
||||
pub swizzle: bool,
|
||||
/// How a `half` texel's NaN is written ([`half_nans`]).
|
||||
pub half_nans: HalfNans,
|
||||
/// The slot's variant binds a texture of another numeric class
|
||||
/// (`LoweringInputs::cross_class`): `texel` is that class's own form
|
||||
/// ([`native_write_form`]), into which the write first turns the declared lanes
|
||||
@@ -500,37 +486,6 @@ impl IntRange {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a `half` texel's write stores a NaN as Metal does ([`half_nans`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum HalfNans {
|
||||
/// Not a `half` texel's write, or one to channels that hold no NaN: the value as held.
|
||||
Held,
|
||||
/// The texture's channels are 16-bit floats: the half widened, its NaN the device's
|
||||
/// conversion of the widening (the half's bits under `DriverDeviation::MetalHalfTexelWrites`).
|
||||
Kept,
|
||||
/// The texture's channels are other floats: every NaN lane `0x7fc00000`.
|
||||
Canonical,
|
||||
/// A heap element: [`HalfNans::Kept`] where its handle's texel class is a half-float
|
||||
/// format's, else [`HalfNans::Canonical`].
|
||||
HeapClass,
|
||||
/// A texture slot whose storage choice declares no format: [`HalfNans::Kept`] where its
|
||||
/// `PushField::TextureHalfChannels` is 1, else [`HalfNans::Canonical`].
|
||||
SlotWord(SlotRef),
|
||||
}
|
||||
|
||||
impl HalfNans {
|
||||
/// The words of the write's NaN handling: the test and select of `emit::quiet_nans`, and for a
|
||||
/// runtime choice its class test or word load and select.
|
||||
pub(crate) fn words(self) -> u32 {
|
||||
match self {
|
||||
HalfNans::Held | HalfNans::Kept => 0,
|
||||
HalfNans::Canonical => 24,
|
||||
HalfNans::HeapClass => 24 + 16 + emit::heap_half_words(),
|
||||
HalfNans::SlotWord(_) => 24 + 32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a `get_*` query reads.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum QueryKind {
|
||||
@@ -888,17 +843,11 @@ impl TextureStrategy {
|
||||
0
|
||||
}
|
||||
+ emit::class_write_words(w.class)
|
||||
+ w.heap_half.map_or(0, heap_half_write_words)
|
||||
+ match w.heap_small_floats {
|
||||
true => heap_half_write_words(StorageImageClass::SmallFloatQuietNan),
|
||||
false => 0,
|
||||
}
|
||||
+ if w.heap_alpha_red {
|
||||
emit::HEAP_ALPHA_IN_RED_WORDS
|
||||
} else {
|
||||
0
|
||||
}
|
||||
+ w.half_nans.words()
|
||||
+ if w.cross.is_some() { 48 } else { 0 }
|
||||
+ w.saturate.words()
|
||||
+ if w.heap_bits {
|
||||
@@ -1441,13 +1390,6 @@ fn declare_heap_classes(mb: &mut ModuleBuilder) -> BResult<GlobalId> {
|
||||
mb.plain_global(crate::spirv::ir::StorageClass::Private, arr, Some(init))
|
||||
}
|
||||
|
||||
/// The words a heap texture's `float` write adds where its handle's class may be a half-float
|
||||
/// format's, written by class `class`, at most: the test of the class index, the class's write, and
|
||||
/// the choice between it and the texel as computed.
|
||||
pub(crate) fn heap_half_write_words(class: StorageImageClass) -> u32 {
|
||||
emit::heap_half_words() + emit::class_write_words(class) + 32
|
||||
}
|
||||
|
||||
/// The words a heap texture's `half` or `float` write adds where it stores a half-float member's
|
||||
/// bits through the unsigned integer twin, at most: the test of the class index, the bits, the
|
||||
/// twin's access chain and load, and the branch between the two writes.
|
||||
@@ -1737,75 +1679,6 @@ pub(crate) fn half_texel_nans(
|
||||
}
|
||||
}
|
||||
|
||||
/// How a `half` read, sample or gather of `image` (shape `shape`), which reads one texel where
|
||||
/// `one` says, answers a NaN texel where the NaN switch asks for Metal's NaN
|
||||
/// (`NanMinMaxPolicy::Exact`, the profile's `TexelNanRoute::Metal`, on every device: whatever
|
||||
/// NaN the device's arithmetic answers, the texel's is the image's decode): by Metal's rule, a NaN
|
||||
/// texel read, sampled or gathered one texel at a time from a texture of
|
||||
/// 16-bit float channels is its own (the device's decode, which a device that widens a half
|
||||
/// texel exactly decodes to its bits), and every other NaN `0x7e00`. The class of the texture
|
||||
/// bound says which: a slot's `TexelFormat` class, which the binder pushes as data
|
||||
/// ([`texel_format_spec`]); a heap element's, its handle's class index; a depth texture's never; an
|
||||
/// access that never reads one texel needs none ([`NanClass::Never`]). `None` where the switch is
|
||||
/// off, or where nothing tells the class (a heap's texture buffer, whose handle carries none: its
|
||||
/// NaN stays the device's decode, noted by [`half_texel_nans`]).
|
||||
pub(crate) fn texel_nans_class(
|
||||
cx: &mut SelectCx<'_>,
|
||||
image: ImageRef,
|
||||
shape: ImageShape,
|
||||
one: OneTexel,
|
||||
) -> Result<Option<NanClass>, Error> {
|
||||
use crate::device::profile::TexelNanRoute;
|
||||
if cx.profile.fields().texel_nans != TexelNanRoute::Metal {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(match image {
|
||||
_ if shape.depth || one == OneTexel::Never => NanClass::Never,
|
||||
ImageRef::Slot(_) => {
|
||||
texel_format_spec(cx, image)?;
|
||||
let ImageRef::Slot(index) = image else {
|
||||
return Err(cx.invariant("a slot's class of a heap element"));
|
||||
};
|
||||
NanClass::Slot(index)
|
||||
}
|
||||
ImageRef::Heap { .. } if shape.dim == ImageDim::Buffer => return Ok(None),
|
||||
ImageRef::Heap { handle, .. } => {
|
||||
cx.families.access.heap_class_index = true;
|
||||
NanClass::Heap(handle)
|
||||
}
|
||||
}))
|
||||
}
|
||||
|
||||
/// How a `half` texel access tells whether the texture bound holds 16-bit float channels, whose
|
||||
/// NaN texel Metal hands back as its own bits where the access reads one texel
|
||||
/// ([`texel_nans_class`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum NanClass {
|
||||
/// Slot `index`'s `TexelFormat` class (`RuntimeFact::TexelFormat`, read as data): the
|
||||
/// half-float family's without a packed field (`metal::texel_format::half_channels`), or
|
||||
/// `TexelFormat::OTHER`, whose conversion is not measured: the device's decode, as before.
|
||||
Slot(u32),
|
||||
/// The class index heap handle `handle` carries (`emit::heap_half_format`).
|
||||
Heap(ValueId),
|
||||
/// A depth texture: never 16-bit float channels, so every NaN is `0x7e00`.
|
||||
Never,
|
||||
}
|
||||
|
||||
impl NanClass {
|
||||
/// The estimated words of an access's answer of Metal's NaN: the texel's NaN test (the bitcast,
|
||||
/// the mask, the compare and their constants), the canonical NaN, the class test (a slot's mask
|
||||
/// and compare, a heap handle's [`emit::heap_half_words`]), a runtime sampler's filter test,
|
||||
/// and the two selects.
|
||||
pub(crate) fn words(self) -> u32 {
|
||||
let class = match self {
|
||||
NanClass::Slot(_) => 40,
|
||||
NanClass::Heap(_) => emit::heap_half_words(),
|
||||
NanClass::Never => 0,
|
||||
};
|
||||
64 + class + 48
|
||||
}
|
||||
}
|
||||
|
||||
/// A read, gather, or sample of `image`, of shape `shape`, with a `float` result that may read
|
||||
/// one texel (`one` not [`OneTexel::Never`]): on a color texture slot, a texture buffer's included,
|
||||
/// on a profile without Metal's own sampler (`VkProperty::MetalSampler`, whose device value is
|
||||
@@ -2466,174 +2339,156 @@ pub fn routine_words(
|
||||
/// no other flag is carried, the masks of the heap handles.
|
||||
pub const HEAP_CLASS_CENSUS: &str = "sampler.heap.texel_class";
|
||||
|
||||
/// The class a `float` written through a heap handle takes where the handle's texel class is a
|
||||
/// half-float format's (`emit::heap_halves`): the class a slot bound in such a format takes
|
||||
/// (`metal::format::half_write_class`), `None` where that is `Identity` (the device stores the
|
||||
/// write's NaN as Metal does).
|
||||
pub(crate) fn heap_write_class(cx: &SelectCx<'_>) -> Option<StorageImageClass> {
|
||||
match crate::metal::format::half_write_class(cx.profile) {
|
||||
StorageImageClass::Identity => None,
|
||||
class => Some(class),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a `float` write to texture `image` (a slot's storage class `class`; a heap write's class
|
||||
/// where its handle's is a half-float format's, `heap_half`) relies on or records where it may
|
||||
/// reach a half-float image, whose rounding of each channel to `half` the device makes (Metal
|
||||
/// rounds toward zero, a finite value past 65504 to 65504): Metal's where the profile takes
|
||||
/// `DriverDeviation::MetalHalfStorageWrites` (the module requires its property), else the device's
|
||||
/// (`PrecisionNote::DeviceColorConversion`), but for a half-float member a heap's unsigned integer
|
||||
/// twin holds (`heap_bits`), whose bits the shader writes. A write the shader quiets stores the NaN
|
||||
/// `0x7fc00000`, Metal's `0x7e00` where the profile takes `DriverDeviation::MetalFloatStorageNans`
|
||||
/// (the module requires its property), else the device's encoding of it
|
||||
/// (`PrecisionNote::DeviceNanEncoding`); one left to the device's conversion whole, a heap write's
|
||||
/// or a slot's whose choice declares a half-float format, requires
|
||||
/// `VkProperty::MetalHalfStorageNans` too.
|
||||
/// What a `float` write to texture `image` (of storage class `class`) relies on or records where it
|
||||
/// may reach a half-float image ([`may_store_half`]), which the device converts whole. Its rounding of each channel to
|
||||
/// `half` (Metal rounds toward zero, a finite value past 65504 to 65504) is Metal's where the
|
||||
/// profile takes `DriverDeviation::MetalHalfStorageWrites` (the module requires its property), else
|
||||
/// the device's (`PrecisionNote::DeviceColorConversion`), but for a half-float member a heap's
|
||||
/// unsigned integer twin holds (`heap_bits`), whose bits the shader writes. Its NaN is Metal's
|
||||
/// `0x7e00` where the profile takes `DriverDeviation::MetalHalfStorageNans` (the module requires its
|
||||
/// property), else the device's encoding of it (`PrecisionNote::DeviceNanEncoding`), but for a
|
||||
/// member the twin holds, which stores Metal's (the runtime announces the note where the heap holds
|
||||
/// a half-float texture the twin does not: `RuntimeFact::HeapHalfTexelWrites`). A write that may
|
||||
/// reach a packed small float image, a heap write's or a slot's whose choice declares such a format
|
||||
/// or none ([`small_float_storage`]), stores its NaN as the device converts it too: Metal stores
|
||||
/// every NaN there as its canonical one, and RADV and NVIDIA keep another NaN's payload bits.
|
||||
pub(super) fn half_storage_facts(
|
||||
cx: &mut SelectCx<'_>,
|
||||
image: ImageRef,
|
||||
class: StorageImageClass,
|
||||
(heap_half, heap_bits): (Option<StorageImageClass>, bool),
|
||||
heap_bits: bool,
|
||||
) -> Result<(), Error> {
|
||||
use crate::device::requirements::VkProperty;
|
||||
let applied = match image {
|
||||
ImageRef::Heap { .. } => heap_half.unwrap_or(StorageImageClass::Identity),
|
||||
ImageRef::Slot(_) => class,
|
||||
};
|
||||
let mut relied = Vec::new();
|
||||
let rounded = |cx: &mut SelectCx<'_>, relied: &mut Vec<VkProperty>| {
|
||||
let measured = cx
|
||||
if class == StorageImageClass::Identity && may_store_half(cx, image)? {
|
||||
let rounds = cx
|
||||
.profile
|
||||
.takes_driver_deviation(DriverDeviation::MetalHalfStorageWrites);
|
||||
match (heap_bits, measured) {
|
||||
match (heap_bits, rounds) {
|
||||
(true, _) => {}
|
||||
(false, true) => relied.push(VkProperty::MetalHalfStorageWrites),
|
||||
(false, true) => {
|
||||
cx.families
|
||||
.texture
|
||||
.storage_properties
|
||||
.insert(VkProperty::MetalHalfStorageWrites);
|
||||
}
|
||||
(false, false) => {
|
||||
cx.precision.insert(PrecisionNote::DeviceColorConversion);
|
||||
}
|
||||
}
|
||||
};
|
||||
match applied {
|
||||
StorageImageClass::HalfQuietNan => {
|
||||
rounded(cx, &mut relied);
|
||||
if cx
|
||||
.profile
|
||||
.takes_driver_deviation(DriverDeviation::MetalFloatStorageNans)
|
||||
{
|
||||
relied.push(VkProperty::MetalFloatStorageNans);
|
||||
} else if heap_bits {
|
||||
// A member the twin holds stores Metal's `0x7e00`; the runtime announces the
|
||||
// note where the heap holds a half-float texture the twin does not.
|
||||
heap_half_texel_writes(cx, false);
|
||||
} else {
|
||||
cx.precision.insert(PrecisionNote::DeviceNanEncoding);
|
||||
}
|
||||
if cx
|
||||
.profile
|
||||
.takes_driver_deviation(DriverDeviation::MetalHalfStorageNans)
|
||||
{
|
||||
cx.families
|
||||
.texture
|
||||
.storage_properties
|
||||
.insert(VkProperty::MetalHalfStorageNans);
|
||||
} else if heap_bits {
|
||||
heap_half_texel_writes(cx, false);
|
||||
} else {
|
||||
cx.precision.insert(PrecisionNote::DeviceNanEncoding);
|
||||
}
|
||||
StorageImageClass::Identity if declared_half(cx, image)? => {
|
||||
rounded(cx, &mut relied);
|
||||
relied.push(VkProperty::MetalHalfStorageNans);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
cx.families.texture.storage_properties.extend(relied);
|
||||
if small_float_storage(cx, image)? {
|
||||
cx.precision.insert(PrecisionNote::DeviceNanEncoding);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// How a `half` texel's write to texture `image` stores a NaN as Metal does, and what it records.
|
||||
/// Metal stores a written half's NaN as the half's own bits in a 16-bit float channel and as its
|
||||
/// conversion of the canonical `0x7fc00000` in any other (the M3 Max under macOS 26.7, measured by
|
||||
/// the consumer; the M4 under macOS 27.0.1: every NaN class, both signs, `write`
|
||||
/// and `read_write`, `Shared` and `Private`): a 16-bit float channel takes the half widened
|
||||
/// ([`HalfNans::Kept`]), which a device of `DriverDeviation::MetalHalfTexelWrites` stores as its
|
||||
/// bits, and any other float channel every NaN as `0x7fc00000` ([`HalfNans::Canonical`]), which a
|
||||
/// 32-bit float channel stores as it is. The texture's format decides: a slot's declared format, or
|
||||
/// the class it writes by (`HalfQuietNan`: a 16-bit float format's); a heap
|
||||
/// element's handle class ([`HalfNans::HeapClass`]); a texture slot's word where its choice
|
||||
/// declares none ([`HalfNans::SlotWord`]). A normalized format's channel stores no NaN
|
||||
/// ([`HalfNans::Held`]).
|
||||
/// Whether a write to texture `image` may store into a packed small float format
|
||||
/// (`RG11B10Float`, `RGB9E5Float`'s alias excepted: its word is Metal's): a heap element, whose
|
||||
/// handle may name one, or a slot whose storage choice declares such a format or none.
|
||||
fn small_float_storage(cx: &SelectCx<'_>, image: ImageRef) -> Result<bool, Error> {
|
||||
use crate::vk::Format as F;
|
||||
let ImageRef::Slot(index) = image else {
|
||||
return Ok(true);
|
||||
};
|
||||
let slot = slot_of(cx, index)?.slot;
|
||||
Ok(cx
|
||||
.inputs
|
||||
.storage_images
|
||||
.get(&slot)
|
||||
.is_some_and(|c| matches!(c.vk_format, F::B10G11R11_UFLOAT_PACK32 | F::UNDEFINED)))
|
||||
}
|
||||
|
||||
/// What a `half` texel's write to texture `image` records of its NaN. Metal stores a written
|
||||
/// half's NaN as the half's own bits in a 16-bit float channel and as its conversion of the
|
||||
/// canonical `0x7fc00000` in any other (the M3 Max under macOS 26.7, measured by the consumer; the
|
||||
/// M4 under macOS 27.0.1: every NaN class, both signs, `write` and `read_write`, `Shared` and
|
||||
/// `Private`). The write stores the half widened, its NaN's payload in the significand's top bits,
|
||||
/// which the device converts: a 16-bit float channel's NaN is Metal's on a device of
|
||||
/// `DriverDeviation::MetalHalfTexelWrites` (the module requires its property), and every other
|
||||
/// float channel's, a 32-bit one's among them, is the device's.
|
||||
///
|
||||
/// The write records `PrecisionNote::DeviceNanEncoding` where the stored NaN stays the device's:
|
||||
/// a 16-bit float channel's, and a packed small float's (the device converting
|
||||
/// `0x7fc00000`), on a profile without `DriverDeviation::MetalHalfTexelWrites`, which states
|
||||
/// both; a heap element's likewise; a texel buffer declaring no format always (it has no word,
|
||||
/// so it keeps the half). A slot's word records nothing: the runtime announces the note at the
|
||||
/// bind of a 16-bit or packed small float texture there on such a profile
|
||||
/// (`RuntimeFact::StorageTextureHalfChannels`). A 32-bit float channel's `0x7fc00000` is
|
||||
/// stored as it is: no note. Nor is a slot's whose choice writes the half's bits through the
|
||||
/// texture's unsigned integer alias (`StorageImageClass::HalfBits`), which every device stores
|
||||
/// exactly; the binder chooses it for a half-float texture a slot only writes on such a profile, so
|
||||
/// that slot's word is not read.
|
||||
pub(super) fn half_nans(
|
||||
/// a 16-bit float channel's on a profile without `DriverDeviation::MetalHalfTexelWrites`, a 32-bit
|
||||
/// or packed small float channel's, a slot's whose choice declares no format, a texel buffer's
|
||||
/// declaring none, and a heap element's, which may be a 32-bit float texture's (where the group's
|
||||
/// unsigned integer twin holds its half-float members too, which states
|
||||
/// `RuntimeFact::HeapHalfTexelWrites`). A normalized or integer channel stores no NaN; nor does a
|
||||
/// slot whose choice writes the half's bits through the texture's unsigned integer alias
|
||||
/// (`StorageImageClass::HalfBits`), which every device stores exactly.
|
||||
pub(super) fn half_write_nans(
|
||||
cx: &mut SelectCx<'_>,
|
||||
image: ImageRef,
|
||||
(buffer, heap_bits): (bool, bool),
|
||||
) -> Result<HalfNans, Error> {
|
||||
heap_bits: bool,
|
||||
) -> Result<(), Error> {
|
||||
use crate::device::requirements::VkProperty;
|
||||
use crate::vk::NumericFormat as N;
|
||||
// Each form, and whether the device's conversion decides the NaN stored (`Device`), and where
|
||||
// a runtime choice lets the runtime narrow the note to the bind (`Bound`).
|
||||
// Whether the stored NaN is exact (`Exact`), a 16-bit float channel's (`Sixteen`, Metal's on
|
||||
// the measured deviation), or the device's (`Device`).
|
||||
#[derive(PartialEq)]
|
||||
enum Stored {
|
||||
Exact,
|
||||
Sixteen,
|
||||
Device,
|
||||
Bound,
|
||||
}
|
||||
let declared = |f: crate::vk::Format| -> (HalfNans, Stored) {
|
||||
let declared = |f: crate::vk::Format| -> Stored {
|
||||
let Some(b) = f.block() else {
|
||||
return (HalfNans::Held, Stored::Exact);
|
||||
return Stored::Device;
|
||||
};
|
||||
match (b.color, b.component_bits, b.packed_bits) {
|
||||
(Some(N::Sfloat), Some(16), None) => (HalfNans::Kept, Stored::Device),
|
||||
(Some(N::Sfloat), Some(32), None) => (HalfNans::Canonical, Stored::Exact),
|
||||
(Some(N::Sfloat | N::Ufloat), _, _) => (HalfNans::Canonical, Stored::Device),
|
||||
_ => (HalfNans::Held, Stored::Exact),
|
||||
(Some(N::Sfloat), Some(16), None) => Stored::Sixteen,
|
||||
(Some(N::Sfloat | N::Ufloat), _, _) => Stored::Device,
|
||||
_ => Stored::Exact,
|
||||
}
|
||||
};
|
||||
let (nans, stored) = match image {
|
||||
// A half-float member the group's unsigned integer twin holds stores the half's bits;
|
||||
// the runtime announces the note where the heap holds a texture it does not.
|
||||
ImageRef::Heap { .. } if heap_bits => (HalfNans::HeapClass, Stored::Bound),
|
||||
ImageRef::Heap { .. } => (HalfNans::HeapClass, Stored::Device),
|
||||
let stored = match image {
|
||||
ImageRef::Heap { .. } => {
|
||||
if heap_bits {
|
||||
heap_half_texel_writes(cx, true);
|
||||
}
|
||||
Stored::Device
|
||||
}
|
||||
ImageRef::Slot(index) => {
|
||||
let slot = slot_of(cx, index)?.slot;
|
||||
match cx.inputs.storage_images.get(&slot) {
|
||||
Some(c) => match c.class {
|
||||
StorageImageClass::HalfQuietNan => (HalfNans::Kept, Stored::Device),
|
||||
StorageImageClass::SmallFloatQuietNan => (HalfNans::Canonical, Stored::Device),
|
||||
// The half's own bits, written through the unsigned integer alias.
|
||||
StorageImageClass::HalfBits => (HalfNans::Kept, Stored::Exact),
|
||||
StorageImageClass::Identity if c.vk_format != crate::vk::Format::UNDEFINED => {
|
||||
declared(c.vk_format)
|
||||
}
|
||||
StorageImageClass::Identity if buffer => (HalfNans::Kept, Stored::Device),
|
||||
StorageImageClass::Identity => (HalfNans::SlotWord(slot), Stored::Bound),
|
||||
_ => (HalfNans::Held, Stored::Exact),
|
||||
StorageImageClass::HalfBits => Stored::Exact,
|
||||
StorageImageClass::Identity => declared(c.vk_format),
|
||||
_ => Stored::Exact,
|
||||
},
|
||||
None if buffer => (HalfNans::Kept, Stored::Device),
|
||||
None => (HalfNans::SlotWord(slot), Stored::Bound),
|
||||
None => Stored::Device,
|
||||
}
|
||||
}
|
||||
};
|
||||
let measured = cx
|
||||
.profile
|
||||
.takes_driver_deviation(DriverDeviation::MetalHalfTexelWrites);
|
||||
if stored != Stored::Exact && measured {
|
||||
cx.families
|
||||
.texture
|
||||
.storage_properties
|
||||
.insert(VkProperty::MetalHalfTexelWrites);
|
||||
} else if stored == Stored::Device {
|
||||
cx.precision.insert(PrecisionNote::DeviceNanEncoding);
|
||||
match stored {
|
||||
Stored::Sixteen if measured => {
|
||||
cx.families
|
||||
.texture
|
||||
.storage_properties
|
||||
.insert(VkProperty::MetalHalfTexelWrites);
|
||||
}
|
||||
Stored::Sixteen | Stored::Device => {
|
||||
cx.precision.insert(PrecisionNote::DeviceNanEncoding);
|
||||
}
|
||||
Stored::Exact => {}
|
||||
}
|
||||
match nans {
|
||||
HalfNans::HeapClass => cx.families.access.heap_class_index = true,
|
||||
HalfNans::SlotWord(_) => mark(cx, image, |u| u.half_channels = true),
|
||||
_ => {}
|
||||
}
|
||||
if heap_bits && !measured {
|
||||
heap_half_texel_writes(cx, true);
|
||||
}
|
||||
Ok(nans)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a `half` or `float` write (`texel`) to texture `image` of shape `shape` stores a
|
||||
@@ -2785,8 +2640,7 @@ pub(super) fn norm_storage_facts(
|
||||
/// small-float one (unmeasured). Kernel, vertex, object, mesh and tile functions write alike at
|
||||
/// every mode. The write is built under the default's rule alone, so: a write that may be such
|
||||
/// records the mode in `StageIo::texture_write_rounding`, for link to match against the pipeline's;
|
||||
/// under `NearestEven` one whose slot's storage choice declares such a format (or rounds as a
|
||||
/// half-float one: `HalfQuietNan`) is refused
|
||||
/// under `NearestEven` one whose slot's storage choice declares such a format is refused
|
||||
/// `NotImplemented(PrivateRenderState(TextureWriteRounding))`, and one whose bound texture
|
||||
/// decides (a slot or texture buffer whose choice declares no format; a heap handle) states
|
||||
/// `RuntimeFact::StorageTextureWriteRounding` or `RuntimeFact::HeapWriteRounding`, which the
|
||||
@@ -2822,14 +2676,6 @@ fn mode_rounded_write(
|
||||
match cx.inputs.storage_images.get(&slot) {
|
||||
None => Target::Slot(slot),
|
||||
Some(c) => match c.class {
|
||||
StorageImageClass::HalfQuietNan => Target::Declared {
|
||||
half: true,
|
||||
small: false,
|
||||
},
|
||||
StorageImageClass::SmallFloatQuietNan => Target::Declared {
|
||||
half: false,
|
||||
small: true,
|
||||
},
|
||||
StorageImageClass::Identity if c.vk_format == F::UNDEFINED => {
|
||||
Target::Slot(slot)
|
||||
}
|
||||
@@ -2883,8 +2729,9 @@ fn mode_rounded_write(
|
||||
}
|
||||
|
||||
/// Whether a write to `image` left to the device's conversion may store a half-float texel: a
|
||||
/// heap element's may, and a slot's whose storage choice declares a half-float format does.
|
||||
fn declared_half(cx: &SelectCx<'_>, image: ImageRef) -> Result<bool, Error> {
|
||||
/// heap element's may, and so does a slot's whose storage choice declares a half-float format or
|
||||
/// none (a formatless declaration views a half-float texture too).
|
||||
fn may_store_half(cx: &SelectCx<'_>, image: ImageRef) -> Result<bool, Error> {
|
||||
use crate::vk::Format as F;
|
||||
let ImageRef::Slot(index) = image else {
|
||||
return Ok(true);
|
||||
@@ -2893,15 +2740,14 @@ fn declared_half(cx: &SelectCx<'_>, image: ImageRef) -> Result<bool, Error> {
|
||||
Ok(cx.inputs.storage_images.get(&slot).is_some_and(|c| {
|
||||
matches!(
|
||||
c.vk_format,
|
||||
F::R16_SFLOAT | F::R16G16_SFLOAT | F::R16G16B16A16_SFLOAT
|
||||
F::R16_SFLOAT | F::R16G16_SFLOAT | F::R16G16B16A16_SFLOAT | F::UNDEFINED
|
||||
)
|
||||
}))
|
||||
}
|
||||
|
||||
/// The class of texture slot `image`'s storage choice, where its variant states one, else
|
||||
/// `Identity`: a write through a converting class moves or encodes the written channels
|
||||
/// (`RotateArgb`'s rotation, `SrgbEncode`'s codes, `HalfQuietNan`'s NaN). A heap element's is
|
||||
/// `Identity`.
|
||||
/// (`RotateArgb`'s rotation, `SrgbEncode`'s codes). A heap element's is `Identity`.
|
||||
pub(crate) fn storage_class(
|
||||
cx: &SelectCx<'_>,
|
||||
image: ImageRef,
|
||||
@@ -3434,10 +3280,18 @@ fn select_read_as(
|
||||
storage_class(cx, image)?,
|
||||
StorageImageClass::HalfBits | StorageImageClass::SharedExponentBits
|
||||
);
|
||||
// A `float` read of a half-float texel's own bits widens a NaN with its sign and payload, where
|
||||
// Metal reads every half NaN as `0x7fc00000`.
|
||||
if texel.conv == TexelConv::F32
|
||||
&& half_bits
|
||||
&& storage_class(cx, image)? == StorageImageClass::HalfBits
|
||||
{
|
||||
cx.precision.insert(PrecisionNote::DeviceNanEncoding);
|
||||
}
|
||||
let exact = raw || srgb_codes || half_bits;
|
||||
// An extended-range texel is decoded exactly to `f32`, which a `half` result rounds to
|
||||
// nearest even, as Metal answers. A read is one texel.
|
||||
let half_nans = if texel.conv == TexelConv::F16 && !exact && extended.is_none() {
|
||||
if texel.conv == TexelConv::F16 && !exact && extended.is_none() {
|
||||
half_texels(
|
||||
cx,
|
||||
image,
|
||||
@@ -3447,10 +3301,7 @@ fn select_read_as(
|
||||
m,
|
||||
)?;
|
||||
half_texel_nans(cx, image, shape, m)?;
|
||||
texel_nans_class(cx, image, shape, OneTexel::Always)?
|
||||
} else {
|
||||
None
|
||||
};
|
||||
}
|
||||
let float_texel = texel.conv == TexelConv::F32
|
||||
&& !exact
|
||||
&& extended.is_none()
|
||||
@@ -3530,7 +3381,6 @@ fn select_read_as(
|
||||
heap_raw,
|
||||
heap_alpha_red,
|
||||
float_texel,
|
||||
half_nans,
|
||||
constant_lanes,
|
||||
declared,
|
||||
heap_class: as_class,
|
||||
@@ -3695,15 +3545,6 @@ fn select_write(
|
||||
let extended = extended_range(cx, image)?;
|
||||
let class = storage_class(cx, image)?;
|
||||
mode_rounded_write(cx, image, texel, extended.is_some())?;
|
||||
// A `float` written through a heap handle may reach a half-float texture, whose format only
|
||||
// the handle's texel class tells: it rounds where the class is one.
|
||||
let heap_half = match image.heap() && texel.conv == TexelConv::F32 {
|
||||
true => heap_write_class(cx),
|
||||
false => None,
|
||||
};
|
||||
// Its NaNs quieted where the class is a small float's.
|
||||
let heap_small_floats = image.heap() && texel.conv == TexelConv::F32;
|
||||
cx.families.access.heap_class_index |= heap_half.is_some() || heap_small_floats;
|
||||
// Its alpha in red where the class is `A8Unorm`'s and the device holds such a texture so.
|
||||
let heap_alpha_red = heap_alpha_in_red(cx, image, shape, texel.conv);
|
||||
// A half-float member's bits through the group's unsigned integer twin, where the handle's
|
||||
@@ -3711,12 +3552,11 @@ fn select_write(
|
||||
let encoded = extended.is_some() || cross.is_some();
|
||||
let heap_bits = heap_bits(cx, image, shape, (texel.conv, encoded));
|
||||
if texel.conv == TexelConv::F32 {
|
||||
half_storage_facts(cx, image, class, (heap_half, heap_bits))?;
|
||||
half_storage_facts(cx, image, class, heap_bits)?;
|
||||
}
|
||||
if texel.conv == TexelConv::F16 && extended.is_none() {
|
||||
half_write_nans(cx, image, heap_bits)?;
|
||||
}
|
||||
let half_nans = match texel.conv == TexelConv::F16 && extended.is_none() {
|
||||
true => half_nans(cx, image, (shape.dim == ImageDim::Buffer, heap_bits))?,
|
||||
false => HalfNans::Held,
|
||||
};
|
||||
// A `half` texel's too, held widened: Metal stores its value by the same rule.
|
||||
if matches!(texel.conv, TexelConv::F32 | TexelConv::F16) && extended.is_none() {
|
||||
norm_storage_facts(cx, image, shape, texel)?;
|
||||
@@ -3744,11 +3584,8 @@ fn select_write(
|
||||
guard,
|
||||
extended,
|
||||
class,
|
||||
heap_half,
|
||||
heap_small_floats,
|
||||
heap_alpha_red,
|
||||
swizzle,
|
||||
half_nans,
|
||||
cross,
|
||||
saturate,
|
||||
heap_bits,
|
||||
|
||||
@@ -88,17 +88,8 @@ pub struct Slice {
|
||||
/// The cell loads are contained.
|
||||
pub contained: bool,
|
||||
/// The slot's storage class (`super::storage_class`): a converting one moves or encodes each
|
||||
/// texel's channels (`RotateArgb`'s rotation, `HalfQuietNan`'s NaN).
|
||||
/// texel's channels (`RotateArgb`'s rotation, `SrgbEncode`'s codes).
|
||||
pub class: StorageImageClass,
|
||||
/// A `float` slice through a heap handle on a device not measured to store its NaN in a
|
||||
/// half-float texture as Metal does: the class each texel takes where the handle's texel
|
||||
/// class is a half-float format's (`super::Write::heap_half`).
|
||||
pub heap_half: Option<StorageImageClass>,
|
||||
/// A `float` slice through a heap handle: each texel's NaN lanes quieted where the handle's
|
||||
/// texel class is a small float's (`super::Write::heap_small_floats`).
|
||||
pub heap_small_floats: bool,
|
||||
/// How a `half` element's NaN is written (`super::half_nans`).
|
||||
pub half_nans: super::HalfNans,
|
||||
/// Each texel of a half-float member stores its bits through the heap group's unsigned
|
||||
/// integer twin where the handle's class names one (`super::Write::heap_bits`).
|
||||
pub heap_bits: bool,
|
||||
@@ -117,14 +108,6 @@ impl Slice {
|
||||
+ if self.contained { 64 } else { 0 }
|
||||
+ if self.guard { 48 } else { 0 }
|
||||
+ super::emit::class_write_words(self.class)
|
||||
+ self.heap_half.map_or(0, |c| {
|
||||
super::HEAP_CLASS_WORDS + super::emit::class_write_words(c) + 32
|
||||
})
|
||||
+ match self.heap_small_floats {
|
||||
true => super::heap_half_write_words(StorageImageClass::SmallFloatQuietNan),
|
||||
false => 0,
|
||||
}
|
||||
+ self.half_nans.words()
|
||||
+ if self.heap_bits {
|
||||
super::heap_bits_write_words()
|
||||
} else {
|
||||
@@ -330,30 +313,20 @@ pub(super) fn select(
|
||||
};
|
||||
let guard = slot::write_guard(cx, false);
|
||||
let class = super::storage_class(cx, image)?;
|
||||
let heap_half = match image.heap() && conv == TexelConv::F32 {
|
||||
true => super::heap_write_class(cx),
|
||||
false => None,
|
||||
};
|
||||
let heap_small_floats = image.heap() && conv == TexelConv::F32;
|
||||
cx.families.access.heap_class_index |= heap_half.is_some() || heap_small_floats;
|
||||
// A half-float member's bits through the group's unsigned integer twin, where the handle's
|
||||
// class names one.
|
||||
let heap_bits = super::heap_bits(cx, image, t.image, (conv, false));
|
||||
if conv == TexelConv::F32 {
|
||||
super::half_storage_facts(cx, image, class, (heap_half, heap_bits))?;
|
||||
super::half_storage_facts(cx, image, class, heap_bits)?;
|
||||
}
|
||||
if matches!(conv, TexelConv::F32 | TexelConv::F16) {
|
||||
super::norm_storage_facts(cx, image, t.image, TexelForm { conv, lanes })?;
|
||||
}
|
||||
let half_nans = match conv == TexelConv::F16 {
|
||||
true => super::half_nans(cx, image, (false, heap_bits))?,
|
||||
false => super::HalfNans::Held,
|
||||
};
|
||||
// A `half` element to a slot of half bits, its NaNs as held: the cells' bits as they are.
|
||||
let bits = match conv == TexelConv::F16
|
||||
&& class == StorageImageClass::HalfBits
|
||||
&& !image.heap()
|
||||
&& matches!(half_nans, super::HalfNans::Held | super::HalfNans::Kept)
|
||||
if conv == TexelConv::F16 {
|
||||
super::half_write_nans(cx, image, heap_bits)?;
|
||||
}
|
||||
// A `half` element to a slot of half bits: the cells' bits as they are.
|
||||
let bits = match conv == TexelConv::F16 && class == StorageImageClass::HalfBits && !image.heap()
|
||||
{
|
||||
true => Some(Leaf {
|
||||
form: Form {
|
||||
@@ -396,9 +369,6 @@ pub(super) fn select(
|
||||
guard,
|
||||
contained: imageblock::contained(cx),
|
||||
class,
|
||||
heap_half,
|
||||
heap_small_floats,
|
||||
half_nans,
|
||||
heap_bits,
|
||||
cooperative,
|
||||
bits,
|
||||
|
||||
@@ -84,9 +84,6 @@ pub struct Uses {
|
||||
/// A cube's texels are fetched by face (an emulated linear cube sample): the slot is declared
|
||||
/// as the binder's 2D-array view of its faces.
|
||||
pub faces: bool,
|
||||
/// A `half` texel's write reads whether the bound texture's channels are 16-bit floats
|
||||
/// (`HalfNans::SlotWord`): the slot's storage choice declares no format.
|
||||
pub half_channels: bool,
|
||||
/// An integer texel's write reads the widths of the bound texture's channels
|
||||
/// (`IntRange::SlotWord`): the slot's storage choice declares no format.
|
||||
pub int_channels: bool,
|
||||
@@ -1125,10 +1122,6 @@ fn declare_slot(
|
||||
};
|
||||
let (format, class) = if storage {
|
||||
facts.push(RuntimeFact::StorageTextureFormat { slot: s.slot });
|
||||
if s.uses.half_channels {
|
||||
facts.push(RuntimeFact::StorageTextureHalfChannels { slot: s.slot });
|
||||
push.push(PushField::TextureHalfChannels(s.slot));
|
||||
}
|
||||
if s.uses.int_channels {
|
||||
facts.push(RuntimeFact::StorageTextureIntegerChannels { slot: s.slot });
|
||||
push.push(PushField::TextureIntegerChannels(s.slot));
|
||||
|
||||
@@ -2887,9 +2887,8 @@ pub fn storage_image_choice(
|
||||
/// `Identity` when the direct format supports the use's storage usage and the shader can declare
|
||||
/// it: with the format `Unknown` where the format serves the use without one
|
||||
/// ([`accessed_without_format`]; every such format of one numeric type shares one key, and
|
||||
/// `StorageImageChoice::numeric` keeps the type), else with its SPIR-V image format. A half-float
|
||||
/// format the use writes takes the class its writes need there instead (`half_storage_class`).
|
||||
/// Otherwise an alias view of a `MUTABLE_FORMAT` image (or the same bytes viewed as the alias
|
||||
/// `StorageImageChoice::numeric` keeps the type), else with its SPIR-V image format: the device
|
||||
/// converts every write, a half-float format's included. Otherwise an alias view of a `MUTABLE_FORMAT` image (or the same bytes viewed as the alias
|
||||
/// format, for a texture buffer): bgra8 through an rgba8 view and bgr10a2 through an rgb10a2 view
|
||||
/// (`A2R10G10B10` through `A2B10G10R10`, which NVIDIA and lavapipe store where they do not store
|
||||
/// the former) with `SwizzleBgra`, the 8-bit sRGB formats through their UNORM twin with
|
||||
@@ -3013,13 +3012,12 @@ fn held_storage_choice(
|
||||
// device that stores the format.
|
||||
let word = matches!(alias, Some((_, StorageImageClass::SharedExponentBits)));
|
||||
if storage(image) && declarable(image) && !rotated && !srgb_x && !word {
|
||||
let class = half_storage_class(pf, use_, profile);
|
||||
if !formatless(image) {
|
||||
return Ok(StorageImageChoice::new(image, class));
|
||||
return Ok(StorageImageChoice::new(image, StorageImageClass::Identity));
|
||||
}
|
||||
// The declaration names no format; the choice keeps the format's numeric type for a
|
||||
// function that depends on it.
|
||||
let mut choice = StorageImageChoice::new(F::UNDEFINED, class);
|
||||
let mut choice = StorageImageChoice::new(F::UNDEFINED, StorageImageClass::Identity);
|
||||
choice.numeric = crate::bind::neutral::numeric_type(image);
|
||||
return Ok(choice);
|
||||
}
|
||||
@@ -3196,29 +3194,6 @@ pub(crate) fn fetch_view_alias(format: vk::Format, profile: &DeviceProfile) -> O
|
||||
}
|
||||
}
|
||||
|
||||
/// The class of a storage choice that views `pf`'s own format for `use_`: for a half-float
|
||||
/// format (`R16Float`, `RG16Float`, `RGBA16Float`, `RGBX16Float`) the function writes,
|
||||
/// [`half_write_class`]. An `RG11B10Float` texture the function writes takes
|
||||
/// `SmallFloatQuietNan` on every device. Otherwise `Identity`: the device converts the write.
|
||||
pub(crate) fn half_storage_class(
|
||||
pf: PixelFormat,
|
||||
use_: StorageUse,
|
||||
profile: &DeviceProfile,
|
||||
) -> StorageImageClass {
|
||||
let half = matches!(
|
||||
pf,
|
||||
PixelFormat::R16Float
|
||||
| PixelFormat::RG16Float
|
||||
| PixelFormat::RGBA16Float
|
||||
| PixelFormat::RGBX16Float
|
||||
);
|
||||
match (half, pf == PixelFormat::RG11B10Float, use_.write) {
|
||||
(true, _, true) => half_write_class(profile),
|
||||
(_, true, true) => StorageImageClass::SmallFloatQuietNan,
|
||||
_ => StorageImageClass::Identity,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `pf`'s alpha is a 1-bit unorm channel (`crate::metal::texel_format::PackedTexels::Rgb5A1`:
|
||||
/// `A1BGR5Unorm`, `BGR5A1Unorm`), whose `float` write Metal stores as 1 only above one half, where
|
||||
/// a device measured to store every other normalized channel as Metal does rounds the half up
|
||||
@@ -3239,18 +3214,6 @@ pub(crate) fn one_bit_storage(use_: StorageUse, profile: &DeviceProfile) -> bool
|
||||
.any(|&pf| storage_choice(pf, use_, profile).is_ok())
|
||||
}
|
||||
|
||||
/// The class a `float` write to a half-float storage image takes on `profile`
|
||||
/// ([`half_storage_class`]): the device rounds each channel to `half` (Metal's rule, toward zero,
|
||||
/// where it takes `DriverDeviation::MetalHalfStorageWrites`), so `Identity` where it stores every
|
||||
/// NaN as Metal does too (`MetalHalfStorageNans`), else `HalfQuietNan`, which writes a NaN as
|
||||
/// `0x7fc00000`.
|
||||
pub(crate) fn half_write_class(profile: &DeviceProfile) -> StorageImageClass {
|
||||
match profile.takes_driver_deviation(DriverDeviation::MetalHalfStorageNans) {
|
||||
true => StorageImageClass::Identity,
|
||||
false => StorageImageClass::HalfQuietNan,
|
||||
}
|
||||
}
|
||||
|
||||
/// The SPIR-V `Image Format` a storage image of Vulkan format `format` is declared with (Vulkan
|
||||
/// spec "Compatibility Between SPIR-V Image Formats and Vulkan Formats"); `None` for formats only
|
||||
/// a formatless (`Unknown`) declaration can access. Crate-private: only the lowering and the
|
||||
|
||||
@@ -1928,23 +1928,18 @@ fn storage_choices_on_committed_profiles_are_declarable() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A half-float storage texture a function writes takes the class its `float` writes need, by
|
||||
/// what the committed profile's device is measured to store for a NaN (and lavapipe's probes):
|
||||
/// `Identity` on MoltenVK (Metal's every NaN), `HalfQuietNan` on every other profile, whose
|
||||
/// device's own conversion rounds each value; a read-only use, and another float format, stay
|
||||
/// `Identity`. On a profile not measured to store a written `half`'s NaN as its bits
|
||||
/// (`DriverDeviation::MetalHalfTexelWrites`), a written use takes the unsigned integer alias
|
||||
/// (`StorageImageClass::HalfBits`) wherever the alias serves it, an image of its own format alone
|
||||
/// the measured class.
|
||||
/// A half-float storage texture a function writes takes `Identity` on every committed profile: the
|
||||
/// device converts each value and NaN (`lower::texture`'s `half_storage_facts` records what it
|
||||
/// relies on or notes); so do a read-only use and another float format. On a profile not measured
|
||||
/// to store a written `half`'s NaN as its bits (`DriverDeviation::MetalHalfTexelWrites`), a written
|
||||
/// use takes the unsigned integer alias (`StorageImageClass::HalfBits`) wherever the alias serves
|
||||
/// it, an image of its own format alone `Identity`.
|
||||
#[test]
|
||||
fn half_float_storage_writes_take_their_measured_class() {
|
||||
let mut seen = BTreeSet::new();
|
||||
for (stem, dev) in committed_devices() {
|
||||
let p = dev.profile();
|
||||
let want = match stem.as_str() {
|
||||
"moltenvk-m3" => StorageImageClass::Identity,
|
||||
_ => StorageImageClass::HalfQuietNan,
|
||||
};
|
||||
let want = StorageImageClass::Identity;
|
||||
for pf in [
|
||||
PixelFormat::R16Float,
|
||||
PixelFormat::RG16Float,
|
||||
@@ -1986,59 +1981,7 @@ fn half_float_storage_writes_take_their_measured_class() {
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(seen.len(), 3, "{seen:?}");
|
||||
}
|
||||
|
||||
/// An `RG11B10Float` storage texture a function writes, or texture buffer, takes
|
||||
/// `SmallFloatQuietNan` on every committed profile that writes it (its NaNs quieted to the
|
||||
/// `0x7fc00000` every device measured stores as Metal's); a read-only use stays `Identity`; and a
|
||||
/// heap write tests the small floats' class, `RG11B10Float`'s and `RGB9E5Float`'s alone.
|
||||
#[test]
|
||||
fn storage_choices_quiet_small_float_writes() {
|
||||
let mut written = 0;
|
||||
for (stem, dev) in committed_devices() {
|
||||
let p = dev.profile();
|
||||
let pf = PixelFormat::RG11B10Float;
|
||||
for use_ in [
|
||||
StorageUse::READ_WRITE_TEXTURE,
|
||||
StorageUse::texture(false, true),
|
||||
StorageUse::texel_buffer(false, true),
|
||||
] {
|
||||
if let Ok(choice) = storage_choice(pf, use_, p) {
|
||||
assert_eq!(
|
||||
choice.class,
|
||||
StorageImageClass::SmallFloatQuietNan,
|
||||
"{stem} {use_:?}"
|
||||
);
|
||||
written += 1;
|
||||
}
|
||||
}
|
||||
if let Ok(read) = storage_choice(pf, StorageUse::texture(true, false), p) {
|
||||
assert_eq!(read.class, StorageImageClass::Identity, "{stem} read");
|
||||
}
|
||||
}
|
||||
assert!(written > 0, "no committed profile writes RG11B10Float");
|
||||
// The small floats' classes are `RG11B10Float`'s and `RGB9E5Float`'s, and no other format's.
|
||||
let classes = crate::metal::texel_format::heap_classes();
|
||||
let small: BTreeSet<u32> = crate::metal::texel_format::heap_small_float_indices()
|
||||
.into_iter()
|
||||
.map(|i| classes[i as usize])
|
||||
.collect();
|
||||
let class = |pf: PixelFormat| {
|
||||
crate::metal::texel_format::heap_class(pf, crate::metal::TextureSwizzleChannels::DEFAULT).0
|
||||
};
|
||||
let want: BTreeSet<u32> = [PixelFormat::RG11B10Float, PixelFormat::RGB9E5Float]
|
||||
.into_iter()
|
||||
.map(class)
|
||||
.collect();
|
||||
assert_eq!(small, want);
|
||||
for &pf in PixelFormat::ALL {
|
||||
assert_eq!(
|
||||
small.contains(&class(pf)),
|
||||
matches!(pf, PixelFormat::RG11B10Float | PixelFormat::RGB9E5Float),
|
||||
"{pf:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(seen.len(), 2, "{seen:?}");
|
||||
}
|
||||
|
||||
/// A `BGR10A2Unorm` storage texture or texture buffer is stored through its own `A2R10G10B10`
|
||||
|
||||
@@ -851,22 +851,6 @@ pub fn heap_numeric(pf: PixelFormat) -> Option<crate::pipeline::sym::SampledType
|
||||
}
|
||||
}
|
||||
|
||||
/// The indices in [`heap_classes`] of the half-float family without a packed field (`R16Float`,
|
||||
/// `RG16Float`, `RGBA16Float`, each its own channels, and `RGBX16Float`, `RGBA16Float`'s with
|
||||
/// three): the classes whose float write through a heap handle takes the half-float storage class,
|
||||
/// which a write tests by its handle's index alone.
|
||||
pub fn heap_half_indices() -> Vec<u32> {
|
||||
use crate::metal::bicubic::BicubicTexels;
|
||||
heap_classes()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, &c)| {
|
||||
c & (BicubicTexels::HALF | TexelFormat::PACKED_MASK) == BicubicTexels::HALF
|
||||
})
|
||||
.filter_map(|(i, _)| u32::try_from(i).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The half-float formats whose texture a heap's unsigned integer twin
|
||||
/// (`StorageFormatClass::HalfBits`) holds through its unsigned integer alias, in the own-view
|
||||
/// classes' order ([`heap_classes`]). `RGBX16Float` is not among them: no heap storage class
|
||||
@@ -900,20 +884,6 @@ pub fn heap_own_view_index(pf: PixelFormat, swizzle: TextureSwizzleChannels) ->
|
||||
reads_unswizzled(pf, swizzle).then_some(heap_layout().own_view + k)
|
||||
}
|
||||
|
||||
/// The indices in [`heap_classes`] of the small floats' class (`RG11B10Float`'s, which
|
||||
/// `RGB9E5Float` shares; a swizzled texture's is `OTHER`): the classes whose `float` write
|
||||
/// through a heap handle quiets its NaNs (`StorageImageClass::SmallFloatQuietNan`), which a write
|
||||
/// tests by its handle's index alone.
|
||||
pub fn heap_small_float_indices() -> Vec<u32> {
|
||||
let small = (PackedTexels::SmallFloat as u32) << TexelFormat::PACKED;
|
||||
heap_classes()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, &c)| c & TexelFormat::PACKED_MASK == small)
|
||||
.filter_map(|(i, _)| u32::try_from(i).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The index in [`heap_classes`] of `A8Unorm`'s class, which no other format's texture carries:
|
||||
/// a storage read or write through a heap handle carrying it converts the member's texels where
|
||||
/// the device holds such a texture's alpha in red (`metal::format::alpha_in_red`), which a heap's
|
||||
@@ -925,9 +895,7 @@ pub fn heap_alpha_in_red_index() -> u32 {
|
||||
}
|
||||
|
||||
/// Whether a texture of pixel format `pf` holds 16-bit float channels of its own: its class is
|
||||
/// the half-float family's without a packed field ([`heap_half_indices`]' classes), so a written
|
||||
/// `half` stores its NaN there as the half's own bits, and elsewhere as the conversion of
|
||||
/// `0x7fc00000` (`PushField::TextureHalfChannels`).
|
||||
/// the half-float family's without a packed field.
|
||||
pub fn half_channels(pf: PixelFormat) -> bool {
|
||||
use crate::metal::bicubic::BicubicTexels;
|
||||
texel_format(pf).0 & (BicubicTexels::HALF | TexelFormat::PACKED_MASK) == BicubicTexels::HALF
|
||||
@@ -1552,16 +1520,24 @@ mod tests {
|
||||
assert_ne!(heap_class_index(PixelFormat::A8Unorm, moved), a8);
|
||||
}
|
||||
|
||||
/// The half-float heap classes a float write tests by index are the unswizzled half-float
|
||||
/// formats' and no other format's: `RGBX16Float`'s too, `RGBA16Float`'s texels with three
|
||||
/// channels, whose writes take the half class as its twin's.
|
||||
/// The heap classes of the half-float family without a packed field are the unswizzled
|
||||
/// half-float formats' and no other format's: `RGBX16Float`'s too, `RGBA16Float`'s texels with
|
||||
/// three channels.
|
||||
///
|
||||
/// The own-view entries of `R16Float`, `RG16Float` and `RGBA16Float` are half classes too, and
|
||||
/// the twin's indices are exactly those formats' own: no other format's texture, swizzled or
|
||||
/// not, carries one, and none carries an own-view index.
|
||||
#[test]
|
||||
fn a_heap_write_finds_the_half_formats_by_index() {
|
||||
let half = heap_half_indices();
|
||||
use crate::metal::bicubic::BicubicTexels;
|
||||
let half: Vec<u32> = heap_classes()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, &c)| {
|
||||
c & (BicubicTexels::HALF | TexelFormat::PACKED_MASK) == BicubicTexels::HALF
|
||||
})
|
||||
.filter_map(|(i, _)| u32::try_from(i).ok())
|
||||
.collect();
|
||||
let wanted = [
|
||||
PixelFormat::R16Float,
|
||||
PixelFormat::RG16Float,
|
||||
|
||||
@@ -44,7 +44,6 @@ fn stage_module_bytes_are_little_endian_words() {
|
||||
strategies: StrategyCensus::default(),
|
||||
constant_blob: None,
|
||||
rounded_colors: Vec::new(),
|
||||
half_bit_colors: Vec::new(),
|
||||
own_pixel_textures: Vec::new(),
|
||||
snapshot_textures: Vec::new(),
|
||||
private_bytes: 0,
|
||||
@@ -95,7 +94,6 @@ fn a_stage_s_notes_under_a_specialization_are_its_held_clauses() {
|
||||
strategies: StrategyCensus::default(),
|
||||
constant_blob: None,
|
||||
rounded_colors: Vec::new(),
|
||||
half_bit_colors: Vec::new(),
|
||||
own_pixel_textures: Vec::new(),
|
||||
snapshot_textures: Vec::new(),
|
||||
private_bytes: 0,
|
||||
|
||||
@@ -127,7 +127,6 @@ fn stage_footprint(stage: &StageModule) -> u64 {
|
||||
+ clauses
|
||||
+ vector_bytes::<u32>(
|
||||
stage.rounded_colors.capacity()
|
||||
+ stage.half_bit_colors.capacity()
|
||||
+ stage.own_pixel_textures.capacity()
|
||||
+ stage.snapshot_textures.capacity(),
|
||||
)
|
||||
@@ -196,12 +195,6 @@ pub struct StageModule {
|
||||
/// every note holds under every specialization. [`StageModule::precision_notes_under`]
|
||||
/// gives the notes of the module as a pipeline specializes it.
|
||||
pub specialized_notes: Vec<SpecializedNote>,
|
||||
/// The color attachments this fragment stage writes as the bits of the half Metal stores,
|
||||
/// through a 16-bit output, rounding none of their channels (`StageIo::half_bit_colors`),
|
||||
/// sorted: a `half` output to a half-float attachment on a device that stores a 16-bit
|
||||
/// output's bits but not a 32-bit output's NaN as Metal does. Each such write costs the stage
|
||||
/// a few instructions per output; empty for every other stage.
|
||||
pub half_bit_colors: Vec<u32>,
|
||||
/// The texture slots this fragment stage reads only at the fragment's own pixel, sorted
|
||||
/// (`StageInterface::own_pixel_textures`): a draw's reads of such a slot lie inside the
|
||||
/// rectangle bounding its scissors, a pixel wider each way for its helper invocations, on a
|
||||
@@ -812,15 +805,22 @@ pub enum PrecisionNote {
|
||||
/// `0x7fc00000` for the NaN results of its float arithmetic and functions, and Vulkan states no
|
||||
/// encoding, so a device may answer another sign or payload (llvmpipe: `0xffc00000`). Recorded
|
||||
/// wherever the module leaves a `float` operation that can produce a NaN to the device; not by
|
||||
/// the functions that select Metal's NaN themselves, nor by Metal's precise and fast `float`
|
||||
/// divisions. Also recorded by every read, sample, gather, and pixel fetch of a `half` texel:
|
||||
/// Metal hands back the texel's own NaN, sign and payload, and Vulkan states no encoding for a
|
||||
/// 16-bit float texel's decode (MoltenVK answers the canonical NaN for every one); on a device
|
||||
/// that rounds a `half` through its conversion under the float controls (ANV, RADV), the NaN
|
||||
/// that conversion makes of the device's decode, by default (`NanMinMaxPolicy::Native`). Also
|
||||
/// recorded by a `half` texel's write to a storage texture that may hold a float format: Metal
|
||||
/// stores a 16-bit float texel's NaN as the half's own bits and a 32-bit one's as `0x7fc00000`,
|
||||
/// and the device converts the half widened. Also recorded by a 16-bit float attachment's blend
|
||||
/// Metal's precise and fast `float` divisions. Also recorded by every read, sample, gather, and
|
||||
/// pixel fetch of a `half` texel: Metal hands back the texel's own NaN, sign and payload, and
|
||||
/// Vulkan states no encoding for a 16-bit float texel's decode (MoltenVK answers the canonical
|
||||
/// NaN for every one); on a device that rounds a `half` through its conversion under the float
|
||||
/// controls (ANV, RADV), the NaN that conversion makes of the device's decode. Also recorded by
|
||||
/// a `float` read of a 16-bit float texture through its unsigned integer alias. Also recorded
|
||||
/// by a `half` texel's write to a storage texture that may hold a float format, a slot whose
|
||||
/// storage choice declares none or a heap element: Metal stores a 16-bit float texel's NaN as
|
||||
/// the half's own bits and a 32-bit or packed small float one's as its canonical NaN, and the
|
||||
/// device converts the half widened. Also recorded by a `float` write to a storage texture that
|
||||
/// may hold a half-float or packed small float format, and by a `float` color output written as
|
||||
/// computed to such an attachment, where the device is not measured to store Metal's NaN there:
|
||||
/// Metal stores every NaN as its canonical one, and RADV and NVIDIA keep a NaN's payload bits.
|
||||
/// Also recorded by a fixed-function vertex attribute of a float format narrower than 32 bits
|
||||
/// that the function reads as `float`: Metal widens its NaN to `0x7fc00000`, and the device's
|
||||
/// widening need not. Also recorded by a 16-bit float attachment's blend
|
||||
/// the function computes in the storage form, on a device not measured to store `0x7fc00000` in
|
||||
/// a 16-bit float storage image as Metal's `0x7e00` (`DriverDeviation::MetalFloatStorageNans`):
|
||||
/// the blend gives every NaN as `0x7fc00000`, and the device's store converts it (ANV stores
|
||||
@@ -1766,8 +1766,11 @@ pub enum PrecisionNote {
|
||||
/// NaN's encoding is the device's. Validation derives no tolerance from it.
|
||||
NativeHalfQuantize,
|
||||
/// Native device maths: a `float` or `half` operation's NaN result is the device's, its sign
|
||||
/// and payload unselected, on a device whose arithmetic is not measured to answer Metal's
|
||||
/// canonical NaN, under `NanMinMaxPolicy::Native` (the default). **Recorded bound:** where
|
||||
/// and payload unselected, where Metal answers a NaN the device is not measured to answer:
|
||||
/// every NaN Metal answers on a device whose arithmetic is not measured to answer Metal's
|
||||
/// canonical NaN, and every NaN but the canonical one (an operand's bits, or the canonical NaN
|
||||
/// with an operand's sign) on a device measured to answer it (MoltenVK on an Apple GPU).
|
||||
/// **Recorded bound:** where
|
||||
/// Metal answers a NaN the device answers a NaN (the module keeps
|
||||
/// `SignedZeroInfNanPreserve` where Metal's entry keeps NaNs), its sign and payload the
|
||||
/// device's own (llvmpipe: `0xffc00000`), where Metal answers its canonical `0x7fc00000`
|
||||
@@ -1781,8 +1784,9 @@ pub enum PrecisionNote {
|
||||
NativeNanEncoding,
|
||||
/// Native device maths: Metal's `fmin`, `fmax`, `min3`, `max3`, `clamp` or `saturate` (its
|
||||
/// `clamp(x, +0, 1)`) on `float` or `half` is the device's `GLSL.std.450` `NMin`, `NMax` or
|
||||
/// `NClamp`, not the translation's selects of Metal's operand, on a device not measured to
|
||||
/// answer Metal's, under `NanMinMaxPolicy::Native` (the default). **Recorded bound:** the
|
||||
/// `NClamp`, on a device not measured to answer Metal's operand; and a `saturate` of a format
|
||||
/// whose operand Metal's other functions do not pick (`bfloat`, `double`) on every device.
|
||||
/// **Recorded bound:** the
|
||||
/// result is one of the operands, the one Metal answers but at three ties: of two NaNs a NaN
|
||||
/// (its bits the device's), where Metal answers the second operand's; of `+0` and `-0` either
|
||||
/// zero, where Metal answers the second; and an `f32` denormal beside a zero or another
|
||||
|
||||
@@ -1842,7 +1842,7 @@ pub(crate) fn spec_request(
|
||||
/// parameters `lower::stage_io` plans). Each with the numeric class it is declared with and
|
||||
/// whether its declared form is a 32-bit `float` (`float`, `float2`, `float3`, `float4`), which is
|
||||
/// what the projection's `VertexFetch::FixedFunction::narrow_float` may hold of it: only a 32-bit
|
||||
/// `float` read canonicalizes the device's widening (`lower::stage_io::plan`). Empty for any other
|
||||
/// `float` read notes the device's widening's NaN (`lower::stage_io::plan`). Empty for any other
|
||||
/// stage.
|
||||
pub(crate) fn declared_attributes(
|
||||
spec: &air::Entry,
|
||||
@@ -2327,8 +2327,9 @@ fn lower_inputs(
|
||||
pull_every,
|
||||
)?;
|
||||
// `narrow_float` is key data only where the entry reads the attribute as a 32-bit
|
||||
// `float`; a `half`-declared attribute compiles the same either way, so the bit must
|
||||
// not key a variant of it (`link::vertex::narrow_float_of_f32_reads`).
|
||||
// `float`, whose NaN the module notes; a `half`-declared attribute compiles the same
|
||||
// either way, so the bit must not key a variant of it
|
||||
// (`link::vertex::narrow_float_of_f32_reads`).
|
||||
crate::pipeline::link::vertex::narrow_float_of_f32_reads(&mut projection, |a| {
|
||||
declared.get(&a).is_some_and(|&(_, f32_read)| f32_read)
|
||||
});
|
||||
@@ -2674,7 +2675,7 @@ fn compile_kept<K>(
|
||||
// 16-bit arithmetic, which they make Metal's too, or read from its bits by the device's
|
||||
// widening, which they make exact but for a NaN's bits: the entry declares them, and so
|
||||
// requires the device's float-controls properties for them, and no fact. A module that widens
|
||||
// so leaves a NaN's bits to the device, as the profile does (`NanMinMaxPolicy::Native`).
|
||||
// so leaves a NaN's bits to the device, as every profile does.
|
||||
if plan.families.arith.quantize == crate::spirv::builder::QuantizeForm::Controlled {
|
||||
let widens = crate::lower::arith::narrow::widens_bits(&module, m)?;
|
||||
if widens
|
||||
|
||||
@@ -1507,7 +1507,6 @@ fn stage_module(c: &CompiledFunction, linked: &Linked, i: usize) -> Result<Stage
|
||||
constant_blob: a.blob.clone(),
|
||||
rounded_colors,
|
||||
specialized_notes: a.specialized.clone(),
|
||||
half_bit_colors: a.interface.io.half_bit_colors.clone(),
|
||||
own_pixel_textures: a.interface.own_pixel_textures.clone(),
|
||||
snapshot_textures: a.interface.snapshot_textures.clone(),
|
||||
private_bytes: a.interface.private_bytes,
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
use crate::budget::{Budget, Meter};
|
||||
use crate::cache::VariantKey;
|
||||
use crate::device::policy::{
|
||||
DevicePolicy, NanMinMaxPolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy,
|
||||
DevicePolicy, SamplingPolicy, TexelConversionPolicy, YCbCrFilterPolicy,
|
||||
};
|
||||
use crate::device::{mechanism, Device, DeviceProfile};
|
||||
use crate::error::Error;
|
||||
@@ -298,7 +298,6 @@ impl ReducedForms {
|
||||
ReducedForms::NativeSampling => sampled,
|
||||
ReducedForms::AllNative => DevicePolicy {
|
||||
texel_conversion: TexelConversionPolicy::Device,
|
||||
nan_and_min_max: NanMinMaxPolicy::Native,
|
||||
..sampled
|
||||
},
|
||||
}
|
||||
@@ -316,7 +315,6 @@ fn dropped_forms(
|
||||
let fact = RuntimeFact::ExactFormsOverCompilerLimit {
|
||||
sampling: base.sampling != policy.sampling || base.ycbcr_filter != policy.ycbcr_filter,
|
||||
texel_conversion: base.texel_conversion != policy.texel_conversion,
|
||||
nan_and_min_max: base.nan_and_min_max != policy.nan_and_min_max,
|
||||
};
|
||||
RuntimeDependency {
|
||||
fact,
|
||||
|
||||
@@ -65,13 +65,12 @@ fn device(stem: &str, policy: DevicePolicy) -> Device {
|
||||
|
||||
/// The forms a fitted pipeline's `dependencies` record it dropped, in the fact's field order;
|
||||
/// `None` where it records none.
|
||||
fn dropped(dependencies: &[RuntimeDependency]) -> Option<[bool; 3]> {
|
||||
fn dropped(dependencies: &[RuntimeDependency]) -> Option<[bool; 2]> {
|
||||
dependencies.iter().find_map(|d| match d.fact {
|
||||
RuntimeFact::ExactFormsOverCompilerLimit {
|
||||
sampling,
|
||||
texel_conversion,
|
||||
nan_and_min_max,
|
||||
} => Some([sampling, texel_conversion, nan_and_min_max]),
|
||||
} => Some([sampling, texel_conversion]),
|
||||
_ => None,
|
||||
})
|
||||
}
|
||||
@@ -83,7 +82,6 @@ fn fitted_as<P: Fitted>(reduced: P, compiled: &P) -> P {
|
||||
let fact = RuntimeFact::ExactFormsOverCompilerLimit {
|
||||
sampling: true,
|
||||
texel_conversion: true,
|
||||
nan_and_min_max: true,
|
||||
};
|
||||
let mut reduced = reduced;
|
||||
reduced
|
||||
@@ -163,7 +161,7 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
|
||||
assert_eq!(largest(&pipe), w_fast, "reduced to the fast default");
|
||||
assert_eq!(
|
||||
dropped(&pipe.dependencies),
|
||||
Some([true; 3]),
|
||||
Some([true; 2]),
|
||||
"every exact form dropped"
|
||||
);
|
||||
|
||||
@@ -174,7 +172,7 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
|
||||
assert_eq!(largest(&pipe), w_sampling_native);
|
||||
assert_eq!(
|
||||
dropped(&pipe.dependencies),
|
||||
Some([true, false, false]),
|
||||
Some([true, false]),
|
||||
"only sampling dropped"
|
||||
);
|
||||
}
|
||||
@@ -226,7 +224,7 @@ fn a_module_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
|
||||
.expect("fitted from the functions");
|
||||
assert_eq!(fitted.key, keys.pipeline);
|
||||
assert_eq!(largest(&fitted), w_fast);
|
||||
assert_eq!(dropped(&fitted.dependencies), Some([true; 3]));
|
||||
assert_eq!(dropped(&fitted.dependencies), Some([true; 2]));
|
||||
}
|
||||
|
||||
/// A mesh render pipeline is fitted as a vertex and fragment pipeline is: past the bound, its
|
||||
@@ -506,7 +504,7 @@ fn a_compute_pipeline_over_the_compiler_bound_drops_its_exact_forms_to_fit() {
|
||||
assert_eq!(pipe.stage, sampled.stage, "{stem}: native sampling");
|
||||
assert_eq!(
|
||||
dropped(&pipe.dependencies),
|
||||
Some([true, false, false]),
|
||||
Some([true, false]),
|
||||
"{stem}: only sampling dropped"
|
||||
);
|
||||
assert_eq!(
|
||||
|
||||
@@ -597,13 +597,6 @@ pub enum RuntimeFact {
|
||||
multisampled: bool,
|
||||
planes: bool,
|
||||
},
|
||||
/// The function writes `half` texels to the storage texture bound to the slot, whose storage
|
||||
/// choice declares no format, and reads whether its channels are 16-bit floats
|
||||
/// (`PushField::TextureHalfChannels`): Metal stores a written half's NaN as the half's own
|
||||
/// bits in a 16-bit float channel and as its conversion of `0x7fc00000` in any other. The
|
||||
/// binder writes 1 for a bound `R16Float`, `RG16Float` or `RGBA16Float` texture
|
||||
/// (`metal::format::half_channels`), and 0 for any other and a neutral.
|
||||
StorageTextureHalfChannels { slot: SlotRef },
|
||||
/// The vertex function was compiled in capture form `form` (`VariantKey::captured_positions`,
|
||||
/// `LoweringInputs::captured_positions`): each vertex it runs writes a 32-byte record of its
|
||||
/// clip position, point size and restart flag from `PushField::CaptureAddress`, at the slot
|
||||
@@ -727,9 +720,10 @@ pub enum RuntimeFact {
|
||||
/// device stores exactly. A member the twin does not hold stores the device's conversion of a
|
||||
/// NaN, not Metal's: a half-float texture that is swizzled or whose image takes no view in
|
||||
/// another format, and where `packed` a packed small float one (`RG11B10Float`,
|
||||
/// `RGB9E5Float`); `bind::heap_write_nans_converted` names such a texture. The module records
|
||||
/// no `PrecisionNote::DeviceNanEncoding` for these writes: the consumer announces it at a
|
||||
/// draw or dispatch whose heap holds such a texture.
|
||||
/// `RGB9E5Float`); `bind::heap_write_nans_converted` names such a texture, which the consumer
|
||||
/// announces `PrecisionNote::DeviceNanEncoding` for at a draw or dispatch whose heap holds
|
||||
/// one. The module records that note for these writes too: a 32-bit or packed small float
|
||||
/// member's NaN is the device's.
|
||||
HeapHalfTexelWrites { stage: Stage, packed: bool },
|
||||
/// The render pipeline draws through synthesized geometry stages, one per topology class, of
|
||||
/// which a draw runs its class's (`RenderPipeline::runs_stage`): its fragment function reads
|
||||
@@ -768,7 +762,6 @@ pub enum RuntimeFact {
|
||||
ExactFormsOverCompilerLimit {
|
||||
sampling: bool,
|
||||
texel_conversion: bool,
|
||||
nan_and_min_max: bool,
|
||||
},
|
||||
/// The render pipeline was compiled under `VariantKey::quad_primitive_ids`, and its fragment
|
||||
/// function reads `[[primitive_id]]` from Vulkan's `PrimitiveId` shifted right by one
|
||||
|
||||
@@ -122,8 +122,8 @@ fn invariant(detail: &str) -> Error {
|
||||
}
|
||||
|
||||
/// Whether data type `ty` is the scalar or vector `want` declares (32-bit `float` or
|
||||
/// unsigned-integer lanes; signed-integer lanes for a color output to a signed-integer attachment;
|
||||
/// 16-bit `float` lanes for a color output written as a half's bits).
|
||||
/// unsigned-integer lanes; signed-integer lanes for a color output to a signed-integer
|
||||
/// attachment).
|
||||
fn io_type_matches(m: &TypedModule, ty: TypeId, want: IoType) -> Result<bool, Error> {
|
||||
let types = m.types();
|
||||
let (elem, lanes) = match types.get(ty)? {
|
||||
@@ -131,15 +131,15 @@ fn io_type_matches(m: &TypedModule, ty: TypeId, want: IoType) -> Result<bool, Er
|
||||
_ => (ty, 1),
|
||||
};
|
||||
let numeric = match types.get(elem)? {
|
||||
Type::Float { width } if u32::from(*width) == u32::from(want.bits) => IoNumeric::Float,
|
||||
Type::Float { width: 32 } => IoNumeric::Float,
|
||||
Type::Int {
|
||||
width: 32,
|
||||
signed: false,
|
||||
} if want.bits == 32 => IoNumeric::Uint,
|
||||
} => IoNumeric::Uint,
|
||||
Type::Int {
|
||||
width: 32,
|
||||
signed: true,
|
||||
} if want.bits == 32 => IoNumeric::Sint,
|
||||
} => IoNumeric::Sint,
|
||||
_ => return Ok(false),
|
||||
};
|
||||
Ok(numeric == want.numeric && lanes == want.components)
|
||||
|
||||
@@ -387,7 +387,6 @@ impl GeometryStages {
|
||||
constant_blob: None,
|
||||
rounded_colors: Vec::new(),
|
||||
specialized_notes: Vec::new(),
|
||||
half_bit_colors: Vec::new(),
|
||||
own_pixel_textures: Vec::new(),
|
||||
snapshot_textures: Vec::new(),
|
||||
private_bytes: 0,
|
||||
|
||||
@@ -9,10 +9,10 @@
|
||||
//! `ColorAttachmentBlend` when blending), the write mask, and the blend state; at most
|
||||
//! `maxColorAttachments` of them. A blend of factors one and zero, added, for color and alpha,
|
||||
//! of an attachment whose format converts the fragment function's output
|
||||
//! (`StageIo::color_writes`), or that the function rounds (`StageIo::rounded_colors`) or writes
|
||||
//! as a half's bits (`StageIo::half_bit_colors`), takes no Vulkan blend: Metal's blend stores the
|
||||
//! output as written, as no blend does, which a device's blend could still change (x86 lavapipe
|
||||
//! adds the clear's `+0` to a `-0` source of an `R16Float` attachment, Metal keeps `-0`). An
|
||||
//! (`StageIo::color_writes`), or that the function rounds (`StageIo::rounded_colors`), takes no
|
||||
//! Vulkan blend: Metal's blend stores the output as written, as no blend does, which a device's
|
||||
//! blend could still change (x86 lavapipe adds the clear's `+0` to a `-0` source of an
|
||||
//! `R16Float` attachment, Metal keeps `-0`). An
|
||||
//! attachment that no first (index 0) output of the fragment function names (every attachment of
|
||||
//! a pipeline without a fragment function) gets an empty write mask, so the draw leaves it
|
||||
//! unmodified. That is what Metal does where measured: an unblended attachment the function reads
|
||||
@@ -388,14 +388,13 @@ pub fn graphics_state(
|
||||
// Metal's blend of one and zero stores the output as written, as no blend
|
||||
// does, so an attachment whose format converts the output (its channels
|
||||
// take a rule of Metal's, `StageIo::color_writes`), or one the function
|
||||
// rounds or writes as a half's bits, takes no Vulkan blend there, nor the
|
||||
// rounds, takes no Vulkan blend there, nor the
|
||||
// format's blend support. But not a 16-bit float attachment's from a module
|
||||
// without fast math, whose blend Metal computes keeping the destination's
|
||||
// product by zero: that one blends, announced (`color_writes::keeps_zero`).
|
||||
let stored = fs.is_some_and(|f| {
|
||||
let color = index as u32;
|
||||
f.io.rounded_colors.contains(&color)
|
||||
|| f.io.half_bit_colors.contains(&color)
|
||||
|| f.io.color_writes.get(&color).is_some_and(|rules| {
|
||||
rules.iter().flatten().any(|r| {
|
||||
*r != crate::pipeline::lower_inputs::ChannelWrite::Device
|
||||
|
||||
@@ -151,7 +151,6 @@ pub fn synthesized_stage(
|
||||
constant_blob: None,
|
||||
rounded_colors: Vec::new(),
|
||||
specialized_notes: Vec::new(),
|
||||
half_bit_colors: Vec::new(),
|
||||
own_pixel_textures: Vec::new(),
|
||||
snapshot_textures: Vec::new(),
|
||||
private_bytes: 0,
|
||||
|
||||
@@ -384,7 +384,6 @@ pub fn synthesized_stages(
|
||||
constant_blob: None,
|
||||
rounded_colors: Vec::new(),
|
||||
specialized_notes: Vec::new(),
|
||||
half_bit_colors: Vec::new(),
|
||||
own_pixel_textures: Vec::new(),
|
||||
snapshot_textures: Vec::new(),
|
||||
private_bytes: 0,
|
||||
|
||||
@@ -45,7 +45,6 @@ pub(super) fn io_ty(numeric: IoNumeric, components: u8) -> IoType {
|
||||
numeric,
|
||||
components,
|
||||
source_bits: 32,
|
||||
bits: 32,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -358,11 +358,11 @@ pub fn vertex_fetch_projection_for(
|
||||
/// Clear `narrow_float` on every fixed-function attribute of `projection` that `f32_read` does
|
||||
/// not hold.
|
||||
///
|
||||
/// The bit asks the function to canonicalize the device's widening of a narrow-float format, and
|
||||
/// `lower::stage_io::plan` emits that canonicalization only where the attribute's declared form is
|
||||
/// a 32-bit `float`: a `half`-declared attribute keeps the fetched code's own bits, as Metal's
|
||||
/// `half` attribute does, whatever the format was. So the bit changes no instruction of such a
|
||||
/// stage, and carrying it in the compile key would make one program two keys
|
||||
/// The bit asks the function to note the NaN of the device's widening of a narrow-float format
|
||||
/// (`PrecisionNote::DeviceNanEncoding`), and `lower::stage_io::plan` records that note only where
|
||||
/// the attribute's declared form is a 32-bit `float`: a `half`-declared attribute keeps the fetched
|
||||
/// code's own bits, as Metal's `half` attribute does, whatever the format was. So the bit changes
|
||||
/// nothing of such a stage, and carrying it in the compile key would make one program two keys
|
||||
/// (`tests::engine_vertex_variants`). Both sides of the key apply this: the compile
|
||||
/// (`pipeline::compile::lower_inputs`, from the specialized entry's parameter forms) and link's
|
||||
/// recomputation ([`vertex_input_state`], from the stage's own declared types), so a stage
|
||||
@@ -379,8 +379,8 @@ pub fn narrow_float_of_f32_reads(
|
||||
}
|
||||
|
||||
/// The projection entry of a resolved attribute. A fixed-function entry carries whether the Metal
|
||||
/// format's components are floats narrower than 32 bits, which the function canonicalizes after
|
||||
/// the device's widening (`VertexFetch::FixedFunction`); the rest of the format is `VertexAttribute`
|
||||
/// format's components are floats narrower than 32 bits, whose NaN after the device's widening
|
||||
/// the function notes (`VertexFetch::FixedFunction`); the rest of the format is `VertexAttribute`
|
||||
/// state.
|
||||
fn fetch_of(r: &Resolved<'_>) -> Result<VertexFetch, Error> {
|
||||
Ok(match r.fetch {
|
||||
|
||||
@@ -1426,22 +1426,12 @@ pub enum StorageImageClass {
|
||||
/// texels and `read_write` access).
|
||||
AlphaInRed,
|
||||
/// A half-float image (`R16Float`, `RG16Float`, `RGBA16Float`) written by a device not
|
||||
/// measured to store every NaN as Metal's `0x7e00`: the shader writes a `float` channel's NaN
|
||||
/// as `0x7fc00000`, every other value as computed, which the device's conversion rounds. A
|
||||
/// `half` texel is written as it is, and reads are `Identity`'s.
|
||||
HalfQuietNan,
|
||||
/// A 4:4:4 two-plane YCbCr texture a slot only writes, through an `R32G32B32A32_UINT` image
|
||||
/// of the texture's own (the consumer's write shadow): the shader writes each texel as the
|
||||
/// bits of its red, green and blue `float` channels (a `half` texel's widened exactly) and a
|
||||
/// 1, the mark of a written texel, which the consumer then encodes into the planes as Metal
|
||||
/// stores it (`bind::ycbcr_write`). The slot is declared `Rgba32ui`; it has no reads.
|
||||
YCbCrWrite,
|
||||
/// An `RG11B10Float` image written by `float` texels, on every device: the shader writes a
|
||||
/// channel's NaN as `0x7fc00000`, which every device measured stores as Metal's `0x7e0` (and
|
||||
/// `0x3f0` in the 10-bit field), every other value as computed, which each rounds toward zero
|
||||
/// as Metal does; RADV and NVIDIA keep another NaN's payload bits. A `half` texel is written
|
||||
/// as it is, and reads are `Identity`'s.
|
||||
SmallFloatQuietNan,
|
||||
/// A half-float image (`R16Float`, `RG16Float`, `RGBA16Float`) a slot writes, and may read,
|
||||
/// on a device not measured to store a written `half`'s NaN as its bits
|
||||
/// (`DriverDeviation::MetalHalfTexelWrites`), viewed through its unsigned integer alias of
|
||||
@@ -1508,8 +1498,8 @@ pub enum VertexFetch {
|
||||
/// `narrow_float`: the Metal format's components are floats narrower than 32 bits (a `half`
|
||||
/// format, or `FloatRG11B10`), which the device's vertex input widens to a `float` attribute
|
||||
/// with a widening of its own, **and** the function reads the attribute as a 32-bit `float`.
|
||||
/// Metal's fetch answers its canonical NaN there, so such a read canonicalizes the value it
|
||||
/// loads (`lower::stage_io`); a `half`-declared attribute keeps the fetched code's own bits,
|
||||
/// Metal's fetch answers its canonical NaN there, so such a read records the device's NaN
|
||||
/// (`PrecisionNote::DeviceNanEncoding`, `lower::stage_io`); a `half`-declared attribute keeps the fetched code's own bits,
|
||||
/// as Metal's `half` attribute does, so the bit is clear for one whatever the format was
|
||||
/// (`link::vertex::narrow_float_of_f32_reads`) and no variant of it is keyed on the format.
|
||||
/// The attribute's own encoding is link-time state, and this bit is what the compile key
|
||||
|
||||
@@ -46,8 +46,7 @@
|
||||
//! link; it reads the role here, never the bytes.
|
||||
//!
|
||||
//! Every interface variable is 32-bit (narrow varyings are widened at the interface, so no varying
|
||||
//! needs `storageInputOutput16`) but a color output written as the bits of the half Metal stores,
|
||||
//! 16-bit ([`IoType::bits`]); [`IoType::source_bits`] keeps the AIR element width for format
|
||||
//! needs `storageInputOutput16`); [`IoType::source_bits`] keeps the AIR element width for format
|
||||
//! checks. An attribute or color takes one whole location; a user varying takes one location at
|
||||
//! component 0 unless link packs varyings into shared locations, for which the module decorates
|
||||
//! every varying with a relocatable `Component`.
|
||||
@@ -202,13 +201,6 @@ pub struct StageIo {
|
||||
/// (`StageModule::rounded_colors`).
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub rounded_colors: Vec<u32>,
|
||||
/// The attachments among `color_writes` whose output the function writes as the bits of the
|
||||
/// half Metal stores, through a 16-bit output, rounding none of its channels (a `half`
|
||||
/// output to a half-float attachment), sorted: the device's conversion of a 32-bit output
|
||||
/// would not keep a NaN's payload (`StageModule::half_bit_colors`). Link gives these, as
|
||||
/// `rounded_colors`, no Vulkan blend of one and zero.
|
||||
#[cfg_attr(feature = "serde", serde(default))]
|
||||
pub half_bit_colors: Vec<u32>,
|
||||
/// The extended-range attachments the fragment function writes a `float` or `half` output
|
||||
/// to through output variables of dual-source index 0
|
||||
/// (`LoweringInputs::extended_range_colors`), by color index: each output variable there is
|
||||
@@ -556,8 +548,8 @@ impl StageIo {
|
||||
}
|
||||
|
||||
/// The vertex attributes the function reads in fixed function as a 32-bit `float` (`float`,
|
||||
/// `float2`, `float3`, `float4`), which is where a narrow-float format's widening is
|
||||
/// canonicalized (`link::vertex::narrow_float_of_f32_reads`). A `half`-declared attribute is
|
||||
/// `float2`, `float3`, `float4`), which is where a narrow-float format's widening's NaN is
|
||||
/// noted (`link::vertex::narrow_float_of_f32_reads`). A `half`-declared attribute is
|
||||
/// not among them, and neither is a pulled attribute, whose decode the module holds whole.
|
||||
pub fn f32_attributes(&self) -> std::collections::BTreeSet<u32> {
|
||||
self.inputs
|
||||
@@ -590,7 +582,6 @@ impl StageIo {
|
||||
numeric: IoNumeric::Uint,
|
||||
components: 1,
|
||||
source_bits: 32,
|
||||
bits: 32,
|
||||
};
|
||||
}
|
||||
match self.extended_range_colors.get(&attachment) {
|
||||
@@ -598,7 +589,6 @@ impl StageIo {
|
||||
numeric: IoNumeric::Uint,
|
||||
components: e.form.raw_components() as u8,
|
||||
source_bits: 32,
|
||||
bits: 32,
|
||||
},
|
||||
None => v.ty,
|
||||
}
|
||||
@@ -735,7 +725,7 @@ pub struct IoVariable {
|
||||
pub enum IoRole {
|
||||
/// Vertex attribute `index`, fetched by fixed-function vertex input. `narrow_float` is the
|
||||
/// `VertexFetch::FixedFunction` bit the function was compiled under: the Metal format's
|
||||
/// components are floats narrower than 32 bits, whose widening the function canonicalizes
|
||||
/// components are floats narrower than 32 bits, whose widening's NaN the function notes
|
||||
/// where it reads the attribute as `float`.
|
||||
Attribute { index: u32, narrow_float: bool },
|
||||
/// A vertex output or fragment input matched by its AIR user key.
|
||||
@@ -855,7 +845,7 @@ pub enum Sampling {
|
||||
}
|
||||
|
||||
/// The declared type of an interface variable: `components` lanes (1–4) of `numeric`, each of
|
||||
/// `bits` bits.
|
||||
/// 32 bits.
|
||||
#[non_exhaustive]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
@@ -865,9 +855,6 @@ pub struct IoType {
|
||||
/// The AIR element width (8, 16, or 32; 16 for `half`; 1 for `bool`, carried as `uint` 0 or
|
||||
/// 1): narrower values are widened at the interface.
|
||||
pub source_bits: u8,
|
||||
/// The declared lane width: 32, or 16 for a `float` color output written as the bits of the
|
||||
/// half Metal stores into a half-float attachment (`storageInputOutput16`).
|
||||
pub bits: u8,
|
||||
}
|
||||
|
||||
/// The numeric class the variable is declared with.
|
||||
|
||||
@@ -1100,12 +1100,6 @@ pub enum PushField {
|
||||
/// clip mode is `MTLDepthClipModeClamp` in bit 4; words 1 and 2 the bits of viewport 0's near
|
||||
/// and far depth (`f32`); word 3 is 0 (`bind::shader_tests_words`).
|
||||
ShaderTestsState,
|
||||
/// Whether the storage texture bound to the slot holds 16-bit float channels (`u32`, 1 or 0;
|
||||
/// 0 where the binder binds a neutral): a `half` texel's write keeps the half where it is 1
|
||||
/// and writes every NaN as `0x7fc00000` where it is 0, as Metal stores a written half
|
||||
/// (`RuntimeFact::StorageTextureHalfChannels`, a slot whose storage choice declares no
|
||||
/// format).
|
||||
TextureHalfChannels(SlotRef),
|
||||
/// The draw's capture layout for a vertex function compiled under
|
||||
/// `LoweringInputs::captured_positions` (`RuntimeFact::CapturedPositions`), a `uvec4`. In the
|
||||
/// vertices form: the draw's first vertex, its vertex count, its first instance, and 0. In the
|
||||
|
||||
@@ -160,9 +160,8 @@ pub fn storage_buffers(a: &FunctionArtifact) -> u32 {
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// The default policy with Metal's NaN and minimum and maximum (`NanMinMaxPolicy::Exact`): the
|
||||
/// policy of the tests of those forms, which the device's forms, the defaults, leave off a device
|
||||
/// whose functions are not Metal's. The texel conversions are the default's.
|
||||
/// The default policy with Metal's answers wherever a choice still offers them
|
||||
/// ([`DevicePolicy::exact_answers`]) but the texel conversions, which are the default's.
|
||||
pub fn exact_maths() -> DevicePolicy {
|
||||
let native = DevicePolicy::default();
|
||||
DevicePolicy {
|
||||
|
||||
@@ -144,9 +144,6 @@ pub struct ModuleBuilder {
|
||||
/// Whether that rounding is the device's own rather than one measured to be Metal's
|
||||
/// ([`ModuleBuilder::native_half`]).
|
||||
native_half: bool,
|
||||
/// Whether a `half` texel keeps the NaN the device decoded under native half rounding too
|
||||
/// ([`ModuleBuilder::texel_nans`]).
|
||||
texel_nans: bool,
|
||||
/// Whether a `half`'s NaN bits are the device's conversion's under the float controls
|
||||
/// ([`ModuleBuilder::native_half_nans`]).
|
||||
native_half_nans: bool,
|
||||
@@ -283,25 +280,10 @@ impl ModuleBuilder {
|
||||
self.native_half
|
||||
}
|
||||
|
||||
/// Whether a `half` texel keeps the NaN the device decoded even where the module's `half`
|
||||
/// rounding is the device's own ([`ModuleBuilder::native_half`]): where the NaN switch asks
|
||||
/// for Metal's NaN (`NanMinMaxPolicy::Exact`). Emission sets it with the form; a builder that
|
||||
/// never sets it keeps the NaN wherever the rounding is Metal's, as before.
|
||||
pub fn set_texel_nans(&mut self, keep: bool) {
|
||||
self.texel_nans = keep;
|
||||
}
|
||||
|
||||
/// Whether a `half` texel keeps its decoded NaN under native half rounding
|
||||
/// ([`ModuleBuilder::set_texel_nans`]).
|
||||
pub fn texel_nans(&self) -> bool {
|
||||
self.texel_nans
|
||||
}
|
||||
|
||||
/// Whether a `half`'s NaN bits are left to the device's conversion where the module rounds
|
||||
/// through it under the float controls ([`QuantizeForm::Controlled`]): a `half` read from its
|
||||
/// bits is the device's widening of them, and a `half` texel takes the rounding's NaN, where
|
||||
/// the profile leaves NaN bits to the device (`NanMinMaxPolicy::Native`). Emission sets it
|
||||
/// with the form; a builder that never sets it decodes in integer arithmetic and keeps a
|
||||
/// bits is the device's widening of them, and a `half` texel takes the rounding's NaN. Emission
|
||||
/// sets it with the form; a builder that never sets it decodes in integer arithmetic and keeps a
|
||||
/// texel's NaN, as before.
|
||||
pub fn set_native_half_nans(&mut self, native: bool) {
|
||||
self.native_half_nans = native;
|
||||
|
||||
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user