diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 21bcc26b7..56dc02180 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -4a5b4059ae00eeaa7edcf46e3651cf2ed4066b64c22c11d81c0deef1bf89909a +9c0db9f87ef306400bae2334e3749350c1a68c875d2a5d5b1f5e9ffb93c17e7a diff --git a/crates/metal2vulkan-validation/src/c3/bound.rs b/crates/metal2vulkan-validation/src/c3/bound.rs index faede801f..94db293eb 100644 --- a/crates/metal2vulkan-validation/src/c3/bound.rs +++ b/crates/metal2vulkan-validation/src/c3/bound.rs @@ -34,7 +34,7 @@ use crate::case::BufferResource; use crate::observation_contract::{value_difference, ValueDifference}; use base64::Engine as _; use metal2vulkan::device::{DeviceProfile, FloatWidth}; -use metal2vulkan::pipeline::{EntryMath, PrecisionNote}; +use metal2vulkan::pipeline::PrecisionNote; use metal2vulkan_air::intrinsics::AirIntrinsic; use metal2vulkan_air::ir::{BinOp, FastMath}; use msl::{Admits, Expr, Format, Math, Prim}; @@ -302,25 +302,20 @@ impl AirOp { /// The precision notes the product's lowering of this operation on `format` records under /// `math` on profile `profile`: the product's own answer (`PrecisionNote::of_float_operator`, /// or `PrecisionNote::of_math_call` of the call's name as [`AirIntrinsic::parse`] decodes it). - /// Under fast math Metal's calls and operators carry every fast-math flag (`fast`), and the - /// entry's module is a fast one ([`EntryMath::Fast`]); otherwise they carry none, a division - /// without them is Metal's precise one, which records nothing, and the module keeps NaNs - /// ([`EntryMath::Precise`]). An error where the product does not lower the operation as a float - /// operation. + /// Under fast math Metal's calls and operators carry every fast-math flag (`fast`); otherwise + /// they carry none, and a division without them is Metal's precise one. An error where the + /// product does not lower the operation as a float operation. pub fn product_notes( &self, format: Format, math: Math, profile: &DeviceProfile, ) -> Result, String> { - let (fmf, entry) = match math { - Math::Fast => ( - FastMath::ALL - .iter() - .fold(FastMath::NONE, |all, (flag, _)| all.union(*flag)), - EntryMath::Fast, - ), - Math::Precise => (FastMath::NONE, EntryMath::Precise), + let fmf = match math { + Math::Fast => FastMath::ALL + .iter() + .fold(FastMath::NONE, |all, (flag, _)| all.union(*flag)), + Math::Precise => FastMath::NONE, }; let notes = match self { AirOp::Binop(op) => PrecisionNote::of_float_operator( @@ -331,12 +326,9 @@ impl AirOp { }, fmf, profile, - entry, ), AirOp::Call(name) => match AirIntrinsic::parse(name) { - Some(AirIntrinsic::Math(call)) => { - PrecisionNote::of_math_call(call, fmf, profile, entry) - } + Some(AirIntrinsic::Math(call)) => PrecisionNote::of_math_call(call, fmf, profile), _ => None, }, }; @@ -359,8 +351,7 @@ impl std::fmt::Display for AirOp { /// Metal's (a near-equivalent): a float division, a square root or remainder, and a function the /// product computes with a division of its own (fast `float` `tanh` and `atan2`). Whether the /// product records it is the product's answer ([`AirOp::product_notes`]) on the row's venue profile -/// `profile`: on a device whose `float` functions are Metal's own, an operation that is Metal's own -/// under fast math records none there. +/// `profile`. /// /// The device's transcendentals (`DeviceTranscendentals`) are the device's own answer, which the /// user accepts within Apple's bound, so they are no near-equivalent. diff --git a/crates/metal2vulkan-validation/tests/integration/fast_trig_within_apples_bound.rs b/crates/metal2vulkan-validation/tests/integration/fast_trig_within_apples_bound.rs index 3eed06096..239b15b03 100644 --- a/crates/metal2vulkan-validation/tests/integration/fast_trig_within_apples_bound.rs +++ b/crates/metal2vulkan-validation/tests/integration/fast_trig_within_apples_bound.rs @@ -1,10 +1,10 @@ -//! Fast `sin`, `cos` and `tan` on `[-pi, pi]` keep the device's own instruction, and on a device -//! whose functions are Metal's (MoltenVK) fast `sinpi`, `cospi` and `tanpi` keep the device's `Sin` -//! and `Cos` around their exact reduction: a near-equivalent of Metal's answer, accepted by the -//! user's standing sign-off only where the device answers within Apple's fast-math bound (MSL Table -//! 8.2: `sin` and `cos` within `2^-13` absolute on `[-pi, pi]`, `sinpi` and `cospi` on `[-1, 1]`, -//! `tan` as `sin(x) * (1 / cos(x))` and `tanpi` as `tan(x * pi)`). This test holds that condition -//! to the committed evidence instead of to prose. Every committed Vulkan and MoltenVK row of the +//! Fast `sin`, `cos` and `tan` on `[-pi, pi]` keep the device's own instruction, and fast `sinpi`, +//! `cospi` and `tanpi` keep the device's `Sin` and `Cos` around their exact reduction: a +//! near-equivalent of Metal's answer, accepted by the user's standing sign-off only where the +//! device answers within Apple's fast-math bound (MSL Table 8.2: `sin` and `cos` within `2^-13` +//! absolute on `[-pi, pi]`, `sinpi` and `cospi` on `[-1, 1]`, `tan` as `sin(x) * (1 / cos(x))` and +//! `tanpi` as `tan(x * pi)`). This test holds that condition to the committed evidence instead of +//! to prose. Every committed Vulkan and MoltenVK row of the //! fast math-library probe case (1,024 operands under Metal's default fast math; words `32t` to //! `32t + 4` are the fast `sin`, `cos`, `tan`, and `sincos` of operand `t`, and words `32t + 26` //! to `32t + 28` its fast `sinpi`, `cospi`, and `tanpi`) is judged by C3's bound check diff --git a/crates/metal2vulkan/src/bind/heap.rs b/crates/metal2vulkan/src/bind/heap.rs index 82afee096..028875cab 100644 --- a/crates/metal2vulkan/src/bind/heap.rs +++ b/crates/metal2vulkan/src/bind/heap.rs @@ -440,8 +440,8 @@ pub(crate) const FILTERED: u32 = 2; /// `DriverDeviation::MetalHalfStorageWrites`. pub(crate) const NAN_SIXTEEN: u32 = 1; -/// The bit of `SpecKey::HeapNanFamilies` of a 32-bit float format: its written `half` NaN is -/// Metal's on a device of `DriverDeviation::MetalNanMoves`. +/// The bit of `SpecKey::HeapNanFamilies` of a 32-bit float format: its written `half` NaN is the +/// device's widening's. pub(crate) const NAN_WIDE: u32 = 2; /// The bit of `SpecKey::HeapNanFamilies` of a packed small float format (`RG11B10Float`, diff --git a/crates/metal2vulkan/src/cache/codec.rs b/crates/metal2vulkan/src/cache/codec.rs index 4922eddf4..f70c8fcaf 100644 --- a/crates/metal2vulkan/src/cache/codec.rs +++ b/crates/metal2vulkan/src/cache/codec.rs @@ -1047,16 +1047,14 @@ codec_enum! { InterpolateAtOffsetCentered, SimdgroupLockstep, MetalSampler, StorageImageSampleCount(f0), DepthResolveMode(f0), StencilResolveMode(f0), IndependentResolveNone, IndependentResolve, VariableSampleLocations, SampleLocationSampleCount(f0), ColorAttachmentSampleCount(f0, f1), - MetalHalfFma, MetalFloatDenormals, - MetalCenterVaryings, MetalMinMax, - MetalHalfArithmetic, MetalHalfStorageWrites, MetalHalfStorageNans, + MetalCenterVaryings, MetalHalfStorageWrites, MetalHalfStorageNans, MetalFragmentSimdgroups, MetalVertexSimdgroups, MetalHalfTexelWrites, MetalNormStorageWrites, DeviceSampling, MetalDepth16Stores, MetalDepth16BiasedStores, MetalInterpolation, MetalFirstVertexIndices, MetalFullQuads, ProvokingVertexModePerPipeline, MetalNormalizedVertexFetch, MetalAlphaCoverage, InterpolateAtOffsetFromSevenSixteenths, - MetalNanMoves, MetalPackConversions, MetalHalfConversion, MetalSmallFloatNans, - MetalUnaryDenormals, SubgroupGeometryStage, + MetalSmallFloatNans, + SubgroupGeometryStage, } VkLimit { MaxComputeWorkGroupSize(f0), MaxComputeWorkGroupCount(f0), MaxComputeWorkGroupInvocations, diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 0822d9b5c..01fc12770 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -61,7 +61,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2237; +pub const SEMANTICS_VERSION: u32 = 2238; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another @@ -71,7 +71,7 @@ pub const SEMANTICS_VERSION: u32 = 2237; /// 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 = 575; +pub const ARTIFACT_FORMAT_VERSION: u32 = 576; /// 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 diff --git a/crates/metal2vulkan/src/cache/tests.rs b/crates/metal2vulkan/src/cache/tests.rs index 5943fee22..3a0a2b2a7 100644 --- a/crates/metal2vulkan/src/cache/tests.rs +++ b/crates/metal2vulkan/src/cache/tests.rs @@ -821,16 +821,6 @@ fn the_version_485_member_round_trips() { assert_ne!(encode(&key), encode(&SpecKey::NearestPixelSampler(slot))); } -/// The member format version 486 appends encodes and decodes as itself: the measured unary -/// operations' kept denormals, a property a module requires. -#[test] -fn the_version_486_member_round_trips() { - use crate::device::requirements::VkProperty; - let p = VkProperty::MetalUnaryDenormals; - assert_eq!(decode::(&encode(&p)), Ok(p)); - assert_ne!(encode(&p), encode(&VkProperty::MetalSmallFloatNans)); -} - /// The member format version 535 appends encodes and decodes as itself: a kernel's image-only /// fact. #[test] diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index 62a374d20..f298ebeac 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -16,8 +16,8 @@ use crate::device::metal::MetalDeviceProperties; use crate::device::policy::DevicePolicy; use crate::device::profile::{ BufferAccess, CubeGradientRoute, CubeGradients, DescriptorCaps, DeviceProfile, EnabledCaps, - FloatFunctions, FormatTable, FragmentCaps, FunctionStorage, HandleDomain, ImageCaps, - Independence, LeafCaps, NanEncoding, PointerDomain, ProfileFields, Robustness, + FormatTable, FragmentCaps, FunctionStorage, HandleDomain, ImageCaps, Independence, LeafCaps, + PointerDomain, ProfileFields, Robustness, }; use crate::device::requirements::{ ApiVersion, FloatControl, FloatWidth, FormatUsage, ResolveMode, SubgroupOp, VkExtension, @@ -331,8 +331,6 @@ fn derive_fields(desc: &DeviceDescription, policy: &DevicePolicy) -> ProfileFiel // so the extended dynamic states a pipeline makes are exactly what it requires. dynamic_vertex_stride: has(VkFeature::ExtendedDynamicState), enabled: enabled_caps(desc), - float_functions: FloatFunctions::Native, - nan_encoding: NanEncoding::Native, // The planes of a two-plane YCbCr texture read in place on every device. ycbcr_in_place: true, // The floor: no Vulkan query states how much a thread holds. diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index adb7ca9e6..592d11508 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -226,27 +226,13 @@ impl DeviceProfile { .enabled .properties .contains(&VkProperty::SimdgroupLockstep), - DriverDeviation::MetalFloatFunctions => f.float_functions == FloatFunctions::Metal, - DriverDeviation::MetalCanonicalNans => f.nan_encoding == NanEncoding::MetalCanonical, DriverDeviation::MetalSampler => { f.enabled.properties.contains(&VkProperty::MetalSampler) } - DriverDeviation::MetalHalfFma => { - f.enabled.properties.contains(&VkProperty::MetalHalfFma) - } - DriverDeviation::MetalFloatDenormals => f - .enabled - .properties - .contains(&VkProperty::MetalFloatDenormals), DriverDeviation::MetalCenterVaryings => f .enabled .properties .contains(&VkProperty::MetalCenterVaryings), - DriverDeviation::MetalMinMax => f.enabled.properties.contains(&VkProperty::MetalMinMax), - DriverDeviation::MetalHalfArithmetic => f - .enabled - .properties - .contains(&VkProperty::MetalHalfArithmetic), DriverDeviation::MetalHalfStorageWrites => f .enabled .properties @@ -298,25 +284,10 @@ impl DeviceProfile { .enabled .properties .contains(&VkProperty::MetalAlphaCoverage), - DriverDeviation::MetalNanMoves => { - f.enabled.properties.contains(&VkProperty::MetalNanMoves) - } - DriverDeviation::MetalPackConversions => f - .enabled - .properties - .contains(&VkProperty::MetalPackConversions), - DriverDeviation::MetalHalfConversion => f - .enabled - .properties - .contains(&VkProperty::MetalHalfConversion), DriverDeviation::MetalSmallFloatNans => f .enabled .properties .contains(&VkProperty::MetalSmallFloatNans), - DriverDeviation::MetalUnaryDenormals => f - .enabled - .properties - .contains(&VkProperty::MetalUnaryDenormals), } } @@ -477,14 +448,6 @@ pub struct ProfileFields { pub dynamic_vertex_stride: bool, /// The enabled capability sets `Requirements` are checked against. pub enabled: EnabledCaps, - /// Which functions the device's `GLSL.std.450` instructions and `OpFDiv` of `float` compute: - /// 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, 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, /// Whether a two-plane YCbCr texture's planes may be read in place /// (`bind::YCbCrInPlace`): on a device whose GPU reads the planes' memory with no bus between /// (`VkPhysicalDeviceType` integrated or CPU), a texture slot whose function reads such a @@ -581,38 +544,6 @@ impl FunctionStorage { } } -/// Which functions a device's `GLSL.std.450` instructions and `OpFDiv` of `float` compute -/// ([`ProfileFields::float_functions`]), decided by the driver's measured deviation -/// [`DriverDeviation::MetalFloatFunctions`]. Either way the module takes the device's -/// instructions. -#[non_exhaustive] -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum FloatFunctions { - /// Metal's own, in the math mode Metal compiles the module with: fast where the entry - /// declares no `SignedZeroInfNanPreserve`, precise where it declares one, and precise - /// `tanh` and `atan2` either way. The division likewise: Metal's fast division and - /// reciprocal in a fast-math module, its correctly rounded ones otherwise. A call that is - /// Metal's own in the entry's mode records no note there. - Metal, - /// The device's, within Vulkan's precision table, taken as they are, each kind recorded 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`]. 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, measured: such a result - /// records nothing. - MetalCanonical, - /// The device's own, unmeasured, noted `PrecisionNote::NativeNanEncoding` with its bound. - Native, -} - /// 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. diff --git a/crates/metal2vulkan/src/device/requirements.rs b/crates/metal2vulkan/src/device/requirements.rs index b4e0387ff..933542fb1 100644 --- a/crates/metal2vulkan/src/device/requirements.rs +++ b/crates/metal2vulkan/src/device/requirements.rs @@ -638,27 +638,6 @@ pub enum VkProperty { /// `framebuffer*ColorSampleCounts` are the counts every format of a kind takes; one format /// may take more. ColorAttachmentSampleCount(vk::Format, u32), - /// The device's `GLSL.std.450 Fma` on 16-bit floats is Metal's own `half` `fma` (the - /// driver's measured deviation - /// [`DriverDeviation::MetalHalfFma`](crate::error::DriverDeviation::MetalHalfFma)). No Vulkan - /// query reports it. A module whose `half` fused multiply-add takes that instruction requires - /// it; without it, the fused multiply-add is a 16-bit `OpFmaKHR` under the 16-bit float - /// controls, or the device's `float` `Fma` rounded to `half` - /// (`PrecisionNote::NativeFma`). - MetalHalfFma, - /// The device's `float` arithmetic, comparisons, `Ldexp`, `Sqrt`, `InverseSqrt`, `Trunc` and - /// `RoundEven` read an `f32` denormal operand as the zero of its sign and flush a denormal - /// result, as Metal does - /// (the driver's measured deviation - /// [`DriverDeviation::MetalFloatDenormals`](crate::error::DriverDeviation::MetalFloatDenormals)). - /// No Vulkan query reports it: `DenormFlushToZero` makes only the results' flush a - /// requirement, the operands' remains the device's choice. A module that leaves such an - /// operation's denormals to the device, recording no `PrecisionNote::DeviceDenormals` for it, - /// requires it; without it, they are the device's own, and the module records that note. So - /// does a module whose entry declares the 16-bit float controls, on every device, as a driver - /// may keep `f32` denormals there (NVIDIA's on the RTX 3090 and the RTX 5080 Laptop GPU); it - /// requires no such property. - MetalFloatDenormals, /// The device reads a center-sampled varying of a multisampled pipeline at the pixel center /// in every fragment invocation, a sample-rate one's included, as Metal does (the driver's /// measured deviation @@ -669,24 +648,6 @@ pub enum VkProperty { /// pixel form, requires it; without it, their pixel form is `InterpolateAtOffset` at offset /// 0, which requires [`VkProperty::InterpolateAtOffsetCentered`]. MetalCenterVaryings, - /// The device's `GLSL.std.450` `NMin`, `NMax` and `NClamp` on 32-bit floats are Metal's own - /// `fmin`, `fmax` and `clamp` (the driver's measured deviation - /// [`DriverDeviation::MetalMinMax`](crate::error::DriverDeviation::MetalMinMax)). No Vulkan - /// query reports it. Every `float` or `half` minimum, maximum or clamp takes those - /// instructions: a module that does requires it, and without it the module records - /// `PrecisionNote::NativeMinMax`. - MetalMinMax, - /// The device's 16-bit `OpFAdd` and `OpFSub` decorated `NoContraction`, and its 16-bit - /// `Fma(a, b, -0.0)` decorated `NoContraction`, are Metal's own `half` `+`, `-` and `*` (the - /// driver's measured deviation - /// [`DriverDeviation::MetalHalfArithmetic`](crate::error::DriverDeviation::MetalHalfArithmetic)). - /// No Vulkan query reports it. A module whose `half` `+`, `-` or `*` takes those instructions - /// requires it; without it, the module takes them under the 16-bit float controls, or - /// computes in `float` and rounds the result to `half` as every `half` rounds. A module that - /// reads a `half` from its bits by the device's widening, outside the 16-bit float controls, - /// requires it too: the measurement reads every `half` through that widening, denormals - /// included; without it the module records `PrecisionNote::NativeHalfConversion`. - MetalHalfArithmetic, /// The device stores every `float` but a NaN that a shader writes to a half-float storage /// image as Metal stores a kernel's write, rounded toward zero (the driver's measured /// deviation @@ -803,34 +764,6 @@ pub enum VkProperty { /// requires it, where no module does (the coverage is the pipeline's multisample state); /// without it, the pipeline's fragment stage records that note. MetalAlphaCoverage, - /// The device's widening and narrowing between 16- and 32-bit floats, and its `OpFNegate` - /// and `FAbs`, answer Metal's NaN bits (the driver's measured deviation - /// [`DriverDeviation::MetalNanMoves`](crate::error::DriverDeviation::MetalNanMoves)). No Vulkan - /// query reports it: Vulkan states no NaN's bits. A module that reads a `half` from its bits or - /// encodes one to them, widens a `half` to `float`, negates a `float` or takes the magnitude - /// of a `float` or `half`, and records no - /// [`PrecisionNote::NativeNanEncoding`](crate::pipeline::PrecisionNote::NativeNanEncoding) - /// for it requires it. - MetalNanMoves, - /// The device's conversions of the packed normalized formats measured to answer Metal's - /// (the driver's measured deviation - /// [`DriverDeviation::MetalPackConversions`](crate::error::DriverDeviation::MetalPackConversions)). - /// No Vulkan query reports it: Vulkan leaves the conversions' rounding to the device. A - /// module that converts one of those forms and records no - /// [`PrecisionNote::DevicePackConversion`](crate::pipeline::PrecisionNote::DevicePackConversion) - /// for it requires it. - MetalPackConversions, - /// The device's conversion of a 32-bit float to 16 bits answers Metal's `half(float)` where - /// the module converts a `float` it holds, and Metal's own `half` texel where the `float` is - /// an image instruction's texel (the driver's measured deviation - /// [`DriverDeviation::MetalHalfConversion`](crate::error::DriverDeviation::MetalHalfConversion)). - /// No Vulkan query reports it: without the float controls Vulkan leaves the conversion's - /// rounding to the device. A module that rounds a `half` through that conversion in those - /// forms alone (a texel's value among them: one the module decodes itself, or a merge of - /// texels) records no - /// [`PrecisionNote::NativeHalfConversion`](crate::pipeline::PrecisionNote::NativeHalfConversion) - /// and requires it. - MetalHalfConversion, /// The device stores a NaN a shader writes to a packed small float storage image /// (`B10G11R11_UFLOAT_PACK32`) as Metal stores it, a `float`'s or a `half`'s widened (the /// driver's measured deviation @@ -839,15 +772,6 @@ pub enum VkProperty { /// [`PrecisionNote::DeviceNanEncoding`](crate::pipeline::PrecisionNote::DeviceNanEncoding) /// for it and requires it. MetalSmallFloatNans, - /// The device's `float` `OpFNegate` and `FAbs` keep an `f32` denormal and its `Floor` and - /// `Ceil` read one as the zero of its sign, as Metal's `-x`, `fabs`, `floor` and `ceil` do (the - /// driver's measured deviation - /// [`DriverDeviation::MetalUnaryDenormals`](crate::error::DriverDeviation::MetalUnaryDenormals)). - /// Vulkan lets a device keep or flush them. A module that leaves those operations' denormals to - /// the device records no - /// [`PrecisionNote::DeviceDenormals`](crate::pipeline::PrecisionNote::DeviceDenormals) for - /// them and requires it. - MetalUnaryDenormals, /// `GLSL.std.450 InterpolateAtOffset` at offset `v` reads Metal's `interpolate_at_offset` at /// `v + 7/16`, measured from the pixel's upper-left corner: a device whose description reports /// a MoltenVK driver, whose SPIRV-Cross hands the instruction to Metal so at any release diff --git a/crates/metal2vulkan/src/device/tests/from_queries.rs b/crates/metal2vulkan/src/device/tests/from_queries.rs index 467a0960f..b4e7bec34 100644 --- a/crates/metal2vulkan/src/device/tests/from_queries.rs +++ b/crates/metal2vulkan/src/device/tests/from_queries.rs @@ -134,12 +134,6 @@ entry: !5 = !{i32 2, !"air.thread_position_in_grid", !"air.arg_type_name", !"uint", !"air.arg_name", !"gid"} "#; -/// On every committed profile `Device::from_queries` derives, a kernel's `float` product beside a -/// `half` one ([`MIXED_PRODUCTS`]) records `PrecisionNote::DeviceDenormals` and requires no -/// `VkProperty::MetalFloatDenormals`, whether its entry declares the 16-bit float controls (where -/// the device computes the `half` product in 16 bits) or not: no Vulkan query states that a -/// device reads an `f32` denormal as Metal does, and a driver may keep one under the 16-bit -/// controls, so the note is static. /// A device whose `maxPushConstantsSize` is below the 256 bytes of the push window every stage is /// lowered for is below the floor: `Unsupported{PushWindow}`, needing `MaxPushConstantsSize` 256. /// The descriptions below it are committed apart (`validation/profiles/below-floor/`, this test's @@ -180,9 +174,13 @@ fn a_push_window_below_256_bytes_is_below_the_floor() { } } +/// On every committed profile `Device::from_queries` derives, a kernel's `float` product beside a +/// `half` one ([`MIXED_PRODUCTS`]) records `PrecisionNote::DeviceDenormals`, whether its entry +/// declares the 16-bit float controls (where the device computes the `half` product in 16 bits) or +/// not: no Vulkan query states that a device reads an `f32` denormal as Metal does, and a driver +/// may keep one under the 16-bit controls, so the note is static. #[test] fn from_queries_records_the_device_denormals_of_a_float_product() { - use crate::device::requirements::VkProperty; use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::testing::{compile, llvm_assemble_text, AssembleError}; let bc = match llvm_assemble_text(MIXED_PRODUCTS) { @@ -204,10 +202,6 @@ fn from_queries_records_the_device_denormals_of_a_float_product() { a.precision.contains(&PrecisionNote::DeviceDenormals), "{stem}" ); - assert!( - !(a.requirements.properties).contains(&VkProperty::MetalFloatDenormals), - "{stem}" - ); compiled += 1; } assert!(compiled >= 10, "{compiled} profiles compiled the kernel"); diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index 6d18e9902..2d20929bc 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -501,16 +501,6 @@ pub enum DriverDeviation { /// an Apple GPU runs a Metal simdgroup (`VkProperty::SimdgroupLockstep`). Unmeasured, a kernel /// that needs that order takes emulated simdgroups, exact. SimdgroupLockstep, - /// The device computes each `GLSL.std.450` function and `OpFDiv` of `float` as Metal's own, - /// in the math mode Metal compiles the module with (`FloatFunctions::Metal`). Unmeasured, the - /// module takes the device's instructions all the same, each kind recorded with its bound - /// (`PrecisionNote::NativeTranscendentals`, and `NativeDivision`, `NativeDot` and `NativeMix` - /// for a division, a `dot` and a `mix`). - MetalFloatFunctions, - /// The device's `float` and `half` arithmetic answers Metal's canonical NaN - /// (`NanEncoding::MetalCanonical`). The module leaves every NaN's bits to the device either - /// way; unmeasured, a NaN Metal answers records `PrecisionNote::NativeNanEncoding`. - MetalCanonicalNans, /// The device samples, filters and converts texels through Metal's own sampler /// (`VkProperty::MetalSampler`), an 8-bit sRGB texel's decode included. Unmeasured, every /// sample, gather, comparison and level query is the device's own sampler's all the same @@ -527,23 +517,6 @@ pub enum DriverDeviation { /// two tangents: an `x` or `z` face's gradient reaches it as Metal's own, a `y` face's `z` /// tangent is lost. Unmeasured, as [`DriverDeviation::CubeGradientRoute`]. GraphicsCubeGradientTangents, - /// The device's `GLSL.std.450 Fma` on 16-bit floats is Metal's own `half` `fma`, which - /// rounds the exact `a * b + c` once (`VkProperty::MetalHalfFma`). Where the profile also has - /// `shaderFloat16`, a `half` fused multiply-add converts its operands (each a `half`, so - /// exactly) to 16 bits, takes the device's `Fma` and widens its result. Unmeasured, it takes - /// `OpFmaKHR` on 16 bits where the profile has `shaderFmaFloat16` and rounds to `half` under - /// the 16-bit float controls, and elsewhere the device's `float` `Fma` rounded to `half`, - /// recorded as `PrecisionNote::NativeFma`. - MetalHalfFma, - /// The device's `float` arithmetic reads an `f32` denormal operand as the zero of its sign - /// and flushes a denormal result to one, as Metal does (`VkProperty::MetalFloatDenormals`): - /// `OpFAdd`, `OpFSub`, `OpFMul`, `OpFmaKHR`, `OpDot`, the comparisons, and `GLSL.std.450`'s - /// `Ldexp`, `Sqrt`, `InverseSqrt`, `Trunc` and `RoundEven`. Measured in entries that declare - /// no float-controls mode: in an entry that declares the 16-bit float controls a driver may - /// keep them, and no query tells which, so there they are the device's own on every device. - /// Unmeasured, or in such an entry, such operands and results are the device's own, recorded - /// as `PrecisionNote::DeviceDenormals`. - MetalFloatDenormals, /// The device reads a center-sampled varying (a smooth input decorated neither `Centroid` /// nor `Sample`) of a multisampled pipeline at the pixel center in every fragment /// invocation, a sample-rate one's included, as Metal reads it @@ -554,37 +527,6 @@ pub enum DriverDeviation { /// that reads from the center (`VkProperty::InterpolateAtOffsetCentered`), and a function that /// runs per sample is refused elsewhere. MetalCenterVaryings, - /// The device's `GLSL.std.450` `NMin`, `NMax` and `NClamp` on 32-bit floats are Metal's own - /// `fmin`, `fmax` and `clamp` (`VkProperty::MetalMinMax`): a NaN operand loses, two NaNs and a - /// tie answer the second operand's bits, an `f32` denormal compares as a zero but is returned - /// itself, and `clamp(x, lo, hi)` is `fmin(fmax(x, lo), hi)`, in every math mode, of every - /// operand class, and of every `half` held widened. Metal's `fmin`, `fmax`, `min3`, `max3`, - /// `clamp` and `saturate` on `float` and `half` are those instructions on every profile: where - /// the profile takes it the module requires the property, and unmeasured it records - /// `PrecisionNote::NativeMinMax`. - MetalMinMax, - /// The device's 16-bit `OpFAdd` and `OpFSub` decorated `NoContraction`, and its 16-bit - /// `Fma(a, b, -0.0)` decorated `NoContraction`, are Metal's own `half` `+`, `-` and `*` - /// (`VkProperty::MetalHalfArithmetic`), with operands narrowed from `float` and the result - /// widened back: the exact result rounded once to nearest even on the `half` grid, `half` - /// denormals kept, an exact zero sum `+0` unless both addends are `-0`, and every NaN result - /// `0x7E00`, in every math mode. Where the profile also has `shaderFloat16`, a `half` `fadd`, - /// `fsub` or `fmul` converts its operands (each a `half`, so exactly) to 16 bits, takes that - /// kept instruction and widens its result; one whose flags carry `contract` and `reassoc` takes - /// the instruction undecorated instead, the AIR's own contraction, outside the measurement - /// (Metal's fast compile folds its conversions away, `PrecisionNote::FastMathRewrites`), and - /// requires nothing for it. Unmeasured, it takes the same instruction under the - /// 16-bit float controls that make it Metal's by the Vulkan spec (`QuantizeForm::Controlled`), - /// and elsewhere computes the result in `float` and rounds it to `half` as every `half` - /// rounds (`narrow::round`, noted `NativeHalfConversion` or `NativeHalfQuantize` where that - /// rounding is not Metal's). The measurement reads every `half` through the device's - /// widening (`x + -0` of every `x`), exact but for a NaN, denormals included: a module that - /// reads a `half` from its bits by that widening (every profile with `shaderFloat16` does) - /// requires the property for its denormals, and records `PrecisionNote::NativeNanEncoding` - /// for its NaNs' bits but where the profile takes [`MetalNanMoves`]. - /// - /// [`MetalNanMoves`]: DriverDeviation::MetalNanMoves - MetalHalfArithmetic, /// The device stores every `float` but a NaN that a shader writes to a half-float storage /// image (`R16Float`, `RG16Float`, `RGBA16Float`; a storage texel buffer of one too) as Metal /// stores a kernel's write (`VkProperty::MetalHalfStorageWrites`): rounded toward zero, a @@ -710,71 +652,13 @@ pub enum DriverDeviation { /// alpha records no `PrecisionNote::DeviceAlphaCoverage` and requires the property. /// Unmeasured, such a pipeline's fragment stage records the note. MetalAlphaCoverage, - /// The device's operations that move a `float` or `half` NaN, rather than compute one, answer - /// Metal's bits (`VkProperty::MetalNanMoves`): its widening of a 16-bit float to 32 bits - /// (`OpFConvert`) answers `0x7FC00000` for every `half` NaN, as Metal's `float(half)` does; - /// its narrowing of a 32-bit float to 16 bits answers Metal's `half` NaN, and its narrowing of - /// such a widening, moved through the registers (selects, phis, a function's `float` - /// variable), which the driver's compiler folds, the `half`'s own bits, as Metal's moves of a - /// `half` keep them; its `OpFNegate` and `FAbs` of a `float` keep a NaN's payload with the sign - /// flipped or cleared, as Metal's `fneg` and `fabs` do; and its `FAbs` of a `half` held - /// widened answers the canonical NaN, as Metal's `half` `fabs` does. Where the profile takes - /// it, a module that reads a `half` from its bits or encodes one to them, a `half`'s widening - /// to `float` and a `half` `fabs` record no `PrecisionNote::NativeNanEncoding` and the module - /// requires the property, but where the module carries a widened `half` out of the registers - /// (a store to a stage output or another variable, a call, a group, atomic or image operation) - /// or reads its bits before narrowing it, or holds a `float` NaN constant other than - /// `0x7FC00000`, which the measurement does not cover (`narrow::moves_unfolded`): there each - /// records the note. A `float` `fneg` and `fabs` record none and require the property. A `half` - /// `fneg` records the note on every profile: the device negates the held `float`, whose NaN - /// keeps its flipped sign unless the driver's compiler moves the negation onto the `half`. - /// Unmeasured, each records it. - MetalNanMoves, - /// The device's conversions of Metal's packed normalized formats outside the four - /// `GLSL.std.450` names in `float` answer Metal's codes and values - /// (`VkProperty::MetalPackConversions`): `unpack_unorm565_to_float` and - /// `pack_float_to_unorm565`, and the `half` forms of `unorm4x8`, `snorm4x8` and `unorm10a2` - /// (both ways), `unorm565` (both ways) and `unorm2x16` and `snorm2x16` (packing). The module - /// takes each as it does on every profile (the format's `GLSL.std.450` instruction, or its - /// definition on the format's fields, around a `half`'s widening or rounding); where the - /// profile takes this deviation, each records no `PrecisionNote::DevicePackConversion` and - /// the module requires the property. The sRGB format, `unorm10a2` in `float`, `snorm10a2`, and - /// the `half` unpacks of `unorm2x16` and `snorm2x16` stay noted. Unmeasured, each records it. - MetalPackConversions, - /// The device's conversion of a 32-bit float to 16 bits, `OpFConvert` (MSL's `half(x)` - /// through MoltenVK), answers Metal's (`VkProperty::MetalHalfConversion`): Metal's - /// `half(float)` (to nearest even on the `half` grid, `half` denormals kept, infinity from - /// 65520 up) of every `float` a function converts, whatever instruction computed it, and, - /// where the `float` is an image instruction's texel, Metal's own `half` result of that access, - /// into which Metal's compiler folds the conversion. Where the profile takes it, a module whose - /// every `half` rounding through that conversion (`QuantizeForm::Converted`) is a conversion of - /// a `float` the function holds (an AIR `fptrunc` or `air.convert` from `float`) or of a - /// texel's value (an image instruction's texel, one the module decodes itself, or a merge of - /// them, whose `half` the access's own texel notes state against Metal's) records no - /// `PrecisionNote::NativeHalfConversion` and requires the property. A `half` a function or an - /// operation computes in `float` and rounds - /// keeps the note on every profile: Metal computes it otherwise (its `half` `tanh` answers 7 - /// of the 65,536 `half`s otherwise than the nearest even `half` of its `float` `tanh`, which the - /// device's conversion answers). Unmeasured, each records it. - MetalHalfConversion, /// The device stores the NaN a shader writes to a packed small float storage image /// (`B10G11R11_UFLOAT_PACK32`, Metal's `RG11B10Float`) as Metal stores the same write: a /// `float` texel's NaN, whatever its sign and payload, and a `half` texel's, handed to the /// device widened (`VkProperty::MetalSmallFloatNans`). Where the profile takes it, a write that /// may reach such an image records no `PrecisionNote::DeviceNanEncoding` for it and the module - /// requires the property; with [`DriverDeviation::MetalNanMoves`], whose widening of a `half` - /// answers Metal's, a widened `half` written there moves its NaN as measured - /// (`lower::arith::narrow::moves_unfolded`). Unmeasured, the write records the note. + /// requires the property. Unmeasured, the write records the note. MetalSmallFloatNans, - /// The device's `float` negation, absolute value, floor and ceiling (`OpFNegate`, `FAbs`, - /// `Floor` and `Ceil`) read an `f32` denormal as Metal does (`VkProperty::MetalUnaryDenormals`): - /// a negation and an absolute value move the sign bit alone, keeping the denormal, and a floor - /// and a ceiling read it as the zero of its sign (`floor(-2^-149)` is `-0`, `ceil(2^-149)` is - /// `+0`). Where the profile takes it, those operations record no - /// `PrecisionNote::DeviceDenormals` and the module requires the property. A texel centre's - /// `floor` stays noted where its address mode parts texel -1 from texel 0: Metal's sampler - /// reads its coordinate unflushed. Unmeasured, each records the note. - MetalUnaryDenormals, } /// One device capability a refusal can name. diff --git a/crates/metal2vulkan/src/lower/access/tile.rs b/crates/metal2vulkan/src/lower/access/tile.rs index a6e54766b..cc86f9df3 100644 --- a/crates/metal2vulkan/src/lower/access/tile.rs +++ b/crates/metal2vulkan/src/lower/access/tile.rs @@ -118,7 +118,6 @@ use std::collections::{BTreeMap, BTreeSet}; use crate::air::abi::{ImageblockArg, ImageblockKind, ParamBinding, ParamRole}; use crate::air::intrinsics::{Imageblock, PackDir, PackFormat}; use crate::air::ir::{Call, Const, Value}; -use crate::device::profile::FloatFunctions; use crate::device::requirements::{FormatUsage, VkFeature}; use crate::error::{ Attachment, Capability, DescriptorError, Error, Feature, MetalAnswer, RuntimeInput, Unsupported, @@ -878,20 +877,9 @@ pub(super) fn select_texel( slot.staged = true; slot.stored |= store; let (offset, leaf) = (slot.offset, slot.leaf); - // The device's conversion, but a `float` one of a format `GLSL.std.450` names on a device - // whose `float` functions are Metal's (Metal's own `pack_float_to_*` and `unpack_*_to_float`, - // as `air.pack`'s strategy notes it); a `half` load rounds the unpacked `float` once more. - if let Some(n) = norm { - let dir = match store { - true => PackDir::Pack, - false => PackDir::Unpack, - }; - let own = cx.profile.fields().float_functions == FloatFunctions::Metal - && (store || !n.half) - && pack::instruction(n.norm.format, dir).is_some(); - if !own { - cx.precision.insert(PrecisionNote::DevicePackConversion); - } + // The device's conversion; a `half` load rounds the unpacked `float` once more. + if norm.is_some() { + cx.precision.insert(PrecisionNote::DevicePackConversion); } imageblock::place_region(cx, cell_bytes)?; let coord = imageblock::operand(cx, coord)?; diff --git a/crates/metal2vulkan/src/lower/arith/denormal.rs b/crates/metal2vulkan/src/lower/arith/denormal.rs index 6c5623df6..70d091f3a 100644 --- a/crates/metal2vulkan/src/lower/arith/denormal.rs +++ b/crates/metal2vulkan/src/lower/arith/denormal.rs @@ -1,81 +1,19 @@ -//! How Metal reads `f32` denormals, per operation, against the device: where the device reads them -//! as Metal does, an `f32` denormal operand as the zero of its sign and a denormal result flushed -//! to one (`DriverDeviation::MetalFloatDenormals`, a measured driver fact), or, for a negation, an -//! absolute value, a floor and a ceiling, as Metal's (`DriverDeviation::MetalUnaryDenormals`), -//! the module leaves them to it and requires the property; elsewhere they are the device's own, -//! noted (`PrecisionNote::DeviceDenormals`). Only `float` operations are listed: a widened `half` is -//! never an `f32` denormal, and Metal's `bfloat` and `double` environments are not measured. +//! How Metal reads `f32` denormals, per operation, against the device: Metal reads an `f32` +//! denormal operand as the zero of its sign and flushes a denormal result to one, where the device +//! keeps or flushes them by its own float controls, noted (`PrecisionNote::DeviceDenormals`). Only +//! `float` operations are listed: a widened `half` is never an `f32` denormal, and Metal's `bfloat` +//! and `double` environments are not measured. -use crate::device::DeviceProfile; -use crate::error::DriverDeviation; use crate::lower::arith::math::FloatFn; -/// Whether profile `p`'s device reads the denormals of the operations [`Covered::Deviation`] -/// names as Metal does: an `f32` denormal operand as the zero of its sign, a denormal result -/// flushed to one (`DriverDeviation::MetalFloatDenormals`, a measured driver fact). Elsewhere -/// they are the device's own (`PrecisionNote::DeviceDenormals`). -pub fn device_flushes(p: &DeviceProfile) -> bool { - p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals) -} - -/// Whether profile `p`'s device reads the denormals of the operations [`Covered::Unary`] names as -/// Metal does: a negation and an absolute value keep one, a floor and a ceiling read one as the -/// zero of its sign (`DriverDeviation::MetalUnaryDenormals`, a measured driver fact). Elsewhere -/// they are the device's own (`PrecisionNote::DeviceDenormals`). -pub fn unary_kept(p: &DeviceProfile) -> bool { - p.takes_driver_deviation(DriverDeviation::MetalUnaryDenormals) -} - -/// Where an operation the device computes reads its `f32` denormals as Metal does. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum Covered { - /// On a device with the measured deviation ([`device_flushes`]); elsewhere they are the - /// device's own. - Deviation, - /// On a device with the measured deviation of the sign moves and the floor and ceiling - /// ([`unary_kept`]); elsewhere they are the device's own. `Floor` and `Ceil` of a denormal - /// give `-1` and `1` on NVIDIA's 615.71.09 and on lavapipe, where Metal reads the operand as a - /// zero (`floor(-2^-149)` is `-0`, `ceil(2^-149)` is `+0`), and RADV and ANV flush a negated - /// one, which Metal keeps. - Unary, - /// On no device measured: the device's own on every profile (a quotient). - Never, -} - -impl Covered { - /// Whether a device whose readings `flushes` ([`device_flushes`]) and `unary` - /// ([`unary_kept`]) state reads an operation of this class's denormals as Metal does. - pub fn holds(self, flushes: bool, unary: bool) -> bool { - match self { - Covered::Deviation => flushes, - Covered::Unary => unary, - Covered::Never => false, - } - } -} - -/// Whether float function `op` moves its operand's sign bit alone, keeping a denormal where Metal's -/// does on a device measured to ([`Covered::Unary`]): `fabs`. Its notes otherwise follow the -/// device's own functions (`function_notes`). -pub fn moves_sign(op: FloatFn) -> bool { - op == FloatFn::Abs -} - -/// Where the device's instruction for float function `op` (on `float` lanes, where the lowering -/// leaves `op` to it) reads `f32` denormals as Metal, which reads each `float` operand of these -/// as the zero of its sign and flushes a denormal result (the denormal probes, `nan_denormals` -/// and `nan_denormals_fast`, every lane). `None` for a function whose lowering reads its -/// denormals as Metal does itself (`FloatFn::metal_denormals`) or whose reading is not measured. -/// -/// | function | where the device's reading is Metal's | -/// |---|---| -/// | `floor`, `ceil` | the unary deviation | -/// | `trunc`, `rint` | the deviation | -/// | `sqrt`, `rsqrt`, `fast::rsqrt` | the deviation | -/// | `dot` | the deviation | -/// | `fma`, `llvm.fmuladd` (`OpFmaKHR`) | the deviation | -/// | `fast::atan2` | the deviation | -/// | `ldexp` on `float` | the deviation | +/// Whether Metal's reading of the `f32` denormals of float function `op` (on `float` lanes, where +/// the lowering leaves `op` to the device's instruction) is measured: Metal reads each `float` +/// operand of these as the zero of its sign and flushes a denormal result (the denormal probes, +/// `nan_denormals` and `nan_denormals_fast`, every lane), where the device's reading is its own, +/// noted `DeviceDenormals`. False for a function whose lowering reads its denormals as Metal does +/// itself (`FloatFn::metal_denormals`) or whose reading is not measured. The functions: `floor`, +/// `ceil`, `trunc`, `rint`, `sqrt`, `rsqrt`, `fast::rsqrt`, `dot`, `fma` and `llvm.fmuladd` +/// (`OpFmaKHR`), `fast::atan2`, and `ldexp` on `float`. /// /// `fast::atan2(y, x)` reads a denormal `y` or `x` as the zero of its sign and answers no denormal /// (an Apple M3 Max under macOS 27.0.1: every pair of 28 patterns, in entries with and without fast @@ -84,26 +22,27 @@ pub fn moves_sign(op: FloatFn) -> bool { /// past `2^126`; a denormal quotient reaches the fast `atan`, which reads it as a zero. /// /// `ldexp` on `float` (`math::ldexp_bits`) reads a denormal operand and rounds a result below -/// `2^-126` by the device's `float` multiply, which the deviation covers: a denormal operand times +/// `2^-126` by the device's `float` multiply: a denormal operand times /// `2^64`, and a normal times `2^-126`. /// /// `trunc` and `rint` (`Trunc`, `RoundEven`) of a denormal answer the zero of its sign on every /// venue measured, as Metal does (the probes' words, both modes, all seven venues), but Vulkan -/// states no sign for a flushed denormal, so only the deviation covers them. -pub fn coverage(op: FloatFn) -> Option { +/// states no sign for a flushed denormal, so the device's is noted. +pub fn covered(op: FloatFn) -> bool { use FloatFn as F; - Some(match op { - F::Floor | F::Ceil => Covered::Unary, - F::Trunc - | F::Rint - | F::Sqrt - | F::Rsqrt - | F::FastRsqrt - | F::Dot - | F::Fma - | F::MulAdd - | F::FastAtan2 { .. } - | F::Ldexp => Covered::Deviation, - _ => return None, - }) + matches!( + op, + F::Floor + | F::Ceil + | F::Trunc + | F::Rint + | F::Sqrt + | F::Rsqrt + | F::FastRsqrt + | F::Dot + | F::Fma + | F::MulAdd + | F::FastAtan2 { .. } + | F::Ldexp + ) } diff --git a/crates/metal2vulkan/src/lower/arith/libm/mod.rs b/crates/metal2vulkan/src/lower/arith/libm/mod.rs index cfa64ea24..6604d4440 100644 --- a/crates/metal2vulkan/src/lower/arith/libm/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/libm/mod.rs @@ -14,16 +14,11 @@ //! (`PrecisionNote::NativeTranscendentals`). No routine computes Metal's answer where the device //! has an instruction, and no select reads a special operand as Metal does where the device's //! instruction answers it: the selects around `pow`, `powr` and `atan2` give only the C99 and MSL -//! values `GLSL.std.450` leaves undefined, by the device's comparisons. Where the device is -//! Metal's own -//! (`FloatFunctions::Metal`: MoltenVK on an Apple GPU), its instruction is Metal's function in the -//! math mode Metal compiles the module with ([`module_mode`]), so a call in that mode is Metal's -//! own answer there ([`Fun::device_answers`]), which the notes read. +//! values `GLSL.std.450` leaves undefined, by the device's comparisons. //! //! Precise `fmod` keeps its routine: the device's form, `OpFRem` (`x - y · trunc(x / y)` at the //! device's precision), Vulkan leaves unbounded once the quotient passes `2^24`, where Metal's is -//! exact. Where the device is Metal's own, a precise module's `OpFRem` is Metal's `fmod`, and takes -//! no routine ([`Fun::device_answers`]). +//! exact. pub(crate) mod fmod; @@ -39,36 +34,17 @@ use crate::spirv::ir::{BinOp, Contraction, ConvOp, Type}; /// The quiet NaN Metal answers at precise `fmod`'s domain errors ([`E::metal_nan`]). pub(crate) const METAL_NAN: u32 = 0x7FC0_0000; -/// A math mode: Metal's precise functions (MSL Table 8.1) or its fast ones (Table 8.2). -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum Mode { - Precise, - Fast, -} - -/// The mode Metal compiles the `float` functions of an entry in on a device whose functions are -/// Metal's (MoltenVK: `MVKDevice::getMTLCompileOptions` under its default on-demand fast math): -/// precise where the entry declares a `SignedZeroInfNanPreserve` execution mode of any width -/// (`declared`, the widths [`super::ArithPlan::modes`] holds), fast otherwise. -pub fn module_mode(declared: &std::collections::BTreeSet) -> Mode { - if declared.is_empty() { - Mode::Fast - } else { - Mode::Precise - } -} - /// A function of Metal's math library on `float` operands, as a call of a float function takes it /// ([`uses`]): one whose answer the device's instruction may give otherwise than Metal, beyond /// Vulkan's precision table, or a part of one. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum Fun { - /// Metal's `atan` in a mode: within 5 ulp in both (Tables 8.1 and 8.2). - Atan(Mode), - /// Metal's `asin` in a mode: within 4 ulp precise, 5 fast. - Asin(Mode), - /// Metal's `acos` in a mode: within 4 ulp precise, 5 fast. - Acos(Mode), + /// Metal's `atan`, precise or fast: within 5 ulp in both (Tables 8.1 and 8.2). + Atan, + /// Metal's `asin`, precise or fast: within 4 ulp precise, 5 fast. + Asin, + /// Metal's `acos`, precise or fast: within 4 ulp precise, 5 fast. + Acos, /// The generic part of Metal's precise `atan2(y, x)` (within 6 ulp): finite nonzero normal /// operands, whose special values `math::atan2_special` answers around it. Atan2, @@ -94,13 +70,12 @@ pub enum Fun { /// Metal's fast `atanh`, MSL Table 8.2's `0.5 · log((1 + x) / (1 - x))`. FastAtanh, /// Metal's `sinpi`, for a precise call (`air.sinpi`) or a fast one (`air.fast_sinpi`): Metal's - /// fast function is its precise one, and only a device whose functions are Metal's tells them - /// apart ([`Fun::device_answers`]). - SinPi(Mode), + /// fast function is its precise one. + SinPi, /// Metal's `cospi`, as [`Fun::SinPi`]. - CosPi(Mode), + CosPi, /// Metal's `tanpi`, as [`Fun::SinPi`]. - TanPi(Mode), + TanPi, /// Metal's precise `sqrt`: correctly rounded (MSL Tables 8.1 and 8.3). Sqrt, /// Metal's precise `rsqrt`: correctly rounded (Tables 8.1 and 8.3). @@ -174,88 +149,6 @@ pub enum Fun { } impl Fun { - /// Whether a device whose `float` functions are Metal's answers `self` with its own - /// instruction as Metal's function in an entry whose functions Metal compiles in mode - /// `module`: the instruction is Metal's function in that mode, and `atan2` is always the - /// precise one (SPIRV-Cross emits `precise::atan2` whatever the flags). The precise-only - /// functions (`sin`, `cos`, `tan`, `sqrt`, `rsqrt`, and `fmod`, whose fast calls are their own - /// functions) are Metal's only in a precise module. Metal's fast `sin`, `cos`, `tan`, `sinh`, - /// `cosh` and `atanh` are the device's `Sin`, `Cos`, `Tan`, `Sinh`, `Cosh` and `Atanh` in a - /// fast-math module only (in a precise one those are Metal's precise functions, which differ: - /// `fast::sin` is `+0` past its flush point), and its fast `tanh` in none (SPIRV-Cross emits - /// `precise::tanh`, below). Metal's `sinpi`, `cospi`, - /// and `tanpi` are none of the instructions SPIRV-Cross emits (it emits no `sinpi`), so the - /// device's `Sin` and `Cos` of `float(π) r` answer a precise call otherwise than Metal (849, - /// 922 and 637 of case 087758cb's 1,024 lanes matched); a fast call is that composition, in - /// either mode, within Apple's fast bound (MSL Table 8.2) and off Metal's own form - /// ([`Fun::device_near_equivalent`]). - /// - /// `exp2` and `log2` are Metal's in either mode (Metal's fast ones are its precise ones), and - /// so is `tanh` (SPIRV-Cross emits `precise::tanh` whatever the flags); `powr` and the other - /// hyperbolic functions, `exp` and `log` only in a precise module. No `GLSL.std.450` - /// instruction reaches Metal's `exp10` and `log10`, but Metal's own compositions of its `exp2` - /// and `log2` do, in either mode (`math::exp10`, `math::log10`). Its reciprocal is the - /// device's `1 / y` in a fast-math module, where Metal - /// compiles the division with its fast reciprocal, and not in a precise one, whose quotient is - /// correctly rounded. The device's instruction on a `half` held as `float` is its `float` - /// function, never Metal's `half` form. - pub fn device_answers(self, module: Mode) -> bool { - match self { - Fun::FastSin - | Fun::FastCos - | Fun::FastTan - | Fun::FastSinh - | Fun::FastCosh - | Fun::FastAtanh => module == Mode::Fast, - Fun::FastTanh => false, - Fun::SinPi(m) | Fun::CosPi(m) | Fun::TanPi(m) => m == Mode::Fast, - Fun::Atan(m) | Fun::Asin(m) | Fun::Acos(m) => m == module, - Fun::Sin - | Fun::Cos - | Fun::Tan - | Fun::Sqrt - | Fun::Rsqrt - | Fun::Fmod - | Fun::Powr - | Fun::Exp - | Fun::Log - | Fun::Sinh - | Fun::Cosh - | Fun::Asinh - | Fun::Acosh - | Fun::Atanh => module == Mode::Precise, - // Metal's fast `asinh` and `acosh` are the device's `Asinh` and `Acosh` in a fast-math - // module. - Fun::Recip | Fun::FastAsinh | Fun::FastAcosh => module == Mode::Fast, - Fun::HalfAtan - | Fun::HalfAtan2 - | Fun::HalfTan - | Fun::HalfSin - | Fun::HalfCos - | Fun::HalfAsinh - | Fun::HalfExp - | Fun::HalfLog - | Fun::HalfPowr - | Fun::HalfSinh - | Fun::HalfCosh - | Fun::HalfTanh => false, - Fun::Atan2 | Fun::Exp2 | Fun::Log2 | Fun::Tanh | Fun::Exp10 | Fun::Log10 => true, - } - } - - /// Whether the device answers the function, where it does ([`Fun::device_answers`]), by a - /// near-equivalent of Metal's function rather than by Metal's function itself: Metal's fast - /// `sinpi`, `cospi`, and `tanpi`, which the device answers by its `Sin` and `Cos` of - /// `float(π) r`, within Apple's fast bound but off Metal's own forms (case f6524207 differs at - /// 175, 102, and 264 of its 1,024 lanes through MoltenVK). Every other function the device - /// answers is Metal's own, word for word (`DriverDeviation::MetalFloatFunctions`). - pub fn device_near_equivalent(self) -> bool { - matches!( - self, - Fun::SinPi(Mode::Fast) | Fun::CosPi(Mode::Fast) | Fun::TanPi(Mode::Fast) - ) - } - /// Whether the call takes the device's instruction for the function: every function but /// precise `fmod`, whose routine computes Metal's exact remainder ([`fmod`]). Its /// precision is Vulkan's (`PrecisionNote::NativeTranscendentals`). @@ -264,8 +157,7 @@ impl Fun { } /// Whether Metal's answer to the function is the one right value at every operand, so that - /// the routine's answer, and the device's where it is Metal's own ([`Fun::device_answers`]), is - /// Metal's on every device in either math mode: precise `fmod`, which Metal documents exact + /// the routine's answer is Metal's on every device in either math mode: precise `fmod`, which Metal documents exact /// (MSL Table 8.1 for `float`, Table 8.3 for `half`), and which its routine computes. pub fn correctly_rounded(self) -> bool { self == Fun::Fmod @@ -312,27 +204,27 @@ pub fn uses(op: FloatFn, f: Form) -> &'static [Fun] { } } match crate::lower::arith::math::half_form(op, f) { - FloatFn::Atan => &[Fun::Atan(Mode::Precise)], - FloatFn::FastAtan => &[Fun::Atan(Mode::Fast)], - FloatFn::Asin => &[Fun::Asin(Mode::Precise)], - FloatFn::FastAsin => &[Fun::Asin(Mode::Fast)], - FloatFn::Acos => &[Fun::Acos(Mode::Precise)], - FloatFn::FastAcos => &[Fun::Acos(Mode::Fast)], + FloatFn::Atan => &[Fun::Atan], + FloatFn::FastAtan => &[Fun::Atan], + FloatFn::Asin => &[Fun::Asin], + FloatFn::FastAsin => &[Fun::Asin], + FloatFn::Acos => &[Fun::Acos], + FloatFn::FastAcos => &[Fun::Acos], FloatFn::Atan2 => &[Fun::Atan2], // `atan(y · rcp(x))`, Metal's fast `atan` of its fast quotient. - FloatFn::FastAtan2 { .. } => &[Fun::Atan(Mode::Fast), Fun::Recip], + FloatFn::FastAtan2 { .. } => &[Fun::Atan, Fun::Recip], FloatFn::Sin => &[Fun::Sin], FloatFn::Cos => &[Fun::Cos], FloatFn::Tan => &[Fun::Tan], FloatFn::FastSin => &[Fun::FastSin], FloatFn::FastCos => &[Fun::FastCos], FloatFn::FastTan => &[Fun::FastTan], - FloatFn::SinPi => &[Fun::SinPi(Mode::Precise)], - FloatFn::CosPi => &[Fun::CosPi(Mode::Precise)], - FloatFn::TanPi => &[Fun::TanPi(Mode::Precise)], - FloatFn::FastSinPi => &[Fun::SinPi(Mode::Fast)], - FloatFn::FastCosPi => &[Fun::CosPi(Mode::Fast)], - FloatFn::FastTanPi => &[Fun::TanPi(Mode::Fast)], + FloatFn::SinPi => &[Fun::SinPi], + FloatFn::CosPi => &[Fun::CosPi], + FloatFn::TanPi => &[Fun::TanPi], + FloatFn::FastSinPi => &[Fun::SinPi], + FloatFn::FastCosPi => &[Fun::CosPi], + FloatFn::FastTanPi => &[Fun::TanPi], FloatFn::Sqrt => &[Fun::Sqrt], FloatFn::Rsqrt => &[Fun::Rsqrt], FloatFn::Fmod => &[Fun::Fmod], @@ -405,7 +297,7 @@ impl Lib { } /// Metal's precise `fmod` of `x` and `y` (`float` lanes of form `f`) by its routine, one call - /// per lane; `None` where the module takes the device's `OpFRem` ([`Fun::device_answers`]). + /// per lane; `None` where the module defines no routine ([`Lib::instructions`]). pub fn fmod( &self, fb: &mut FunctionBuilder<'_>, diff --git a/crates/metal2vulkan/src/lower/arith/math.rs b/crates/metal2vulkan/src/lower/arith/math.rs index 759be5b59..7cd17529f 100644 --- a/crates/metal2vulkan/src/lower/arith/math.rs +++ b/crates/metal2vulkan/src/lower/arith/math.rs @@ -178,8 +178,8 @@ fn ldexp(fb: &mut FunctionBuilder<'_>, f: Form, x: Value, k: Value) -> BResult, f: Form, x: Value, k: Value) -> BResult { let i = u32_form(f); let it = ty(fb, i)?; @@ -784,15 +784,13 @@ pub enum FloatFn { /// of the `f32` container, so exact for NaNs and zeros on every device. Not on `double`. CopySign, // Device precision (`PrecisionNote::DeviceArithmetic`). - /// Metal's precise `sqrt`: correctly rounded (MSL Table 8.1). The device's `Sqrt`, Metal's own - /// where the device's functions are Metal's in a module compiled with precise functions - /// ([`libm`]). + /// Metal's precise `sqrt`: correctly rounded (MSL Table 8.1). The device's `Sqrt`. Sqrt, /// `fma` on `double` (`GLSL.std.450 Fma`) and `bfloat` (`narrow::bf16_fma`). `float` and `half` /// select the correctly rounded [`super::fma`]. Fma, /// Metal's precise `fmod`: exact (Table 8.1), `fmod(x, ±inf) = x`. On `float` and `half` its - /// routine, but where the device's `OpFRem` is Metal's `fmod` ([`libm::Fun::device_answers`]). + /// routine. Fmod, /// `dot`: the device's `OpDot`. Dot, @@ -830,27 +828,21 @@ pub enum FloatFn { /// `air.fast_log10` on `float`: `log2(x) · log10(2)` (MSL Table 8.2), the product rounded: /// every lane of case f6524207. FastLog10, - /// Metal's precise `sin`: within 4 ulp (MSL Table 8.1). The device's instruction, Metal's own - /// where the device's functions are Metal's in a module compiled with precise functions - /// ([`libm`]). + /// Metal's precise `sin`: within 4 ulp (MSL Table 8.1). The device's instruction. Sin, /// Metal's precise `cos`: within 4 ulp; as [`FloatFn::Sin`]. Cos, - /// `air.fast_sin` on `float`: the device's `Sin`, Metal's `fast::sin` itself where its - /// functions are Metal's in a fast-math module. Metal answers `+0` past `float(π/2) · 2^22` and + /// `air.fast_sin` on `float`: the device's `Sin`. Metal answers `+0` past `float(π/2) · 2^22` and /// for an infinity or NaN; the device answers its `Sin` there. FastSin, /// `air.fast_cos` on `float`: the device's `Cos`; as [`FloatFn::FastSin`]. FastCos, /// Metal's precise `tan`: within 6 ulp; as [`FloatFn::Sin`]. Tan, - /// `air.fast_tan` on `float`: the device's `Tan`, Metal's `fast::tan` itself where its - /// functions are Metal's in a fast-math module (MSL Table 8.2 defines it as `sin(x) · (1 / - /// cos(x))`). + /// `air.fast_tan` on `float`: the device's `Tan` (MSL Table 8.2 defines Metal's as `sin(x) · (1 + /// / cos(x))`). FastTan, - /// Metal's precise `asin`: within 4 ulp (MSL Table 8.1). The device's instruction, Metal's own - /// where the device's functions are Metal's in a module compiled with precise functions - /// ([`libm`]). + /// Metal's precise `asin`: within 4 ulp (MSL Table 8.1). The device's instruction. Asin, /// `air.fast_asin` on `float`: within 5 ulp (Table 8.2); as [`FloatFn::Asin`], in Metal's /// fast mode. @@ -865,29 +857,25 @@ pub enum FloatFn { FastAtan, /// Metal's precise `sinh`; as [`FloatFn::Exp`]. Sinh, - /// `air.fast_sinh` on `float`: the device's `Sinh`, Metal's `fast::sinh` itself where its - /// functions are Metal's in a fast-math module (MSL Table 8.2 defines it as + /// `air.fast_sinh` on `float`: the device's `Sinh` (MSL Table 8.2 defines Metal's as /// `(exp(x) - exp(-x)) · 0.5`). FastSinh, /// Metal's precise `cosh`; as [`FloatFn::Exp`]. Cosh, /// `air.fast_cosh` on `float`: the device's `Cosh`; as [`FloatFn::FastSinh`]. FastCosh, - /// Metal's precise `tanh` (within 5 ulp): the device's instruction, Metal's own where its - /// functions are Metal's (SPIRV-Cross emits `precise::tanh` in either mode). + /// Metal's precise `tanh` (within 5 ulp): the device's instruction. Tanh, /// `air.fast_tanh` on `float`: the device's `Tanh`. MSL Table 8.2 defines Metal's as the /// formula `(t - 1) / (t + 1)` with `t = exp(2x)`, which is `NaN` once `t` overflows, where the - /// device's `Tanh` answers `±1`; on a device whose functions are Metal's the instruction is - /// Metal's precise `tanh`. Narrow forms keep [`FloatFn::Tanh`]: the fast-math table is the + /// device's `Tanh` answers `±1`. Narrow forms keep [`FloatFn::Tanh`]: the fast-math table is the /// single-precision one. FastTanh, /// Metal's precise `asinh`; as [`FloatFn::Exp`]. Asinh, /// `air.fast_asinh` on `float` with every flag: Metal's fast formula /// `log(x + sqrt(x * x + 1))` (MSL Table 8.2), which is the canonical NaN at `-inf` - /// (`-inf + inf`): the device's `Asinh`, Metal's own in a fast-math module where its functions - /// are Metal's. + /// (`-inf + inf`): the device's `Asinh`. FastAsinh, /// Metal's precise `acosh`; as [`FloatFn::Exp`]. Acosh, @@ -895,8 +883,7 @@ pub enum FloatFn { FastAcosh, /// Metal's precise `atanh`; as [`FloatFn::Exp`]. Atanh, - /// `air.fast_atanh` on `float`: the device's `Atanh`, Metal's `fast::atanh` itself where its - /// functions are Metal's in a fast-math module (MSL Table 8.2 defines it as + /// `air.fast_atanh` on `float`: the device's `Atanh` (MSL Table 8.2 defines Metal's as /// `0.5 · log((1 + x) / (1 - x))`). FastAtanh, /// Metal's `sinpi`: within 4 ulp (MSL Table 8.1). The exact reduction around the device's `Sin` @@ -924,7 +911,7 @@ pub enum FloatFn { /// Metal composes it. FastPow, /// Metal `atan2(y, x)`: C99 Annex F's special values (`atan2_special`) around the generic - /// value, the device's `Atan2` (always `precise::atan2` where its functions are Metal's). + /// value, the device's `Atan2`. Atan2, /// `air.fast_atan2` on `float`: `atan(y / x)` turned by `±π` when `x` is below zero, MSL Table /// 8.2's formula (`fast_atan2`): `0 / 0` and `inf / inf` are NaN, where `atan2` answers C99's @@ -1038,21 +1025,20 @@ impl FloatFn { /// the device's denormal mode, or records the device's answer under another note, so it records /// no `PrecisionNote::DeviceDenormals` of its own: `copysign`, which moves bits, and precise /// `fmod` on `float`, the remainder's routine, which reads a denormal divisor as a zero on the - /// bits and computes the remainder in integers (`libm::fmod`), or on MoltenVK Metal's own; + /// bits and computes the remainder in integers (`libm::fmod`); /// `fmin`, `fmax`, `min3`, `max3`, `clamp`, `saturate` and `median3`, the device's `NMin`, - /// `NMax` and `NClamp`, whose comparison of a denormal is Metal's where measured - /// (`DriverDeviation::MetalMinMax`, but in `median3`) and else `PrecisionNote::NativeMinMax`'s + /// `NMax` and `NClamp`, whose comparison of a denormal is within `PrecisionNote::NativeMinMax`'s /// bound; `round`, /// whose every denormal operand rounds to a zero, its sign the note's /// (`PrecisionNote::NativeTranscendentals`); and the device's instructions for Metal's /// functions: `fabs`, `sign`, `fract` and `fast::sqrt` ([`FloatFn::native_instruction`]), the /// trigonometric, hyperbolic and arc families in both modes, `sinpi`, `cospi`, and `tanpi`, /// the exponentials and logarithms, and `pow`, `powr` and `atan2` with their special cases - /// (the device's comparisons around the device's instruction), Metal's own where the device's - /// functions are Metal's, and elsewhere recording the device's denormals with their precision + /// (the device's comparisons around the device's instruction), recording the device's + /// denormals with their precision /// (`PrecisionNote::NativeTranscendentals`). `fast::atan2` does not: its quotient is the /// device's division or its product with the device's reciprocal, whose operands and - /// reciprocal `denormal::coverage` reads. + /// reciprocal `denormal::covered` reads. pub fn metal_denormals(self) -> bool { use FloatFn as F; matches!( @@ -1120,9 +1106,7 @@ impl FloatFn { } /// Whether the call takes the device's instruction for one of Metal's functions that no - /// `libm::Fun` names, which is Metal's own function where the device's functions are Metal's - /// (SPIRV-Cross writes Metal's `fabs`, `sign`, `fract` and `sqrt`), and elsewhere answers its - /// special operands as the device does: `fabs` (`FAbs`), `sign` (`FSign`), `fract` and + /// `libm::Fun` names, which answers its special operands as the device does: `fabs` (`FAbs`), `sign` (`FSign`), `fract` and /// `fast::fract` (`Fract`), and `fast::sqrt` (`Sqrt`, where Metal's is `x · rsqrt(x)`). pub fn native_instruction(self) -> bool { matches!( @@ -1142,8 +1126,7 @@ impl FloatFn { /// Whether a `half` call on form `f` answers a zero remainder of a nonzero dividend with its /// `float` function's sign where Metal's `half` function answers another, on every device: - /// `fmod`, whose `float` remainder (the exact remainder's routine, or the device's where its - /// functions are Metal's) keeps the dividend's sign, as C's does, where Metal's `half` `fmod` + /// `fmod`, whose `float` remainder (the exact remainder's routine) keeps the dividend's sign, as C's does, where Metal's `half` `fmod` /// answers `+0` (`fmod(-2, 0.5)`; `nan_fmod_zero`, `nan_fmod_zero_fast`, with and without /// fast-math flags) (`PrecisionNote::NativeTranscendentals`). pub fn half_zero_of_float(self, f: Form) -> bool { @@ -1174,7 +1157,7 @@ impl FloatFn { /// Whether the function divides by a device division besides its [`FloatFn::precision`] /// class (`PrecisionNote::DeviceArithmetic`): `fast_atan2`'s `y / x` (the device's division) - /// and `fast::tanpi`'s quotient where the device's functions are Metal's. + /// and `fast::tanpi`'s quotient. pub fn divides(self) -> bool { matches!(self, FloatFn::FastAtan2 { .. } | FloatFn::FastTanPi) } @@ -1394,9 +1377,8 @@ fn float_fn_core( F::Fract => fract_below_one(fb, f, a), F::FastFract => g1(fb, GlslOp::Fract), F::Sign => g1(fb, GlslOp::FSign), - // 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. + // Metal's `clamp(x, +0, 1)`: the device's `NClamp`, 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]) @@ -1486,8 +1468,7 @@ fn float_fn_core( let c = wide_splat(fb, f, k)?; fb.binary_with(BinOp::FMul, l, c, Contraction::Forbidden) } - // The device's instructions in both modes, Metal's fast functions where its functions are - // Metal's in a fast-math module (`libm::Fun::device_answers`). + // The device's instructions in both modes. F::Sin | F::FastSin => g1(fb, GlslOp::Sin), F::Cos | F::FastCos => g1(fb, GlslOp::Cos), F::Tan | F::FastTan => g1(fb, GlslOp::Tan), @@ -1755,8 +1736,7 @@ pub(super) fn fast_powr_special( /// one, as Metal defines it (`fmin(x - floor(x), 0x1.fffffep-1)`): the largest value below one of /// the format wherever the difference reaches one (`-1e-10` gives `1 - 2^-24`, not `1`). The /// bound is an ordered comparison, so a NaN `Fract` is kept, the device's NaN. An infinity, a NaN -/// and an `f32` denormal answer as the device's `Fract` does (`PrecisionNote::NativeTranscendentals` -/// off Metal's own functions). +/// and an `f32` denormal answer as the device's `Fract` does (`PrecisionNote::NativeTranscendentals`). fn fract_below_one(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { // `floor(x)` of a narrow value is a value of the format: the difference takes the device's // rounding. @@ -1859,8 +1839,7 @@ pub(super) type QuotientOf<'a> = /// `quotient`'s, the device's `OpFDiv`. For a normal `x` no operand of it is a denormal: a nonzero /// `sinpi` is at least `π 2^-126` in magnitude (`r` is `x` below 1, and a multiple of `2^-23` /// above); a denormal `x` reaches the first multiply and difference, which read it as the device -/// does: Metal's reading where the profile's functions are Metal's (the deviation, or flushed -/// before), the device's under native device maths (`PrecisionNote::DeviceDenormals`). At a +/// does, under native device maths (`PrecisionNote::DeviceDenormals`). At a /// quarter turn (`r = ±1/4`, exact like every step before the multiply) the two arms are the sine /// and cosine of `π/4`, equal in magnitude, so `tanpi` is exactly `±1` with the quotient's sign, /// whatever the device's `Sin` and `Cos` round them to (on lavapipe they differ by one ulp, and the @@ -2236,7 +2215,7 @@ pub(super) type AtanOf<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, Value) -> BRes /// `atan2` answers `-π`), and `fast::atan2(1, -0)` is `-π/2`. /// /// Zeros are the device's comparisons, so an `f32` denormal operand is a zero where the device -/// reads it so (`denormal::coverage`), and a denormal quotient is the device's `Atan` of it. +/// reads it so (`denormal::covered`), and a denormal quotient is the device's `Atan` of it. /// /// The quotient follows the call's fast-math flags. A call that carries every flag (case /// c11eb8cb, compiled with fast math) divides over the whole range (`fast::atan2(FLT_MAX, @@ -2245,7 +2224,7 @@ pub(super) type AtanOf<'a> = &'a dyn Fn(&mut FunctionBuilder<'_>, Value) -> BRes /// `OpFDiv` bound their error. Any other call (`by_reciprocal`; case 6802ab13, compiled without /// fast math, measured with no flag) multiplies `y` by the device's reciprocal of `x`, as Metal /// composes it. Beyond `2^126` that reciprocal is an `f32` denormal, the device's to keep or -/// flush (`denormal::coverage`): Metal flushes it, so its quotient is the signed zero, or NaN for +/// flush (`denormal::covered`): Metal flushes it, so its quotient is the signed zero, or NaN for /// an infinite `y` (`fast::atan2(FLT_MAX, FLT_MAX)` is `+0`, `fast::atan2(inf, FLT_MAX)` is NaN), /// and so is the device's where it flushes; a device that keeps it answers `atan` of the product /// (`±π/2` for an infinite `y`). A quotient the device's product makes NaN (an infinite `y` times diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index dd6bcbb2c..23faabfa5 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -60,10 +60,9 @@ //! one and the device's multiply, `RoundEven` and clamp elsewhere ([`pack`], //! `PrecisionNote::DevicePackConversion`). //! -//! 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`. +//! A NaN result's bits are the device's ([`nan`]): where Metal answers one (its canonical +//! `0x7FC00000` or `0x7E00`, or a NaN that carries an operand's sign or bits), the module records +//! `PrecisionNote::NativeNanEncoding`. pub mod aggregate; pub mod chunk; @@ -101,15 +100,14 @@ use crate::air::ir::{ }; use crate::air::Entry; use crate::budget::Meter; -use crate::device::profile::{FloatFunctions, NanEncoding}; use crate::device::{DeviceProfile, FloatWidth}; use crate::error::Error; use crate::lower::access; use crate::lower::emit::EmitCx; use crate::lower::select::{FamilyPlans, Plan, SelectCx}; use crate::lower::strategy::FamilyStrategy; -use crate::pipeline::artifact::{EntryMath, PrecisionNote}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder, ProductForm, QuantizeForm}; +use crate::pipeline::artifact::PrecisionNote; +use crate::spirv::builder::{FunctionBuilder, ModuleBuilder, QuantizeForm}; use crate::spirv::error::BResult; use crate::spirv::ids::{DemoteTy, FuncId, TypeId, Value as SValue}; use crate::spirv::ir::{Contraction, ExecMode, UnOp}; @@ -202,8 +200,8 @@ pub enum ArithStrategy { contract: Contraction, }, /// A `half` `fadd`, `fsub` or `fmul` on lanes of `form` by the device's 16-bit arithmetic, - /// Metal's own in the forms that keep it apart (measured, `DriverDeviation::MetalHalfArithmetic`, - /// or by the Vulkan spec under the 16-bit float controls, [`ops::f16_binary`]): the operands + /// Metal's own in the forms that keep it apart (by the Vulkan spec under the 16-bit float + /// controls, [`ops::f16_binary`]): the operands /// narrowed to 16 bits, exactly, the instruction, and its result widened, exactly. `contract` /// is the AIR's own, as for [`ArithStrategy::Float`] ([`contraction`]): `Allowed` leaves the /// instruction to the device's compiler, `Forbidden` keeps it apart. @@ -704,41 +702,16 @@ pub struct ArithPlan { /// The `half` additions, subtractions and products held at `float` precision, unrounded, /// between a chain's roundings on a device without `shaderFloat16` ([`half_chain`]). pub held_at_float: BTreeSet, - /// Whether a call takes Metal's precise `fmod` on `float` or `half` lanes ([`libm::uses`]), - /// recorded at selection; [`finish`] decides [`ArithPlan::fmod`] from it. - pub fmod_uses: bool, - /// Whether the module defines precise `fmod`'s routine ([`declare`]): where a call takes it - /// and the device's `OpFRem` is not Metal's `fmod` in the entry's mode - /// ([`libm::Fun::device_answers`]), decided by [`finish`]. + /// Whether the module defines precise `fmod`'s routine ([`declare`]): a call takes Metal's + /// precise `fmod` on `float` or `half` lanes ([`libm::uses`]), recorded at selection. pub fmod: bool, - /// The mode of the device's own `float` functions where the profile's are Metal's - /// (`FloatFunctions::Metal`): the mode Metal compiles this entry in ([`libm::module_mode`], - /// decided by [`finish`]). `None` on any other profile. - pub metal_functions: Option, /// Whether a selected fused multiply-add takes the device's `Fma` ([`fma::Route::Native`], or /// [`fma::Route::F16Native`] on 16-bit floats), whose note [`finish`] records. pub native_fma: bool, - /// How the module emits a multiply the device must round on its own, decided by [`finish`] from - /// the same fact as [`ArithPlan::metal_functions`]: a device whose `float` functions are - /// Metal's reaches Metal through SPIRV-Cross, which loses a `-0` product of a `NoContraction` - /// `OpFMul`, so it takes `Fma(a, b, -0.0)`; any other device takes the `OpFMul`, which has no - /// `-0.0` addend for it to answer. In either form a constant factor's `-0.0` components are - /// multiplied as `+0.0` and negated (`FunctionBuilder::binary`). - pub product: ProductForm, /// Whether a function converts the texels of a slot or attachment bound in an extended-range, /// padded or bfloat form ([`ArithPlan::converts`]) by the device's arithmetic /// ([`extended_range`]): [`finish`] then records `PrecisionNote::DevicePackConversion`. pub extended_range: bool, - /// Whether a `float` operation leaves its `f32` denormals to the device because the device - /// reads them as Metal does ([`denormal::device_flushes`]), recorded at selection: the module - /// then requires `VkProperty::MetalFloatDenormals`, or, where its entry declares the 16-bit - /// float controls, records `PrecisionNote::DeviceDenormals` on every device - /// (`pipeline::compile`). - pub device_denormals: bool, - /// Whether a `float` negation, absolute value, floor or ceiling leaves its `f32` denormals to - /// the device because the device reads them as Metal does ([`denormal::unary_kept`]), - /// recorded at selection: the module then requires `VkProperty::MetalUnaryDenormals`. - pub unary_denormals: bool, /// How the module rounds an `f32` to `half` ([`narrow::round`]), decided by [`finish`] from /// the profile ([`narrow::quantize_form`]): the device's conversion to 16 bits and its /// widening under the float controls that make it Metal's, else that conversion as it is @@ -759,36 +732,6 @@ pub struct ArithPlan { /// `sqrt` are the device's 16-bit instructions and it holds its `half` values at 16 bits /// (`spirv::half_hold`), whatever [`ArithPlan::quantize`] is. pub controls: 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 - /// (`DriverDeviation::MetalMinMax`), recorded at selection: the module then requires - /// `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 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`. - pub f16_arith: bool, - /// Whether the NaN a `float` `fneg` or `fabs` moves is left to the device because it is - /// measured to answer Metal's (`DriverDeviation::MetalNanMoves`, [`nan::moves_answered`]), - /// recorded at selection: the module then requires `VkProperty::MetalNanMoves`. - pub nan_moves: bool, - /// Whether the NaN of a `half` held widened that a widening to `float` or a `half` `fabs` - /// moves is left to the device because it is measured to answer Metal's - /// ([`nan::moves_answered`]), recorded at selection: the module then requires - /// `VkProperty::MetalNanMoves`, but where it holds a `half` the device's conversions did not - /// make ([`narrow::moves_unfolded`]), where it records `PrecisionNote::NativeNanEncoding`. - pub held_nan_moves: bool, - /// Whether an `air.pack` or `air.unpack` takes the device's conversion with no note because - /// its form is measured to answer Metal's (`DriverDeviation::MetalPackConversions`, - /// [`pack::measured`]), recorded at selection: the module then requires - /// `VkProperty::MetalPackConversions`. - pub metal_packs: bool, - /// The precision notes the plan's operations record unless their entry's quotient and - /// functions are Metal's own (the profile's `float` functions are Metal's and Metal compiles - /// the entry with fast math), recorded at selection ([`OpNotes::unless_metal_fast`]); - /// [`finish`] records them where they are not. - pub unless_metal_fast: BTreeSet, } impl ArithPlan { @@ -825,12 +768,8 @@ pub const FAST_DIVIDE: &str = "arith.fdiv.fast"; /// Complete the arith family's plan once every instruction and parameter is selected: declare /// `SignedZeroInfNanPreserve` for each required width the profile supports, and note /// `DeviceSignedZeroInfNan` for one it does not (the device's behavior is accepted and -/// reported); then, with the entry's execution modes known, decide whether precise `fmod` takes -/// its routine ([`ArithPlan::fmod`]: on a profile whose `float` functions are Metal's, not in an -/// entry Metal compiles with precise functions, [`libm::module_mode`]), record the notes of the -/// operations that are Metal's own in a fast-math entry only where it is not -/// ([`ArithPlan::unless_metal_fast`]), and choose the form of a multiply the device must round on -/// its own by the same fact ([`ArithPlan::product`]). +/// reported); then record `NativeFma` where a fused multiply-add takes the device's `Fma` +/// ([`ArithPlan::native_fma`]). pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { cx.families.arith.wide = legal::holds_wide(cx.profile); cx.families.arith.quantize = narrow::quantize_form(cx.profile); @@ -856,28 +795,10 @@ pub fn finish(cx: &mut SelectCx<'_>) -> Result<(), Error> { cx.precision.insert(PrecisionNote::DeviceSignedZeroInfNan); } } - let arith = &mut cx.families.arith; - // The measured device fact, never the driver's name. - arith.metal_functions = match cx.profile.fields().float_functions { - FloatFunctions::Metal => Some(libm::module_mode(&arith.modes)), - FloatFunctions::Native => None, - }; // Every family selected its fused multiply-adds by now (a cube position's at selection). - if arith.native_fma { + if cx.families.arith.native_fma { cx.precision.insert(PrecisionNote::NativeFma); } - let metal = arith.metal_functions; - // The same fact decides the multiply's form. - arith.product = match metal { - Some(_) => ProductForm::NegativeZeroFma, - None => ProductForm::Multiply, - }; - // Precise `fmod` takes its routine but where the device's `OpFRem` is Metal's `fmod`. - arith.fmod = arith.fmod_uses && !metal.is_some_and(|m| libm::Fun::Fmod.device_answers(m)); - // An operation that is Metal's own in a fast-math entry records its notes only outside one. - if !metal_fast(arith.metal_functions) { - cx.precision.extend(arith.unless_metal_fast.iter().copied()); - } Ok(()) } @@ -1113,77 +1034,6 @@ fn device_float_notes(f: Form, denormals: bool, nans: bool) -> impl Iterator, - /// The notes it records unless the entry is Metal's fast one. - pub unless_metal_fast: BTreeSet, -} - -impl OpNotes { - /// `notes`, held in every entry. - fn everywhere(notes: BTreeSet) -> OpNotes { - OpNotes { - always: notes, - unless_metal_fast: BTreeSet::new(), - } - } - - /// `notes`, held in every entry but Metal's fast one where `own`, else in every entry. - fn unless_own(notes: BTreeSet, own: bool) -> OpNotes { - if own { - OpNotes { - always: BTreeSet::new(), - unless_metal_fast: notes, - } - } else { - OpNotes::everywhere(notes) - } - } - - /// Both sets of `other` added to this one's. - fn with(mut self, other: OpNotes) -> OpNotes { - self.always.extend(other.always); - self.unless_metal_fast.extend(other.unless_metal_fast); - self - } - - /// The notes the operation records in an entry whose `float` functions are Metal's in mode - /// `metal` (`None` on a profile whose functions are the device's), as [`finish`] decides - /// them. - pub fn in_entry(self, metal: Option) -> BTreeSet { - let mut notes = self.always; - if !metal_fast(metal) { - notes.extend(self.unless_metal_fast); - } - notes - } -} - -/// Whether an entry whose `float` functions are Metal's in mode `metal` (`None`: the device's) is -/// one Metal compiles with fast math: its `arcp` quotient and its functions are then Metal's own -/// ([`OpNotes`]). -fn metal_fast(metal: Option) -> bool { - metal == Some(libm::Mode::Fast) -} - -/// Record `notes`, an operation's: those that hold in every entry now, the others once [`finish`] -/// knows whether the entry is Metal's fast one. -fn record(cx: &mut SelectCx<'_>, notes: OpNotes) { - cx.precision.extend(notes.always); - cx.families - .arith - .unless_metal_fast - .extend(notes.unless_metal_fast); -} - /// The precision notes the lowering of the float binary operator `op` with fast-math flags `fmf` /// on operands of format `fmt` records for the operator itself on profile `p`: a division or /// remainder is the device's arithmetic, and a `float` operator leaves its denormals to the device @@ -1198,10 +1048,7 @@ fn record(cx: &mut SelectCx<'_>, notes: OpNotes) { /// fast-math flag is the device's `OpFRem`, `x - y · trunc(x / y)` at its precision, as Metal /// computes it of its precise quotient. Beside these, an addition, subtraction, or multiply whose /// flags let the device fuse or regroup it with an operand's definition records -/// `FastMathRewrites`, which the operands decide (`note_rewrites`); a `half` one whose flags -/// allow contraction records it whatever its operands where the profile takes -/// `DriverDeviation::MetalHalfArithmetic` (MoltenVK), whose compiler answers the device's 16-bit -/// instruction left undecorated as the unrounded `float` result. `None` for an integer operator. +/// `FastMathRewrites`, which the operands decide (`note_rewrites`). `None` for an integer operator. /// /// [`select`] records exactly these for such an operator (a `half` result's rounding is noted from /// the emitted module); validation reads them to tell which operations the product computes as a @@ -1211,23 +1058,20 @@ pub fn float_binop_notes( fmt: FloatFmt, fmf: FastMath, p: &DeviceProfile, -) -> Option { +) -> Option> { if !op.is_float() { return None; } - // The device leaves the NaN Metal answers to the device where the profile does. - let native_nan = |answers: bool| { - (answers && nan::encoding(p) == NanEncoding::Native) - .then_some(PrecisionNote::NativeNanEncoding) - }; + // The NaN Metal answers is left to the device, noted. + let native_nan = |answers: bool| answers.then_some(PrecisionNote::NativeNanEncoding); if divide::precise(op, fmt, fmf) { - return Some(OpNotes::everywhere( + return Some( [Some(PrecisionNote::NativeDivision), native_nan(true)] .into_iter() .flatten() .chain(device_float_notes(scalar_float(fmt), true, false)) .collect(), - )); + ); } // A `float` remainder with every flag is Metal's `fast::fmod`, with that function's notes. if op == AirBin::FRem && fmt == FloatFmt::F32 && every_flag(fmf) { @@ -1246,35 +1090,19 @@ pub fn float_binop_notes( PrecisionNote::DeviceDenormals, ]); notes.extend(native_nan(true)); - return Some(OpNotes::unless_own( - notes, - p.fields().float_functions == FloatFunctions::Metal, - )); + return Some(notes); } - // 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. + // A `float` `+ - *` and remainder answer the device's NaN, noted ([`nan`]), and leave their + // denormals to the device ([`leave_denormals`]). // Metal's `half` and `bfloat` remainders are not measured. let answer = binop_answer(op, fmt); let nans = answer.is_none(); - let denormals = op == AirBin::FRem || !denormal::device_flushes(p); - let mut notes: BTreeSet<_> = device_float_notes(scalar_float(fmt), denormals, nans).collect(); + let mut notes: BTreeSet<_> = device_float_notes(scalar_float(fmt), true, nans).collect(); if matches!(op, AirBin::FDiv | AirBin::FRem) { notes.insert(PrecisionNote::DeviceArithmetic); } notes.extend(native_nan(answer.is_some())); - // The device's 16-bit `half` `+ - *` left to its compiler on the measured basis: Metal's fast - // compile folds its conversions away and answers the `float` result unrounded ([`select`]). - let lane = Form { - held: Held::Float(fmt), - lanes: 1, - }; - if contraction(fmf) == Contraction::Allowed - && f16_arithmetic(p, op, lane) == Some(F16Basis::Measured) - { - notes.insert(PrecisionNote::FastMathRewrites); - } - Some(OpNotes::everywhere(notes)) + Some(notes) } /// The NaN Metal answers for the float binary operator `op` on format `fmt`, which its lowering @@ -1288,8 +1116,7 @@ fn binop_answer(op: AirBin, fmt: FloatFmt) -> Option { } /// 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`]). +/// it itself, with that NaN left to the device ([`nan`]): noted `NativeNanEncoding`. fn with_nan( cx: &mut SelectCx<'_>, s: ArithStrategy, @@ -1299,55 +1126,20 @@ fn with_nan( s } -/// `answer`, the NaN Metal answers for an operation that moves a NaN (a `half`'s widening to -/// `float`, a `float` `fneg`), where the device is not measured to answer it: `None` on a profile -/// whose device's moves are measured to be Metal's ([`nan::moves_answered`]), which the plan -/// records ([`ArithPlan::held_nan_moves`] for a `half` held widened, else -/// [`ArithPlan::nan_moves`]). -fn moved_nan( - cx: &mut SelectCx<'_>, - answer: Option, - held: bool, -) -> Option { - if answer.is_some() && nan::moves_answered(cx.profile) { - match held { - true => cx.families.arith.held_nan_moves = true, - false => cx.families.arith.nan_moves = true, - } - return None; - } - answer -} - -/// Record `NativeNanEncoding` where Metal answers a NaN (`answer`) the device is not measured to -/// answer ([`nan::NanAnswer::device_answers`]). +/// Record `NativeNanEncoding` where Metal answers a NaN (`answer`). fn note_native_nan(cx: &mut SelectCx<'_>, answer: Option) { - if answer.is_some_and(|a| !a.device_answers(nan::encoding(cx.profile))) { + if answer.is_some() { cx.precision.insert(PrecisionNote::NativeNanEncoding); } } -/// Leave an operation's `f32` denormals (on `float` lanes of form `f`) to the device: where the -/// device is measured to read them as Metal does and the operation is one the measured deviation -/// covers (`covered`: [`denormal::device_flushes`], or [`denormal::unary_kept`] for a negation, a -/// floor and a ceiling), the module requires the deviation's property; elsewhere they are the -/// device's own, noted `DeviceDenormals` (as the operation's notes record it). -/// Another format leaves nothing: a `half` is held widened, never an `f32` denormal, and Metal's -/// `bfloat` and `double` environments are not measured. -pub(super) fn leave_denormals(cx: &mut SelectCx<'_>, f: Form, covered: denormal::Covered) { - if f.float_fmt() != Some(FloatFmt::F32) { - return; - } - match covered { - denormal::Covered::Deviation if denormal::device_flushes(cx.profile) => { - cx.families.arith.device_denormals = true; - } - denormal::Covered::Unary if denormal::unary_kept(cx.profile) => { - cx.families.arith.unary_denormals = true; - } - _ => { - cx.precision.insert(PrecisionNote::DeviceDenormals); - } +/// Leave an operation's `f32` denormals (on `float` lanes of form `f`) to the device: they are the +/// device's own, noted `DeviceDenormals` (as the operation's notes record it). Another format +/// leaves nothing: a `half` is held widened, never an `f32` denormal, and Metal's `bfloat` and +/// `double` environments are not measured. +pub(super) fn leave_denormals(cx: &mut SelectCx<'_>, f: Form) { + if f.float_fmt() == Some(FloatFmt::F32) { + cx.precision.insert(PrecisionNote::DeviceDenormals); } } @@ -1491,25 +1283,23 @@ fn select_in( // 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()); + cx.precision.extend(notes.unwrap_or_default()); note_rewrites(cx, (*op, *fmf), *a, *b); fp_env(cx, *fmf, f); - leave_denormals(cx, f, denormal::Covered::Never); + leave_denormals(cx, f); let s = S::NativeDivide { form: 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); - record(cx, notes.unwrap_or_default()); + cx.precision.extend(notes.unwrap_or_default()); note_rewrites(cx, (*op, *fmf), *a, *b); fp_env(cx, *fmf, f); let contract = contraction(*fmf); // Metal divides `float` under `arcp` as `x` times its fast reciprocal of `y` // (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, noted where it - // is not measured to be Metal's canonical one; its `f32` denormals the + // `OpFDiv(x, y)`. Its NaN is the device's, noted; its `f32` denormals the // device's ([`float_binop_notes`]). if *op == AirBin::FDiv && fmf.contains(FastMath::ARCP) @@ -1517,18 +1307,10 @@ fn select_in( { let s = S::FastDivide { form: f, contract }; with_nan(cx, s, Some(nan::NanAnswer::Canonical)) - } else if let Some(basis) = f16_arithmetic(cx.profile, *op, f) { + } else if f16_arithmetic(cx.profile, *op, f) { // The device's own `half` arithmetic, its contraction the AIR's own as - // `float`'s is. Kept apart, it is Metal's: measured, a property the - // module requires, or under the float controls its entry declares. - // Left to the device's compiler on MoltenVK, Metal's fast compile folds - // its conversions away and answers the `float` result unrounded - // (measured with `DriverDeviation::MetalHalfArithmetic`), noted. - let kept = contract == Contraction::Forbidden; - cx.families.arith.f16_arith |= basis == F16Basis::Measured && kept; - if basis == F16Basis::Measured && !kept { - cx.precision.insert(PrecisionNote::FastMathRewrites); - } + // `float`'s is. Kept apart, it is Metal's under the float controls its + // entry declares. let s = S::F16 { op: *op, form: f, @@ -1552,10 +1334,10 @@ fn select_in( contract, }; // Metal reads an `f32` denormal operand of `+ - *` as a zero and flushes a - // denormal result: the device's reading, on the deviation. A remainder's - // are the device's on every device ([`float_binop_notes`]). + // denormal result: the device's reading, noted. A remainder's are the + // device's too ([`float_binop_notes`]). if matches!(op, AirBin::FAdd | AirBin::FSub | AirBin::FMul) { - leave_denormals(cx, f, denormal::Covered::Deviation); + leave_denormals(cx, f); } with_nan(cx, s, binop_answer(*op, fmt)) } @@ -1567,18 +1349,11 @@ fn select_in( let f = form_in(cx, *v, chunk)?; // The device's sign flip: it makes no NaN. Metal's `float` `fneg` flips the sign bit // alone, keeping a NaN's payload and a denormal, whatever the flags; Vulkan lets - // `OpFNegate` flush a denormal (`DeviceDenormals` but where the device is measured to - // keep it, [`denormal::Covered::Unary`]), and states no NaN's bits, noted + // `OpFNegate` flush a denormal (`DeviceDenormals`), and states no NaN's bits, noted // `NativeNanEncoding` where Metal answers one ([`nan::fneg_answer`]). - leave_denormals(cx, f, denormal::Covered::Unary); + leave_denormals(cx, f); fp_env(cx, *fmf, f); let nan = f.float_fmt().and_then(nan::fneg_answer); - // A `float` one's NaN is Metal's where the device's negation is measured to be - // ([`moved_nan`]); a `half` one's held result keeps the flipped sign, noted. - let nan = match f.float_fmt() { - Some(FloatFmt::F32) => moved_nan(cx, nan, false), - _ => nan, - }; with_nan(cx, S::FNeg { form: f }, nan) } InstKind::ICmp { pred, a, .. } => { @@ -1596,7 +1371,7 @@ fn select_in( let f = form_in(cx, *a, chunk)?; // Metal compares an `f32` denormal as a zero; the result is a `bool`, never a NaN. fp_env(cx, *fmf, f); - leave_denormals(cx, f, denormal::Covered::Deviation); + leave_denormals(cx, f); S::FloatCompare { pred: *pred, form: f, @@ -1693,12 +1468,8 @@ fn select_cast( to, }; // A `float` narrowed to `half` answers Metal's canonical `half` NaN; a `half` widened - // to `float` is the widening it was read with ([`moved_nan`]). + // to `float` is the widening it was read with ([`nan::cast_answer`]). let answer = match (from.float_fmt(), to.float_fmt()) { - (Some(FloatFmt::Half), Some(FloatFmt::F32)) => { - let answer = nan::cast_answer(op, FloatFmt::Half, FloatFmt::F32); - moved_nan(cx, answer, true) - } (Some(a), Some(b)) => nan::cast_answer(op, a, b), _ => None, }; @@ -1875,9 +1646,8 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result { /// call keeps the precise function: /// /// - `air.fast_tanh`, `air.fast_sinh`, `air.fast_cosh`, `air.fast_atanh`, `air.fast_sin`, -/// `air.fast_cos` and `air.fast_tan` are the device's instructions, which a device whose -/// functions are Metal's answers as Metal's fast functions only in a fast-math module (and its -/// `Tanh` as Metal's precise `tanh` in every module): their own variants for their notes +/// `air.fast_cos` and `air.fast_tan` are the device's instructions: their own variants for +/// their notes /// ([`FloatFn::FastTanh`], [`FloatFn::FastSinh`], [`FloatFn::FastCosh`], /// [`FloatFn::FastAtanh`], [`FloatFn::FastSin`], [`FloatFn::FastCos`], [`FloatFn::FastTan`]); /// - `air.fast_asinh` with every flag is MSL Table 8.2's formula, the canonical NaN at `-inf` @@ -1891,9 +1661,8 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result { /// - `air.fast_pow`'s magnitude is `exp2(y · log2|x|)` ([`FloatFn::FastPow`]); /// - `air.fast_atan2` is `atan(y / x)` turned by `±π`, NaN at `0 / 0` and `inf / inf` /// ([`FloatFn::FastAtan2`]); -/// - `air.fast_asin`, `air.fast_acos`, and `air.fast_atan` are Metal's fast functions, which a -/// device that is Metal's own answers only in a fast-math module and which answer `fast::asin` -/// of a zero and of a denormal as `+0` and `fast::atan` of one as its signed zero +/// - `air.fast_asin`, `air.fast_acos`, and `air.fast_atan` are Metal's fast functions, which +/// answer `fast::asin` of a zero and of a denormal as `+0` and `fast::atan` of one as its signed zero /// ([`FloatFn::FastAsin`], [`FloatFn::FastAcos`], [`FloatFn::FastAtan`]); /// - `air.fast_rsqrt` is Metal's fast `rsqrt` ([`FloatFn::FastRsqrt`]), apart from the correctly /// rounded precise one; @@ -1905,9 +1674,8 @@ fn llvm_math(op: &LlvmIntrinsic) -> Result { /// magnitude is the last of `|x|`; /// - `air.fast_log2` is Metal's `log2`, the precise one ([`FloatFn::FastLog2`]), which the fast /// formulas' `log2` is too; -/// - `air.fast_sinpi`, `air.fast_cospi`, and `air.fast_tanpi` are Metal's precise functions, -/// which a device whose functions are Metal's answers by its `Sin` and `Cos` within Apple's -/// fast bound ([`FloatFn::FastSinPi`], [`FloatFn::FastCosPi`], [`FloatFn::FastTanPi`]). +/// - `air.fast_sinpi`, `air.fast_cospi`, and `air.fast_tanpi` are Metal's precise functions +/// ([`FloatFn::FastSinPi`], [`FloatFn::FastCosPi`], [`FloatFn::FastTanPi`]). /// /// `air.fast_fmod` on `float` is selected beside this, as [`ArithStrategy::FastFmod`]. /// @@ -2060,24 +1828,12 @@ fn select_float_fn( ) -> Result { let facts = FloatFacts::on(cx.profile); let lowered = float_call(op, fast, fmf, f, facts).ok_or_else(not_lowered)?; - record(cx, lowered.notes); + cx.precision.extend(lowered.notes); fp_env(cx, fmf, f); if let FloatLowering::Fn(op) = lowered.how { let fmod = libm::uses(op, f).contains(&libm::Fun::Fmod); let arith = &mut cx.families.arith; - arith.fmod_uses |= fmod; - arith.device_min_max |= device_min_max(cx.profile, op, f); - // `fabs` keeps a denormal as Metal's does where the device is measured to - // ([`denormal::moves_sign`]): its notes leave it out ([`float_call_of`]). - arith.unary_denormals |= facts.unary_denormals - && denormal::moves_sign(op) - && f.float_fmt() == Some(FloatFmt::F32); - } - if facts.nan_moves && moves_nan(lowered.how, f) { - match f.float_fmt() { - Some(FloatFmt::Half) => cx.families.arith.held_nan_moves = true, - _ => cx.families.arith.nan_moves = true, - } + arith.fmod |= fmod; } if let FloatLowering::Fma(fma) | FloatLowering::FastFmod(fma) = lowered.how { cx.families.arith.take_fma(fma); @@ -2091,55 +1847,29 @@ fn select_float_fn( contract: contraction(fmf), }, }; - // The device reads the call's `f32` denormals as Metal does where the table says so, on the - // deviation; elsewhere they are its own, as the call's notes say. - if let Some(covered) = call_coverage(lowered.how, facts) { - leave_denormals(cx, f, covered); + // The call's `f32` denormals Metal's table reads are the device's own, noted. + if call_coverage(lowered.how) { + leave_denormals(cx, f); } Ok(with_nan(cx, s, lowered.nan)) } -/// Where the device reads the `f32` denormals of a float function call lowered as `how` on a -/// profile with float facts `facts` as Metal does ([`denormal::coverage`]): a fused multiply-add -/// and `fast::fmod` by the device's own `float` instruction as `fma` (`OpFmaKHR`, or the device's -/// `Fma`), and the function's own row. Where the profile's -/// functions are Metal's, Metal's fast `sinpi`, `cospi` and `tanpi` are the device's form -/// ([`FloatFn::FastSinPi`], `math::pi_scaled`), whose first multiply and difference read the -/// operand, on the deviation. `None` for a lowering the table does not list. -fn call_coverage(how: FloatLowering, facts: FloatFacts) -> Option { +/// Whether Metal's table reads the `f32` denormals of a float function call lowered as `how` +/// ([`denormal::covered`]): a fused multiply-add and `fast::fmod` by the device's own `float` +/// instruction as `fma` (`OpFmaKHR`, or the device's `Fma`), and the function's own row. +fn call_coverage(how: FloatLowering) -> bool { match how { - FloatLowering::Fma(fma) | FloatLowering::FastFmod(fma) if fma.route.device_float() => { - denormal::coverage(FloatFn::Fma) + FloatLowering::Fma(fma) | FloatLowering::FastFmod(fma) => { + fma.route.device_float() && denormal::covered(FloatFn::Fma) } - FloatLowering::Fn(FloatFn::FastSinPi | FloatFn::FastCosPi | FloatFn::FastTanPi) - if facts.metal_functions => - { - Some(denormal::Covered::Deviation) - } - FloatLowering::Fn(op) => denormal::coverage(op), - FloatLowering::Fma(_) | FloatLowering::FastFmod(_) => None, + FloatLowering::Fn(op) => denormal::covered(op), } } -/// Whether the device leaves a call lowered as `how` (on lanes of form `f`) its `f32` denormals -/// on a profile with float facts `facts`, as [`leave_denormals`] notes them: where its reading is -/// covered ([`call_coverage`]) but not by the profile's deviation (`facts.device_denormals`, or -/// `facts.unary_denormals` for a floor and a ceiling). -fn coverage_left(how: FloatLowering, f: Form, facts: FloatFacts) -> bool { - f.float_fmt() == Some(FloatFmt::F32) - && call_coverage(how, facts) - .is_some_and(|c| !c.holds(facts.device_denormals, facts.unary_denormals)) -} - -/// Whether Metal's minimum and maximum function `op` on lanes of form `f` takes the device's -/// `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) - && math::metal_picks(f.float_fmt()) - && p.takes_driver_deviation(DriverDeviation::MetalMinMax) +/// Whether the device leaves a call lowered as `how` (on lanes of form `f`) its `f32` denormals, +/// as [`leave_denormals`] notes them: where Metal's table reads them ([`call_coverage`]). +fn coverage_left(how: FloatLowering, f: Form) -> bool { + f.float_fmt() == Some(FloatFmt::F32) && call_coverage(how) } /// Whether float function `op` is one of Metal's minimum and maximum functions, which pick one of @@ -2159,59 +1889,39 @@ 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, 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`]), `saturate` on every other float format, -/// which no device is measured to answer as Metal's `clamp(x, +0, 1)`, and `median3` and +/// `NMin`, `NMax` or `NClamp` as they are, not measured to be Metal's, noted `NativeMinMax`: +/// `fmin`, `fmax`, `min3`, `max3` and `clamp` ([`min_max_family`]) on `float` and `half` +/// ([`math::metal_picks`]), `saturate` on every float format, which no device is measured to +/// answer as Metal's `clamp(x, +0, 1)`, and `median3` and /// `fast::median3` on every device: `min(max(c, min(a, b)), max(a, b))` of the device's `NMin` and /// `NMax` (`math::median3`), Metal's answer but of two NaNs, whose NaN is the device's, of /// `fast::median3`'s two NaN first operands beside a number, which it answers as precise `median3` /// does where Metal's fast form answers `b` (undefined under fast math, MSL section 8.1), and of an /// `f32` denormal, which Metal compares as a zero. -fn native_min_max(op: FloatFn, f: Form, native_min_max: bool) -> bool { +fn native_min_max(op: FloatFn, f: Form) -> bool { let picks = math::metal_picks(f.float_fmt()); - (min_max_family(op) && ((picks && native_min_max) || (op == FloatFn::Saturate && !picks))) + (min_max_family(op) && (picks || op == FloatFn::Saturate)) || matches!(op, FloatFn::Median3 | FloatFn::FastMedian3) } -/// Why the device's 16-bit `+ - *` answers as Metal's `half` arithmetic ([`f16_arithmetic`]). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum F16Basis { - /// Measured (`DriverDeviation::MetalHalfArithmetic`): the module requires - /// `VkProperty::MetalHalfArithmetic`. - Measured, - /// The 16-bit float controls ([`narrow::half_controls`]), which its entry then declares - /// ([`narrow::computes_in_16_bits`]): no fact. Its `half` roundings take them too - /// ([`QuantizeForm::Controlled`]); a driver that folds the conversion's round trip (NVIDIA's) - /// leaves a 16-bit instruction's rounding as it is. - Controlled, -} - /// Whether the float binary operator `op` on lanes of form `f` takes the device's 16-bit -/// arithmetic ([`ArithStrategy::F16`]), and on what basis: a `half` `fadd`, `fsub` or `fmul`, on -/// one to four lanes (a chunk's own form), where profile `p` has `shaderFloat16` and takes -/// `DriverDeviation::MetalHalfArithmetic` ([`F16Basis::Measured`]) or computes under the 16-bit -/// float controls ([`F16Basis::Controlled`]). Under those controls the instruction is Metal's -/// by the Vulkan spec ([`ops::f16_binary`]). A `half` `fdiv` is Metal's precise division +/// arithmetic ([`ArithStrategy::F16`]): a `half` `fadd`, `fsub` or `fmul`, on one to four lanes +/// (a chunk's own form), where profile `p` has `shaderFloat16` and computes under the 16-bit +/// float controls ([`narrow::half_controls`]), which its entry then declares +/// ([`narrow::computes_in_16_bits`]), its `half` roundings taking them too +/// ([`QuantizeForm::Controlled`]); a driver that folds the conversion's round trip (NVIDIA's) +/// leaves a 16-bit instruction's rounding as it is. Under those controls the instruction is +/// Metal's by the Vulkan spec ([`ops::f16_binary`]). A `half` `fdiv` is Metal's precise division /// ([`divide::native`]): under those controls the device's 16-bit `OpFDiv`, its native form, and /// elsewhere the device's `float` quotient of the widened operands rounded to `half`, as Metal's /// fast and relaxed compiles answer the device's 16-bit quotient of widened operands as a `float` /// one and it has no form that keeps it apart. A `half` `frem` is not measured. -fn f16_arithmetic(p: &DeviceProfile, op: AirBin, f: Form) -> Option { - use crate::error::DriverDeviation; - let applies = matches!(op, AirBin::FAdd | AirBin::FSub | AirBin::FMul) +fn f16_arithmetic(p: &DeviceProfile, op: AirBin, f: Form) -> bool { + matches!(op, AirBin::FAdd | AirBin::FSub | AirBin::FMul) && f.float_fmt() == Some(FloatFmt::Half) && (1..=4).contains(&f.lanes) - && p.fields().leaf.float16; - if !applies { - None - } else if p.takes_driver_deviation(DriverDeviation::MetalHalfArithmetic) { - Some(F16Basis::Measured) - } else if narrow::half_controls(p) { - Some(F16Basis::Controlled) - } else { - None - } + && p.fields().leaf.float16 + && narrow::half_controls(p) } /// How [`select_call`] lowers a float function call. @@ -2229,7 +1939,7 @@ enum FloatLowering { /// that its lowering does not. struct FloatCall { how: FloatLowering, - notes: OpNotes, + notes: BTreeSet, nan: Option, } @@ -2238,21 +1948,6 @@ struct FloatCall { struct FloatFacts { /// The fused multiply-add routes ([`fma::routes`]). routes: fma::Routes, - /// Whether the profile's `float` functions are Metal's (`FloatFunctions::Metal`). - metal_functions: bool, - /// Whether the device reads `f32` denormals as Metal does ([`denormal::device_flushes`]). - device_denormals: bool, - /// Whether the device's negation, absolute value, floor and ceiling read `f32` denormals as - /// Metal's do ([`denormal::unary_kept`]). - unary_denormals: bool, - /// 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, - /// Whether the device's `fabs` answers Metal's NaN, `float` and `half` - /// ([`nan::moves_answered`]). - nan_moves: bool, } impl FloatFacts { @@ -2260,136 +1955,59 @@ impl FloatFacts { fn on(p: &DeviceProfile) -> FloatFacts { FloatFacts { routes: fma::routes(p), - metal_functions: p.fields().float_functions == FloatFunctions::Metal, - device_denormals: denormal::device_flushes(p), - unary_denormals: denormal::unary_kept(p), - nans: nan::encoding(p), - native_min_max: !p.takes_driver_deviation(crate::error::DriverDeviation::MetalMinMax), - nan_moves: nan::moves_answered(p), } } } -/// How much of a call of float function `op` (with the `fast_` prefix where `fast`) on form `f` -/// is Metal's own in an entry Metal compiles with fast math, on a device whose `float` functions -/// are Metal's. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum MetalOwn { - /// None of it: the device's instruction is not Metal's function in a fast-math module, the - /// device answers it by a near-equivalent ([`libm::Fun::device_near_equivalent`]), or no - /// `float` or `half` function is called. - No, - /// Its function and its division: a `fast_` call of no listed function (`fast::rsqrt`, - /// `fast::sqrt`), whose device instruction the module compiles as Metal's fast function, and - /// whose division is Metal's fast one. - Function, - /// Wholly: every function the call takes the device answers in a fast-math module as Metal's - /// own function ([`libm::Fun::device_answers`]), whose every word, denormals and NaNs among - /// them, is Metal's (`DriverDeviation::MetalFloatFunctions`); its division is Metal's fast - /// one. - Wholly, -} - -impl MetalOwn { - /// The call of `op` (`fast_` where `fast`) on form `f`. - fn of(op: FloatFn, fast: bool, f: Form) -> MetalOwn { - if !matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half)) { - return MetalOwn::No; - } - let uses = libm::uses(op, f); - let own = |r: &libm::Fun| r.device_answers(libm::Mode::Fast) && !r.device_near_equivalent(); - if !uses.iter().all(own) { - MetalOwn::No - } else if !uses.is_empty() { - MetalOwn::Wholly - } else if fast && f.float_fmt() == Some(FloatFmt::F32) { - MetalOwn::Function - } else { - MetalOwn::No - } - } -} - -/// The notes of a call of float function `op` (with the `fast_` prefix where `fast`) on form `f` -/// lowered as the function itself, on a profile whose `float` functions are Metal's where -/// `metal_functions`: where they are not, the device's precision where the call takes the device's -/// instruction for one of Metal's functions, `fabs`, `sign`, `fract` and `fast::sqrt` included -/// ([`FloatFn::native_instruction`], `NativeTranscendentals`), else the function's precision -/// ([`FloatFn::precision`]); `round`'s zero, C99's, on every device -/// ([`FloatFn::composed_on_every_device`], `NativeTranscendentals`); -/// and its division's (`DeviceArithmetic` for [`FloatFn::divides`], and `NativeDivision` where the -/// functions are not Metal's), and its `f32` denormals' and NaNs' where they are left to the -/// device (`denormals`, `nans`, [`device_float_notes`]). +/// The notes of a call of float function `op` on form `f` lowered as the function itself: the +/// device's precision where the call takes the device's instruction for one of Metal's functions, +/// `fabs`, `sign`, `fract` and `fast::sqrt` included ([`FloatFn::native_instruction`], +/// `NativeTranscendentals`), else the function's precision ([`FloatFn::precision`]); `round`'s +/// zero, C99's, on every device ([`FloatFn::composed_on_every_device`], `NativeTranscendentals`); +/// its division's (`DeviceArithmetic` and `NativeDivision` for [`FloatFn::divides`]); and its +/// `f32` denormals' and NaNs' where they are left to the device (`denormals`, `nans`, +/// [`device_float_notes`]). /// /// A call of precise `fmod` by its routine, whose answer is the one right value, Metal's on every /// device ([`libm::Fun::correctly_rounded`]), records no precision note, but on `half`, whose zero -/// remainder of a nonzero dividend is the `float` remainder's sign, where Metal answers `+0`, in -/// every entry on every device ([`FloatFn::half_zero_of_float`], `NativeTranscendentals`). Where the profile's -/// `float` functions are Metal's, a call -/// that is Metal's own in a fast-math entry ([`MetalOwn`]) records its function's and its -/// division's notes only outside one, and, where it is wholly Metal's own, its denormals' and -/// NaNs' too ([`OpNotes`]). Of its fast functions, `fast::atan2` is Apple's formula -/// `atan(y / x)` turned by `±π` (MSL Table 8.2) of Metal's own fast `atan` and fast reciprocal, -/// and answers Metal's word on every lane of case f6524207 through MoltenVK but two, whose -/// divisors are past `2^126`, where Table 8.2 states no accuracy for the quotient: within Apple's -/// bound, which the user's fast-math sign-off accepts ("fast-math within Apple's bound", -/// 2026-10-03), so it is Metal's own too. Its fast `sinpi`, `cospi`, and `tanpi`, the device's -/// near-equivalents, keep their notes, as does every call in an entry that keeps NaNs. +/// remainder of a nonzero dividend is the `float` remainder's sign, where Metal answers `+0`, on +/// every device ([`FloatFn::half_zero_of_float`], `NativeTranscendentals`). fn function_notes( op: FloatFn, - fast: bool, f: Form, - metal_functions: bool, (denormals, nans): (bool, bool), -) -> OpNotes { +) -> BTreeSet { let uses = libm::uses(op, f); - // Off Metal's own functions, the device's instruction for one of Metal's functions, and the - // device's `fast::sqrt`: its precision is Vulkan's, and its `f32` denormals the device's. - let native = !metal_functions; - let native_uses = native && (uses.iter().any(|r| r.native()) || op.native_instruction()); + // The device's instruction for one of Metal's functions, and the device's `fast::sqrt`: its + // precision is Vulkan's, and its `f32` denormals the device's. + let native_uses = uses.iter().any(|r| r.native()) || op.native_instruction(); let exact = !native_uses && !uses.is_empty() && uses.iter().all(|r| r.correctly_rounded()); - let mut function = BTreeSet::new(); + let mut notes = BTreeSet::new(); if native_uses { - function.insert(PrecisionNote::NativeTranscendentals); + notes.insert(PrecisionNote::NativeTranscendentals); } else if !exact { - function.extend(precision_note(op.precision())); + notes.extend(precision_note(op.precision())); } - // `round`'s composition on every device: C99's `-0`, where Metal answers `+0`. - if op.composed_on_every_device() { - function.insert(PrecisionNote::NativeTranscendentals); + // `round`'s composition on every device: C99's `-0`, where Metal answers `+0`; and a `half` + // `fmod`'s zero, the `float` remainder's sign. + if op.composed_on_every_device() || op.half_zero_of_float(f) { + notes.insert(PrecisionNote::NativeTranscendentals); } if op.divides() { - function.insert(PrecisionNote::DeviceArithmetic); - if native { - function.insert(PrecisionNote::NativeDivision); - } + notes.insert(PrecisionNote::DeviceArithmetic); + notes.insert(PrecisionNote::NativeDivision); } - let denormals = denormals || native_uses; - let environment: BTreeSet<_> = device_float_notes(f, denormals, nans).collect(); - let own = if metal_functions { - MetalOwn::of(op, fast, f) - } else { - MetalOwn::No - }; - // A `half` `fmod`'s zero, the `float` remainder's sign in either math mode. - let half_zero = BTreeSet::from_iter( - op.half_zero_of_float(f) - .then_some(PrecisionNote::NativeTranscendentals), - ); - OpNotes::unless_own(function, own != MetalOwn::No) - .with(OpNotes::unless_own(environment, own == MetalOwn::Wholly)) - .with(OpNotes::everywhere(half_zero)) + notes.extend(device_float_notes(f, denormals || native_uses, nans)); + notes } /// The note of fused multiply-add `fma`: `NativeFma` where it takes the device's `Fma` /// ([`fma::Route::Native`], [`fma::Route::F16Native`]), which [`finish`] records for every such /// route a family takes. -fn native_fma(fma: fma::Fma) -> OpNotes { +fn native_fma(fma: fma::Fma) -> BTreeSet { match fma.route { - fma::Route::Native | fma::Route::F16Native => { - OpNotes::everywhere(BTreeSet::from([PrecisionNote::NativeFma])) - } - fma::Route::Khr => OpNotes::default(), + fma::Route::Native | fma::Route::F16Native => BTreeSet::from([PrecisionNote::NativeFma]), + fma::Route::Khr => BTreeSet::new(), } } @@ -2398,8 +2016,8 @@ fn native_fma(fma: fma::Fma) -> OpNotes { /// ([`FloatFacts`]); `None` where the form refuses the function (it is not a float, or a `double` /// 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 +/// and Metal's minimum and maximum functions are the device's, noted `NativeMinMax` +/// ([`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( @@ -2410,36 +2028,24 @@ fn float_call( facts: FloatFacts, ) -> Option { let mut call = float_call_of(op, fast, fmf, f, facts)?; - // The device's `fabs` moves the NaN Metal's does where that is measured ([`moves_nan`]). - if facts.nan_moves && moves_nan(call.how, f) { - call.nan = None; - } let mut native = BTreeSet::new(); - if call.nan.is_some_and(|a| !a.device_answers(facts.nans)) { + if call.nan.is_some() { native.insert(PrecisionNote::NativeNanEncoding); } if let FloatLowering::Fn(op) = call.how { - if native_min_max(op, f, facts.native_min_max) { + if native_min_max(op, f) { native.insert(PrecisionNote::NativeMinMax); } } // The `f32` denormals the device reads where it is not measured to read them as Metal does // ([`leave_denormals`]). - if coverage_left(call.how, f, facts) { + if coverage_left(call.how, f) { native.insert(PrecisionNote::DeviceDenormals); } - call.notes = call.notes.with(OpNotes::everywhere(native)); + call.notes.extend(native); Some(call) } -/// Whether a float call lowered as `how` on form `f` moves its operand's NaN rather than computes -/// one, so that a device measured to move it as Metal does answers Metal's NaN -/// ([`nan::moves_answered`]): `fabs` on `float` and `half`. -fn moves_nan(how: FloatLowering, f: Form) -> bool { - matches!(how, FloatLowering::Fn(FloatFn::Abs)) - && matches!(f.float_fmt(), Some(FloatFmt::F32 | FloatFmt::Half)) -} - /// [`float_call`] before the device's NaN and minimum and maximum notes. fn float_call_of( op: FloatFn, @@ -2451,11 +2057,7 @@ fn float_call_of( if !f.is_float() || (f.bits() == 64 && !op.allows_f64()) { return None; } - let FloatFacts { - routes, - metal_functions, - .. - } = facts; + let routes = facts.routes; let op = refine_float(op, fast, fmf, f); // `float` and `half` fused multiply-adds take the profile's route ([`fma`]); a `bfloat` one // corrects its tie, and a `double` one is `GLSL.std.450 Fma` at the device's precision. @@ -2486,24 +2088,19 @@ fn float_call_of( // with and without fast-math flags; the device's instructions may round or sum otherwise (a // tree, an unfused sum, or, under fast-math flags, `b * (a + c)` for // `dot(float2(a, b), float2(b, c))`), noted `NativeMix` and `NativeDot`, Vulkan's bounds - // inherited from `x * (1 - a) + y * a` and the sum of products. Where the profile's `float` - // functions are Metal's, a `float` one reaches Metal's own `mix` and `dot`; a `half` one is - // the instruction on its `float` container, rounded once, or the 16-bit instruction where the - // module holds its operands at 16 bits (`spirv::half_hold`), noted. Their NaN is the - // device's, noted as for any function. + // inherited from `x * (1 - a) + y * a` and the sum of products. A `half` one is the + // instruction on its `float` container, rounded once, or the 16-bit instruction where the + // module holds its operands at 16 bits (`spirv::half_hold`). Their NaN is the device's, noted + // as for any function. if matches!(op, FloatFn::Mix | FloatFn::Dot) { let fmt = f.float_fmt()?; - let own = metal_functions && fmt == FloatFmt::F32; - let mut notes = BTreeSet::new(); - if !own { - notes.insert(if op == FloatFn::Mix { - PrecisionNote::NativeMix - } else { - PrecisionNote::NativeDot - }); - if op == FloatFn::Mix { - notes.extend(device_float_notes(f, true, false)); - } + let mut notes = BTreeSet::from([if op == FloatFn::Mix { + PrecisionNote::NativeMix + } else { + PrecisionNote::NativeDot + }]); + if op == FloatFn::Mix { + notes.extend(device_float_notes(f, true, false)); } let nan = match (op, fmt) { (FloatFn::Mix, FloatFmt::F32) => Some(nan::NanAnswer::Canonical), @@ -2511,23 +2108,22 @@ fn float_call_of( }; return Some(FloatCall { how: FloatLowering::Fn(op), - notes: OpNotes::everywhere(notes), + notes, nan, }); } // `air.fast_fmod` on `float` is Metal's composition around a fused multiply-add, of the // device's quotient; the fast-math table is single precision, so a narrow call keeps `fmod`. - // Where the profile's `float` functions are Metal's, its `fma` is Metal's own and its quotient - // Metal's fast one in a fast-math entry, so its notes hold only outside one. Metal reads a - // denormal operand as the zero of its sign and answers no denormal, in both modes; the - // device's reading is noted where the profile lacks the deviation ([`coverage_left`]). + // Metal reads a denormal operand as the zero of its sign and answers no denormal, in both + // modes; the device's reading is noted where the profile lacks the deviation + // ([`coverage_left`]). if fast && op == FloatFn::Fmod && f.float_fmt() == Some(FloatFmt::F32) { if let Some(fma) = fma::Fma::by(routes, f) { let khr = fma.route.device_float(); let notes = BTreeSet::from([PrecisionNote::DeviceArithmetic]); return Some(FloatCall { how: FloatLowering::FastFmod(fma), - notes: OpNotes::unless_own(notes, metal_functions && khr).with(native_fma(fma)), + notes: notes.into_iter().chain(native_fma(fma)).collect(), nan: khr.then_some(nan::NanAnswer::Canonical), }); } @@ -2538,30 +2134,20 @@ fn float_call_of( .and_then(|fmt| nan::function_answer(op, fast, every_flag(fmf), fmt)); let metal_nans = f.float_fmt().is_some_and(|fmt| op.metal_nans(fmt)); let nan = answer.filter(|_| !metal_nans); - // A function whose denormals Metal's table reads ([`denormal::coverage`]), and Metal's fast - // `sinpi`, `cospi` and `tanpi` where the device's functions are Metal's, are noted where the + // A function whose denormals Metal's table reads ([`denormal::covered`]) is noted where the // device's reading is left ([`call_coverage`], [`float_call`]); the device's instruction for // one of Metal's functions records its denormals itself ([`function_notes`]). - let fast_pi = matches!( - op, - FloatFn::FastSinPi | FloatFn::FastCosPi | FloatFn::FastTanPi - ); let mut notes = function_notes( op, - fast, f, - metal_functions, ( - !op.metal_denormals() - && denormal::coverage(op).is_none() - && !fast_pi - && !(facts.unary_denormals && denormal::moves_sign(op)), + !op.metal_denormals() && !denormal::covered(op), !metal_nans && answer.is_none(), ), ); // A `bfloat` or `double` `llvm.fmuladd` is fused or not, as the implementation chooses. if op == FloatFn::MulAdd { - notes.always.insert(PrecisionNote::FastMathRewrites); + notes.insert(PrecisionNote::FastMathRewrites); } Some(FloatCall { how: FloatLowering::Fn(op), @@ -2580,7 +2166,11 @@ fn float_call_of( /// Validation reads it, through the AIR symbol Metal compiles an MSL function to, to tell which /// operations the product computes as a near-equivalent of Metal's, as /// [`PrecisionNote::of_math_call`]. -pub fn float_call_notes(call: Math, fmf: FastMath, p: &DeviceProfile) -> Option { +pub fn float_call_notes( + call: Math, + fmf: FastMath, + p: &DeviceProfile, +) -> Option> { let Ok(Fun::Float(op)) = air_math(call.f) else { return None; }; @@ -2598,20 +2188,10 @@ pub fn float_call_notes(call: Math, fmf: FastMath, p: &DeviceProfile) -> Option< float_call(op, fast, fmf, f, FloatFacts::on(p)).map(|lowered| lowered.notes) } -/// The mode of the `float` functions of an entry of math mode `math` on profile `p` -/// ([`ArithPlan::metal_functions`]): Metal's in that mode where the profile's are Metal's, -/// `None` elsewhere. -fn metal_functions_in(p: &DeviceProfile, math: EntryMath) -> Option { - (p.fields().float_functions == FloatFunctions::Metal).then_some(match math { - EntryMath::Fast => libm::Mode::Fast, - EntryMath::Precise => libm::Mode::Precise, - }) -} - impl PrecisionNote { /// The precision notes a compile for profile `p` records for the AIR float operator `op` /// (`fadd`, `fsub`, `fmul`, `fdiv` or `frem`) on lanes of `width`, with fast-math flags - /// `fmf`, in an entry of math mode `math`: what a module states for the operator itself. Its + /// `fmf`: what a module states for the operator itself. Its /// operands' instructions record their own, and a `half` result's rounding is noted from the /// emitted module. `None` for an integer operator. The precision contract a tool reads to tell /// which operations the crate computes as a near-equivalent of Metal's. @@ -2620,28 +2200,26 @@ impl PrecisionNote { width: FloatWidth, fmf: FastMath, p: &DeviceProfile, - math: EntryMath, ) -> Option> { let fmt = match width { FloatWidth::F16 => FloatFmt::Half, FloatWidth::F32 => FloatFmt::F32, FloatWidth::F64 => FloatFmt::F64, }; - float_binop_notes(op, fmt, fmf, p).map(|notes| notes.in_entry(metal_functions_in(p, math))) + float_binop_notes(op, fmt, fmf, p) } /// The precision notes a compile for profile `p` records for the AIR math call `call` (an /// `air.*` function, as `metal2vulkan_air::intrinsics::AirIntrinsic::parse` decodes its - /// symbol) with fast-math flags `fmf`, in an entry of math mode `math`: the notes for the call + /// symbol) with fast-math flags `fmf`: the notes for the call /// itself. `None` where the crate does not lower `call` as a float function: an integer /// function, `sincos` (lowered with its store), or a type it refuses. pub fn of_math_call( call: Math, fmf: FastMath, p: &DeviceProfile, - math: EntryMath, ) -> Option> { - float_call_notes(call, fmf, p).map(|notes| notes.in_entry(metal_functions_in(p, math))) + float_call_notes(call, fmf, p) } } @@ -2682,7 +2260,6 @@ pub(super) fn select_sincos( // 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; for op in [sin, cos] { let answer = f .float_fmt() @@ -2690,12 +2267,10 @@ pub(super) fn select_sincos( let metal_nans = f.float_fmt().is_some_and(|fmt| op.metal_nans(fmt)); let notes = function_notes( op, - fast, f, - metal_functions, (!op.metal_denormals(), !metal_nans && answer.is_none()), ); - record(cx, notes); + cx.precision.extend(notes); note_native_nan(cx, answer.filter(|_| !metal_nans)); } fp_env(cx, call.fmf, f); @@ -2758,24 +2333,7 @@ fn select_pack( } // The device's conversion: GLSL.std.450's instruction for the format, or its multiply, // `RoundEven` and clamp, whose rounding Vulkan leaves to the device (`DevicePackConversion`). - // Where the profile's `float` functions are Metal's, a `float` one of the four formats - // GLSL.std.450 names reaches Metal's own `pack_float_to_*` or `unpack_*_to_float`. Where the - // profile takes `MetalPackConversions`, the forms measured to be Metal's (`pack::measured`) - // are, and the module requires that property. - let fmt = floats.float_fmt(); - let own = FloatFacts::on(cx.profile).metal_functions - && fmt == Some(FloatFmt::F32) - && pack::instruction(p.format, p.dir).is_some(); - let measured = !own - && cx - .profile - .takes_driver_deviation(crate::error::DriverDeviation::MetalPackConversions) - && fmt.is_some_and(|f| pack::measured(p.format, p.dir, f)); - if measured { - cx.families.arith.metal_packs = true; - } else if !own { - cx.precision.insert(PrecisionNote::DevicePackConversion); - } + cx.precision.insert(PrecisionNote::DevicePackConversion); Ok(ArithStrategy::Pack { dir: p.dir, format: p.format, @@ -2885,12 +2443,8 @@ fn select_convert( return Err(cx.invariant("an air.convert whose kinds disagree with its types")); } let s = ArithStrategy::Convert { kind, from, to }; - // Metal's widening of a `half` NaN, as `fpext`'s ([`moved_nan`]). + // Metal's widening of a `half` NaN, as `fpext`'s. let nan = match (kind, from.float_fmt(), to.float_fmt()) { - (ConvertKind::Float, Some(FloatFmt::Half), Some(FloatFmt::F32)) => { - let answer = nan::convert_answer(FloatFmt::Half, FloatFmt::F32); - moved_nan(cx, answer, true) - } (ConvertKind::Float, Some(a), Some(b)) => nan::convert_answer(a, b), _ => None, }; diff --git a/crates/metal2vulkan/src/lower/arith/nan.rs b/crates/metal2vulkan/src/lower/arith/nan.rs index 3110d86d9..715a7ac63 100644 --- a/crates/metal2vulkan/src/lower/arith/nan.rs +++ b/crates/metal2vulkan/src/lower/arith/nan.rs @@ -20,10 +20,7 @@ //! these classes. //! //! 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`]). +//! `PrecisionNote::NativeNanEncoding` where Metal answers a NaN: every answer these tables give. //! //! [`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 @@ -31,8 +28,6 @@ //! float mode reaches: the conversions and functions whose answer at a NaN is a number test so. use crate::air::ir::{BinOp as AirBin, CastOp, FastMath}; -use crate::device::profile::NanEncoding; -use crate::device::DeviceProfile; use crate::lower::arith::legal::{FloatFmt, Form, Held}; use crate::lower::arith::math::FloatFn; use crate::lower::arith::narrow::u32_form; @@ -51,9 +46,7 @@ pub enum NanAnswer { /// `0x7FC00000` for a result the device computes exactly, passing its operand's NaN on: the /// widening of a `half` to `float`, which a `half` held widened leaves no device operation at /// all, and `half` `fneg` and `fabs`, which a device computes on the sign alone. No device's - /// arithmetic answers it, so the canonical-NaN fact does not leave it to the device; where the - /// device's moves of a NaN are measured ([`moves_answered`]), the held `half` is its widening's - /// canonical NaN, so the widening and `fabs` answer it. + /// arithmetic answers it, so it is noted on every device. CanonicalExact, /// The canonical NaN with a NaN first operand's sign, and `+` for a NaN of another origin (a /// domain error): precise `asin`, `atan`, `asinh`, `atanh`. @@ -71,20 +64,6 @@ pub enum NanAnswer { BaseToExponentOne, } -impl NanAnswer { - /// 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 => false, - } - } -} - /// How [`is_nan`] tests a value for a NaN. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NanTest { @@ -460,19 +439,3 @@ fn flagged_precise(op: FloatFn) -> bool { F::Sin | F::Cos | F::Tan | F::Asin | F::Acos | F::Atan | F::Asinh | F::Atanh | F::Atan2 ) } - -/// The profile's NaN encoding. -pub fn encoding(p: &DeviceProfile) -> NanEncoding { - p.fields().nan_encoding -} - -/// Whether profile `p`'s device is measured to answer Metal's NaN where an operation moves a NaN -/// rather than computes one (`DriverDeviation::MetalNanMoves`): its widening of a `half` to -/// `float` ([`NanAnswer::CanonicalExact`]), its `float` `fneg` and `fabs` -/// ([`NanAnswer::Operand`]) and its `half` `fabs` ([`NanAnswer::CanonicalExact`]), each where the -/// module moves its `half` values only as measured (`narrow::moves_unfolded`). A `half` `fneg`, -/// whose held result keeps the operand's NaN with its sign flipped unless the driver's compiler -/// moves the negation onto the `half`, is not among them. -pub fn moves_answered(p: &DeviceProfile) -> bool { - p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves) -} diff --git a/crates/metal2vulkan/src/lower/arith/narrow.rs b/crates/metal2vulkan/src/lower/arith/narrow.rs index b48920c7f..3d8e080e6 100644 --- a/crates/metal2vulkan/src/lower/arith/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/narrow.rs @@ -21,8 +21,7 @@ //! exact integer round-to-nearest-even of the `f32` bits. Where the device's 16-bit `+ - *`, kept //! apart, is Metal's `half` arithmetic and the profile has `shaderFloat16`, a `half` `+ - *` is //! that instruction between exact conversions instead, with no rounding here (`ops::f16_binary`): -//! where it is measured to be (`DriverDeviation::MetalHalfArithmetic`), and under those float -//! controls ([`half_controls`]), which make it so by the Vulkan spec and which the entry then +//! under those float controls ([`half_controls`]), which make it so by the Vulkan spec and which the entry then //! declares ([`computes_in_16_bits`]), on a driver that folds the conversion's round trip too //! (NVIDIA's: the fold is the pair's, a 16-bit instruction keeps its rounding); there the emitted //! module holds every exact `half` at 16 bits, its moves, minimums, maximums and clamps, its @@ -54,8 +53,6 @@ //! `f32` ([`f64_to_f32_odd`]), and a `bfloat` fused multiply-add corrects its one inexact case //! ([`bf16_fma`]), so the final rounding is the only one that counts. -mod merges; - use crate::budget::Meter; use crate::device::profile::Independence; use crate::device::DeviceProfile; @@ -67,8 +64,8 @@ use crate::spirv::builder::{FunctionBuilder, NarrowFmt, QuantizeForm}; use crate::spirv::error::{BResult, BuildError, TypeRule}; use crate::spirv::ids::Value; use crate::spirv::ir::{ - BinOp, ConstBits, ConstKind, Constant, ConvOp, ExecMode, GlslOp, Inst, StorageClass, - Terminator, Type, TypedModule, UnOp, ValueOrigin, + BinOp, ConstBits, ConstKind, Constant, ConvOp, ExecMode, GlslOp, Inst, Type, TypedModule, UnOp, + ValueOrigin, }; /// The unsigned 32-bit integer form with `f`'s lanes. @@ -179,11 +176,6 @@ pub fn native_rounding(form: QuantizeForm) -> Option { /// rounded at all (the note's stated bound), and the store's conversion to bits rounds it /// ([`converted_bits`]). fn converted(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult { - converted_pair(fb, wide, x).map(|(_, w)| w) -} - -/// [`converted`]'s pair: the narrowing to 16 bits and its widening back. -fn converted_pair(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult<(Value, Value)> { let e = fb.module().ty(Type::Float { width: 16 })?; let h = match wide.lanes { 1 => e, @@ -191,26 +183,7 @@ fn converted_pair(fb: &mut FunctionBuilder<'_>, wide: Form, x: Value) -> BResult }; let w = ty(fb, wide)?; let n = fb.convert(ConvOp::FConvert, x, h)?; - Ok((n, fb.convert(ConvOp::FConvert, n, w)?)) -} - -/// [`round`] of a `float` the function holds to `half` (an AIR `fptrunc` or `air.convert` of a -/// `float`, [`resize`], and a texel's value, [`round_texel`]): the conversion Metal's compiler -/// compiles from the AIR's own, which -/// `DriverDeviation::MetalHalfConversion` measures to be Metal's `half(float)` whatever computed -/// the `float` ([`rounds_unmeasured`]). In [`QuantizeForm::Converted`] the pair's narrowing is -/// recorded as measured (`ModuleBuilder::note_measured_rounding`); every other form rounds as -/// [`round`] does. A `half` an operation or a function computes in `float` is not this form: -/// Metal computes it otherwise (its `half` `tanh`), and it takes [`round`]. -pub fn round_measured(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { - match (f.held, fb.module().quantize_form()) { - (Held::Float(FloatFmt::Half), QuantizeForm::Converted) => { - let (n, w) = converted_pair(fb, f.with(Held::Float(FloatFmt::F32)), x)?; - fb.module().note_measured_rounding(n); - Ok(w) - } - _ => round(fb, f, x), - } + fb.convert(ConvOp::FConvert, n, w) } /// `x` (`f32` lanes of form `wide`) rounded to `half` by the device's conversion to 16 bits and @@ -349,112 +322,6 @@ pub fn rounds_by_conversion(m: &TypedModule, meter: &mut Meter) -> Result Result { - let width = |v: Value| -> Option { - let ty = m.value(v).ok()?.ty; - let ty = match m.types().get(ty).ok()? { - Type::Vector { elem, .. } => *elem, - _ => ty, - }; - match m.types().get(ty).ok()? { - Type::Float { width } => Some(*width), - _ => None, - } - }; - let words = m.values().len().div_ceil(64); - let bytes = 8 * m.values().len() + 8 * words; - meter.charge(bytes)?; - // Each instruction result's definition. - let mut def: Vec> = vec![None; m.values().len()]; - for n in m.blocks().iter().flat_map(|b| &b.insts) { - if let Some(slot) = n.result.and_then(|r| def.get_mut(r.index())) { - *slot = Some(&n.inst); - } - } - let image = |v: Value| -> bool { - let at = |v: Value| def.get(v.index()).copied().flatten(); - let direct = |i: Option<&Inst>| { - matches!( - i, - Some( - Inst::ImageFetch { .. } - | Inst::ImageRead { .. } - | Inst::ImageSample { .. } - | Inst::ImageGather { .. } - | Inst::ImageDrefGather { .. } - ) - ) - }; - match at(v) { - Some(Inst::CompositeExtract { composite, .. }) => direct(at(*composite)), - i => direct(i), - } - }; - let texel = |v: Value| -> bool { - if image(v) { - return true; - } - let Ok(ValueOrigin::Param { func, index }) = m.value(v).map(|d| d.origin) else { - return false; - }; - let mut calls = m - .blocks() - .iter() - .flat_map(|b| &b.insts) - .filter_map(|n| match &n.inst { - Inst::Call { func: f, args } if *f == func => Some(args), - _ => None, - }) - .peekable(); - calls.peek().is_some() - && calls.all(|args| args.get(index as usize).is_some_and(|&a| image(a))) - }; - let fconverts = || { - m.blocks() - .iter() - .flat_map(|b| &b.insts) - .filter_map(|n| match (&n.inst, n.result) { - ( - Inst::Convert { - op: ConvOp::FConvert, - a, - .. - }, - Some(r), - ) => Some((*a, r)), - _ => None, - }) - }; - // The narrowings some conversion widens back. - let mut widened = vec![0u64; words]; - for (a, r) in fconverts() { - if width(a) == Some(16) && width(r) == Some(32) { - set_bit(&mut widened, a); - } - } - let found = fconverts().any(|(a, r)| { - width(a) == Some(32) - && width(r) == Some(16) - && has_bit(&widened, r) - && !m.measured_roundings().contains(&r) - && !texel(a) - }); - drop((def, widened)); - meter.release(bytes); - Ok(found) -} - /// An upper estimate of the SPIR-V words of one [`round_texel`] on form `f`: [`round`]'s, and the /// NaN test's four instructions with their two constants. pub fn round_texel_words(f: Form) -> u32 { @@ -479,25 +346,21 @@ pub fn round_texel_words(f: Form) -> u32 { /// 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 `half` texel rounds as [`round_measured`] rounds a `float` the function holds: in -/// [`QuantizeForm::Converted`] the pair's narrowing is recorded as measured -/// (`ModuleBuilder::note_measured_rounding`), the device's conversion of the texel's `f32` value, -/// which `DriverDeviation::MetalHalfConversion` measures to be Metal's `half(float)` whatever -/// computed it, so the module records no `PrecisionNote::NativeHalfConversion` for it there. That -/// holds for a texel the module decodes itself (`extended_range::decode`) and for a merge of texels -/// (a heap read's phi of its fetch and its decode routine's texel) as for an image instruction's. -/// Where Metal's `half` texel is not that rounding of the texel's value, the access records its +/// A `half` texel rounds as [`round`] rounds a `float` the function holds, in +/// [`QuantizeForm::Converted`] by the device's conversion of the texel's `f32` value, which the +/// module records as `PrecisionNote::NativeHalfConversion`. That holds for a texel the module +/// decodes itself (`extended_range::decode`) and for a merge of texels (a heap read's phi of its +/// fetch and its decode routine's texel) as for an image instruction's. Where Metal's `half` texel +/// is not that rounding of the texel's value, the access records its /// own note: `PrecisionNote::HalfTexelConversion` (by the bound class at a slot; outright for a /// heap element and a depth texture) or, for a decoded texel, `PrecisionNote::DevicePackConversion` /// (whose bound states the `half`'s narrowing against Metal's rounding with ties away from zero). pub fn round_texel(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { let native = fb.module().native_half(); match f.held { - Held::Float(FloatFmt::Half) if native || fb.module().native_half_nans() => { - round_measured(fb, f, x) - } + Held::Float(FloatFmt::Half) if native || fb.module().native_half_nans() => round(fb, f, x), Held::Float(FloatFmt::Half) => { - let r = round_measured(fb, f, x)?; + let r = round(fb, f, x)?; let u = u32_form(f); let ut = ty(fb, u)?; let b = fb.convert(ConvOp::Bitcast, x, ut)?; @@ -947,9 +810,7 @@ fn encode(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult { /// device's (the SPIR-V spec's `SignedZeroInfNanPreserve`: "Bit patterns for NaNs might not be /// preserved"), where Metal moves a `half` NaN with its bits, and a denormal, which the device may /// flush to the zero of its sign without `DenormPreserve` for 16 bits: kept under the float -/// controls ([`QuantizeForm::Controlled`], [`controlled_modes`]), measured kept on MoltenVK -/// (`DriverDeviation::MetalHalfArithmetic`, whose measurement narrows every `half`), and elsewhere -/// within `PrecisionNote::NativeHalfConversion`'s bound; the module records +/// controls ([`QuantizeForm::Controlled`], [`controlled_modes`]), and elsewhere within `PrecisionNote::NativeHalfConversion`'s bound; the module records /// `PrecisionNote::NativeNanEncoding` ([`encodes_bits`]). A value that is no `half` value (under /// native half rounding the device's compiler may fold [`converted`]'s pair and hand `x` on /// unrounded, as NVIDIA's and lavapipe's do) takes the device's rounding, within @@ -1046,8 +907,7 @@ fn packed_bits(fb: &mut FunctionBuilder<'_>, f: Form, x: Value) -> BResult Result { let packs = m.blocks().iter().flat_map(|b| &b.insts).any(|n| { @@ -1418,9 +1278,8 @@ fn unpacked_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResul /// every `half` NaN to `0x7FC00000` and moves one unwidened with its bits; the module records /// `PrecisionNote::NativeNanEncoding` ([`widens_bits`]). A denormal "obtained via unpacking an /// integer into a vector of values with smaller bit width" is kept under `DenormPreserve` for 16 -/// bits, which the float controls declare ([`QuantizeForm::Controlled`], [`controlled_modes`]); on -/// MoltenVK the measured `DriverDeviation::MetalHalfArithmetic` reads every `half` through this -/// widening as Metal widens it, and the module requires that fact; elsewhere the device may flush +/// bits, which the float controls declare ([`QuantizeForm::Controlled`], [`controlled_modes`]); +/// elsewhere the device may flush /// it to the zero of its sign, within `PrecisionNote::NativeHalfConversion`'s bound, which the /// module records. fn device_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult { @@ -1470,11 +1329,9 @@ fn device_from_bits(fb: &mut FunctionBuilder<'_>, f: Form, h: Value) -> BResult< /// [`QuantizeForm::Device`]), or an `OpFConvert` to 32 bits of an `OpBitcast` to a 16-bit float or /// a vector of them, or of 16-bit floats taken from one by a component extract or a shuffle /// ([`device_from_bits`]). The module then records `PrecisionNote::NativeNanEncoding` (a NaN's -/// bits the device's) unless the device's moves of a NaN are measured to be Metal's -/// ([`moves_unfolded`]); under the float controls ([`QuantizeForm::Controlled`]) its entry -/// declares [`controlled_modes`], and elsewhere its denormals are the measured fact's -/// (`DriverDeviation::MetalHalfArithmetic`, which measures the conversion, not the unpack) or the -/// device's (`PrecisionNote::NativeHalfConversion`). The device's 16-bit arithmetic and +/// bits the device's); under the float controls ([`QuantizeForm::Controlled`]) its entry +/// declares [`controlled_modes`], and elsewhere its denormals are the device's +/// (`PrecisionNote::NativeHalfConversion`). The device's 16-bit arithmetic and /// conversions widen what they compute, which no bitcast gives. At most four passes over the /// instructions, with three bits per value of the module charged to `meter` while they run. pub fn widens_bits(m: &TypedModule, meter: &mut Meter) -> Result { @@ -1567,221 +1424,6 @@ fn has_bit(bits: &[u64], v: Value) -> bool { .is_some_and(|w| w & (1 << (v.index() % 64)) != 0) } -/// Whether module `m` moves a `half` NaN where the device's compiler is not measured to fold the -/// widening and the narrowing that hold it (`DriverDeviation::MetalNanMoves`), so that its bits -/// stay the device's. A value a `half` read from its bits widens to ([`widens_bits`]), moved -/// through phis, selects, copies, composites and a function's scalar or vector `float` variable -/// (stored and loaded, which the driver's compiler keeps in the registers), may reach a -/// conversion (its bits, by a bitcast, only as stored to a buffer or to workgroup memory), an -/// arithmetic or comparison instruction, a fused multiply-add, a derivative, a `GLSL.std.450` -/// function other than `FrexpStruct`, `ModfStruct` and `Ldexp`, each of which computes a value -/// whose NaN Metal answers from the widened value's or its own note records, and a store to a -/// buffer or to workgroup memory, which holds a `float` there, and a texture write's store of it -/// as its texel (`TypedModule::stored_texels`), whose stored NaN the write's own notes account for -/// under the format it stores (`lower::texture::half_write_nans` and `half_storage_facts`); -/// anything else (a store to another class, a call, a return, an atomic, a group or another image -/// operation, or its bits read) carries the widened `float` out of the registers or reads its bits -/// before any narrowing. The module holding a 32-bit float constant that is a NaN other than -/// `0x7FC00000`, such as a `half` NaN constant held widened with its payload, which no conversion -/// of the device made, is unfolded too, and so is a module that merges a widened value a select -/// took against a value it does not hold widened with another widened value, member by member -/// where composites carry them (`merges::merges_mixed_selects`), which Metal's compiler does not -/// fold. The measurement covers moves through the registers, and `half` values held as the -/// device's conversions made them. One pass over the constants, then a pass over the instructions -/// per round of the moves' closure and two more, with eight bits per value of the module charged -/// to `meter` while it runs (and the merges' records while they run). -pub fn moves_unfolded(m: &TypedModule, meter: &mut Meter) -> Result { - let float32 = |ty| matches!(m.types().get(ty), Ok(Type::Float { width: 32 })); - let payload = m.consts().iter().any(|(_, c)| match &c.kind { - ConstKind::Plain(Constant::Scalar { ty, bits }) if float32(*ty) => { - let b = bits.0 as u32; - b & 0x7F80_0000 == 0x7F80_0000 && b & 0x007F_FFFF != 0 && b != 0x7FC0_0000 - } - _ => false, - }); - if payload { - return Ok(true); - } - let words = m.values().len().div_ceil(64); - // The class of pointer `ptr`, and the type it points to. - let pointer = |ptr| { - m.value(ptr).ok().and_then(|v| match m.types().get(v.ty) { - Ok(Type::Pointer { class, pointee }) => Some((*class, *pointee)), - _ => None, - }) - }; - // Whether pointer `ptr` is to a function's scalar or vector `float` variable. - let local_float = |ptr| match pointer(ptr) { - Some((StorageClass::Function, pointee)) => { - let lane = match m.types().get(pointee) { - Ok(Type::Vector { elem, .. }) => *elem, - _ => pointee, - }; - float32(lane) - } - _ => false, - }; - meter.charge(48 * words)?; - let carried = widenings(m, meter).and_then(|mut widened| { - // The widened values' bits, by a bitcast and the moves. - let mut bits = vec![0u64; words]; - // The moves' closure: a phi, a select, a copy or a composite of a widened value is one, - // and of its bits. - let mut grew = true; - while grew { - grew = false; - for b in m.blocks() { - for phi in &b.phis { - for set in [&mut widened, &mut bits] { - if !has_bit(set, phi.result) - && phi.incoming.iter().any(|(v, _)| has_bit(set, *v)) - { - set_bit(set, phi.result); - grew = true; - } - } - } - for n in &b.insts { - // A function's `float` variable a widened value is stored to holds one. - if let Inst::Store { ptr, value, .. } = &n.inst { - if has_bit(&widened, *value) - && local_float(*ptr) - && !has_bit(&widened, *ptr) - { - set_bit(&mut widened, *ptr); - grew = true; - } - continue; - } - let Some(r) = n.result else { continue }; - if let Inst::Load { ptr, .. } = &n.inst { - if has_bit(&widened, *ptr) && !has_bit(&widened, r) { - set_bit(&mut widened, r); - grew = true; - } - continue; - } - if let Inst::Convert { - op: ConvOp::Bitcast, - a, - .. - } = &n.inst - { - if has_bit(&widened, *a) && !has_bit(&bits, r) { - set_bit(&mut bits, r); - grew = true; - } - continue; - } - if !moves(&n.inst) { - continue; - } - for set in [&mut widened, &mut bits] { - let mut from = false; - n.inst.for_each_value(|v| from |= has_bit(set, v)); - if from && !has_bit(set, r) { - set_bit(set, r); - grew = true; - } - } - } - } - } - // A merge of a widened value a select took against a value it does not hold widened - // (the translation's bounds check selects a read against `0`) with another widened value, - // by a phi or by stores to one function variable, the two in a composite's members too: - // Metal's compiler widens and narrows the NaN there, where it folds each of the two moves - // alone (measured). - if merges::merges_mixed_selects(m, &widened, &local_float, meter)? { - return Ok(true); - } - // Whether pointer `ptr` is to a buffer or to workgroup memory. - let held_as_float = |ptr| { - matches!( - pointer(ptr), - Some(( - StorageClass::StorageBuffer - | StorageClass::PhysicalStorageBuffer - | StorageClass::Workgroup, - _ - )) - ) - }; - Ok(m.blocks().iter().any(|b| { - let returned = matches!( - b.term, - Terminator::ReturnValue(v) if has_bit(&widened, v) || has_bit(&bits, v) - ); - returned - || b.insts.iter().filter(|n| !moves(&n.inst)).any(|n| { - let (mut from, mut read) = (false, false); - n.inst.for_each_value(|v| { - from |= has_bit(&widened, v); - read |= has_bit(&bits, v); - }); - match &n.inst { - Inst::Store { ptr, value, .. } => { - has_bit(&bits, *ptr) - || (has_bit(&widened, *value) - && !held_as_float(*ptr) - && !local_float(*ptr)) - || (has_bit(&bits, *value) && !held_as_float(*ptr)) - } - Inst::Load { .. } => false, - Inst::ImageWrite { texel, .. } => { - read || (from - && !(has_bit(&widened, *texel) - && m.stored_texels().contains(texel))) - } - Inst::AtomicStore { ptr, .. } => { - from || has_bit(&widened, *ptr) || has_bit(&bits, *ptr) - } - Inst::Convert { - op: ConvOp::Bitcast, - .. - } => read, - inst => read || (from && !computes(inst)), - } - }) - })) - }); - meter.release(48 * words); - carried -} - -/// Whether `inst` moves its operands' values into its result unchanged ([`moves_unfolded`]). -fn moves(inst: &Inst) -> bool { - matches!( - inst, - Inst::Select { .. } - | Inst::Unary { - op: UnOp::CopyObject, - .. - } - | Inst::CompositeConstruct { .. } - | Inst::CompositeExtract { .. } - | Inst::CompositeInsert { .. } - | Inst::VectorExtractDynamic { .. } - | Inst::VectorInsertDynamic { .. } - | Inst::VectorShuffle { .. } - ) -} - -/// Whether `inst` computes a value from its operands' in the registers, whose NaN Metal answers -/// from the widened value's or its own note records ([`moves_unfolded`]). -fn computes(inst: &Inst) -> bool { - match inst { - Inst::Convert { op, .. } => *op != ConvOp::Bitcast, - Inst::Glsl { op, .. } => { - !matches!(op, GlslOp::FrexpStruct | GlslOp::ModfStruct | GlslOp::Ldexp) - } - Inst::Unary { .. } | Inst::Binary { .. } | Inst::Fma { .. } | Inst::Derivative { .. } => { - true - } - _ => false, - } -} - /// Whether module `m` computes in 16-bit floats: an `OpFAdd`, `OpFSub`, `OpFMul` or `OpFDiv`, an /// `OpFmaKHR`, or a `GLSL.std.450 Fma` or `Sqrt` whose result is a 16-bit float or a vector of /// them, the device's own `half` arithmetic (`super::ops::f16_binary`, `super::fma`, @@ -1992,8 +1634,6 @@ pub fn resize(fb: &mut FunctionBuilder<'_>, from: Form, to: Form, x: Value) -> B ); if widening { Ok(x) - } else if (src, dst) == (FloatFmt::F32, FloatFmt::Half) { - round_measured(fb, to, x) } else { round(fb, to, x) } diff --git a/crates/metal2vulkan/src/lower/arith/narrow/merges.rs b/crates/metal2vulkan/src/lower/arith/narrow/merges.rs deleted file mode 100644 index 791c7dcd7..000000000 --- a/crates/metal2vulkan/src/lower/arith/narrow/merges.rs +++ /dev/null @@ -1,350 +0,0 @@ -//! The merges of a widened `half` that a select took against a value it does not hold widened -//! with another widened value, followed through the composites that carry them -//! ([`merges_mixed_selects`], `narrow::moves_unfolded`). -//! -//! A select carried inside a composite (a texel read's `{T, i8}`, a struct, an array, a vector) -//! and merged with it is taken for the measured merge of its members: not measured through a -//! composite, but its members' merges are the measured shape once a compiler splits it into them. -//! The analysis therefore asks, member by member, what a value holds: a path of -//! literal indices names a member (a struct's member, an array's element, a matrix's column, a -//! vector's lane), the empty path the value itself. A construct, an insert, an extract and a copy -//! carry each member through unchanged; a select and a phi take each member from their operands. - -use super::has_bit; -use crate::budget::Meter; -use crate::error::Error; -use crate::spirv::ids::{BlockId, Value}; -use crate::spirv::ir::{Inst, Type, TypedModule, UnOp}; -use std::collections::HashMap; - -/// The most steps one question of a value's member follows ([`Members::widened_at`], -/// [`Members::mixed_at`]): a bound on the walk. Past it a member counts as widened wherever its -/// value is widened, so a merge is never missed for it. -const STEPS: usize = 256; - -/// The most members of one value's type the merge checks look at; a type with more counts as -/// merging wherever two of its incoming values are widened. -const NODES: usize = 256; - -/// The bytes one value's record holds while the analysis runs, as the meter charges it: the -/// entry and the map's slack. -const RECORD_BYTES: usize = std::mem::size_of::<(Value, Made<'static>)>() + 16; - -/// How module `m`'s value was made, where it carries its operands' members. -enum Made<'a> { - Construct(&'a [Value]), - Insert { - object: Value, - composite: Value, - indices: &'a [u32], - }, - Extract { - composite: Value, - indices: &'a [u32], - }, - Copy(Value), - Select { - t: Value, - f: Value, - }, - Phi(&'a [(Value, BlockId)]), -} - -/// The values of a module that carry members, and its widened values. -struct Members<'a> { - m: &'a TypedModule, - made: HashMap>, - widened: &'a [u64], -} - -impl<'a> Members<'a> { - fn new(m: &'a TypedModule, widened: &'a [u64]) -> Members<'a> { - let mut made = HashMap::new(); - for b in m.blocks() { - for phi in &b.phis { - made.insert(phi.result, Made::Phi(&phi.incoming)); - } - for n in &b.insts { - let Some(r) = n.result else { continue }; - let carried = match &n.inst { - Inst::CompositeConstruct { parts } => Made::Construct(parts), - Inst::CompositeInsert { - object, - composite, - indices, - } => Made::Insert { - object: *object, - composite: *composite, - indices, - }, - Inst::CompositeExtract { composite, indices } => Made::Extract { - composite: *composite, - indices, - }, - Inst::Unary { - op: UnOp::CopyObject, - a, - } => Made::Copy(*a), - Inst::Select { t, f, .. } => Made::Select { t: *t, f: *f }, - _ => continue, - }; - made.insert(r, carried); - } - } - Members { m, made, widened } - } - - /// The type of value `v`. - fn ty(&self, v: Value) -> Option<&'a Type> { - let ty = self.m.value(v).ok()?.ty; - self.m.types().get(ty).ok() - } - - /// The lanes of value `v`: a vector's, 1 for a scalar. - fn lanes(&self, v: Value) -> u32 { - match self.ty(v) { - Some(Type::Vector { len, .. }) => u32::from(*len), - _ => 1, - } - } - - /// The part of construct `v` (of `parts`) that holds member `path`, and the path inside it: - /// a vector's lane is in the part that supplies it, every other composite's member is its - /// part. `None` for the empty path or one out of range. - fn part(&self, v: Value, parts: &[Value], path: &[u32]) -> Option<(Value, Vec)> { - let (&first, rest) = path.split_first()?; - if !matches!(self.ty(v), Some(Type::Vector { .. })) { - return Some((*parts.get(first as usize)?, rest.to_vec())); - } - let mut lane = first; - for &p in parts { - let n = self.lanes(p); - if lane < n { - let inside = match matches!(self.ty(p), Some(Type::Vector { .. })) { - true => [&[lane][..], rest].concat(), - false => rest.to_vec(), - }; - return Some((p, inside)); - } - lane -= n; - } - None - } - - /// Whether member `path` of `v` holds a widened value, wholly or in part: the member of a - /// construct's part, an insert's object or composite, an extract's composite, a copy's - /// operand, a select's or a phi's operands, else (a value made otherwise) `v`'s own mark. - fn widened_at(&self, v: Value, path: &[u32]) -> bool { - let mut seen = Vec::new(); - let mut steps = STEPS; - self.widened_in(v, path.to_vec(), &mut seen, &mut steps) - } - - fn widened_in( - &self, - v: Value, - path: Vec, - seen: &mut Vec, - steps: &mut usize, - ) -> bool { - let own = has_bit(self.widened, v); - if *steps == 0 { - return own; - } - *steps -= 1; - match self.made.get(&v) { - Some(Made::Construct(parts)) => match self.part(v, parts, &path) { - Some((p, inside)) => self.widened_in(p, inside, seen, steps), - None => own, - }, - Some(Made::Insert { - object, - composite, - indices, - }) => { - let inside = path.strip_prefix(*indices).map(<[u32]>::to_vec); - if path.is_empty() { - own - } else if let Some(inside) = inside { - self.widened_in(*object, inside, seen, steps) - } else if indices.starts_with(&path) { - self.widened_in(*object, Vec::new(), seen, steps) - || self.widened_in(*composite, path, seen, steps) - } else { - self.widened_in(*composite, path, seen, steps) - } - } - Some(Made::Extract { composite, indices }) => { - let full = [&indices[..], &path[..]].concat(); - self.widened_in(*composite, full, seen, steps) - } - Some(Made::Copy(a)) => self.widened_in(*a, path, seen, steps), - Some(Made::Select { t, f }) => { - self.widened_in(*t, path.clone(), seen, steps) - || self.widened_in(*f, path, seen, steps) - } - Some(Made::Phi(incoming)) => { - if seen.contains(&v) { - return false; - } - seen.push(v); - incoming - .iter() - .any(|(i, _)| self.widened_in(*i, path.clone(), seen, steps)) - } - None => own, - } - } - - /// Whether member `path` of `v` is a select of a widened value against a value it does not - /// hold widened, carried there by constructs, inserts, extracts and copies (a phi carries - /// none: a merge then a select keeps every NaN's bits, measured). A select of composites - /// selects each member: its member `path` is such a select where one operand's member is - /// widened and the other's is not. - fn mixed_at(&self, v: Value, path: &[u32]) -> bool { - let mut steps = STEPS; - let mut at = (v, path.to_vec()); - loop { - let (v, path) = at; - if steps == 0 { - return has_bit(self.widened, v); - } - steps -= 1; - at = match self.made.get(&v) { - Some(Made::Select { t, f }) => { - return self.widened_at(*t, &path) != self.widened_at(*f, &path); - } - Some(Made::Construct(parts)) => match self.part(v, parts, &path) { - Some(inside) => inside, - None => return false, - }, - Some(Made::Insert { - object, - composite, - indices, - }) => { - let inside = path.strip_prefix(*indices).map(<[u32]>::to_vec); - if let (false, Some(inside)) = (path.is_empty(), inside) { - (*object, inside) - } else if indices.starts_with(&path) { - return false; - } else { - (*composite, path) - } - } - Some(Made::Extract { composite, indices }) => { - (*composite, [&indices[..], &path[..]].concat()) - } - Some(Made::Copy(a)) => (*a, path), - Some(Made::Phi(_)) | None => return false, - }; - } - } - - /// The paths of every member of `v`'s type, itself (the empty path) first: a struct's - /// members, a sized array's elements, a matrix's columns and a vector's lanes, and theirs. - /// `None` past [`NODES`]. - fn paths(&self, v: Value) -> Option>> { - let ty = self.m.value(v).ok()?.ty; - let mut out = Vec::new(); - let mut open = vec![(ty, Vec::new())]; - while let Some((ty, path)) = open.pop() { - if out.len() == NODES { - return None; - } - let types = self.m.types(); - let members: Vec<_> = match types.get(ty).ok()? { - Type::Struct { members, .. } => members.to_vec(), - Type::Vector { elem, len } => vec![*elem; usize::from(*len)], - Type::Matrix { col, cols } => vec![*col; usize::from(*cols)], - Type::Array { elem, len, .. } => match self.m.consts().array_len(*len, types) { - Ok(Some(n)) if n as usize <= NODES => vec![*elem; n as usize], - Ok(Some(_)) => return None, - _ => Vec::new(), - }, - _ => Vec::new(), - }; - for (i, member) in members.into_iter().enumerate().rev() { - open.push((member, [&path[..], &[i as u32]].concat())); - } - out.push(path); - } - Some(out) - } - - /// Whether one of `values`, at index `at`, holds a mixed select at a member where another of - /// them holds a widened value: their merge is the measured one. The others are every other - /// index, or with `distinct` every other value (a phi's incoming value twice is no merge with - /// itself). Only widened values take part: a value holding a widened member is widened. A - /// type of more than [`NODES`] members merges wherever two of them are widened. - fn merges(&self, values: &[Value], at: usize, distinct: bool) -> bool { - let Some(&s) = values.get(at).filter(|s| has_bit(self.widened, **s)) else { - return false; - }; - let others = || { - values.iter().enumerate().filter(move |&(j, v)| { - has_bit(self.widened, *v) && if distinct { *v != s } else { j != at } - }) - }; - let Some(paths) = self.paths(s) else { - return others().next().is_some(); - }; - paths - .iter() - .any(|path| self.mixed_at(s, path) && others().any(|(_, v)| self.widened_at(*v, path))) - } -} - -/// Whether module `m` merges a widened value (one of `widened`) that a select took against a value -/// it does not hold widened with another widened value (`narrow::moves_unfolded`): a phi with -/// such a select among its incoming values and another widened one, or a function variable -/// (`local_float`) such a select is stored to and another widened value too, member by member -/// (the module docs). Measured on the M3 Max under macOS 27.0.1 (2026-11-03), every `half` bit -/// pattern widened, moved and narrowed by Metal's compiler, with and without fast math: a merge of -/// `b ? float(h) : 0.0` with `float(h2)`, or with `b ? float(h2) : 0.0`, answers 2045 of the 2046 -/// NaNs `0x7E00`, where the select alone, the merge of widened values alone, a select of two -/// widened values merged with a third, the select merged with a constant, a merge then a select, -/// two selects, two merges, the select carried to a later block, and a select of the `half` bits -/// before the widening each keep every NaN's bits. One pass over the instructions to record the -/// values that carry members and the stores, [`RECORD_BYTES`] per instruction and phi charged to -/// `meter` while it runs, then the questions of each phi's and each such variable's values. -pub(super) fn merges_mixed_selects( - m: &TypedModule, - widened: &[u64], - local_float: &dyn Fn(Value) -> bool, - meter: &mut Meter, -) -> Result { - let records: usize = m - .blocks() - .iter() - .map(|b| b.phis.len() + b.insts.len()) - .sum(); - let bytes = records.saturating_mul(RECORD_BYTES); - meter.charge(bytes)?; - let members = Members::new(m, widened); - // The widened values stored to each function variable, in order. Each store is one of the - // merged values, where each of a phi's incoming values is: two stores of one select to a - // variable merge it with itself, and a phi's two edges of one value do not. - let mut stores: HashMap> = HashMap::new(); - for n in m.blocks().iter().flat_map(|b| &b.insts) { - if let Inst::Store { ptr, value, .. } = &n.inst { - if has_bit(widened, *value) && local_float(*ptr) { - stores.entry(*ptr).or_default().push(*value); - } - } - } - let stored = stores - .values() - .any(|values| (0..values.len()).any(|i| members.merges(values, i, false))); - let merged = stored - || m.blocks().iter().flat_map(|b| &b.phis).any(|phi| { - if !has_bit(widened, phi.result) { - return false; - } - let values: Vec = phi.incoming.iter().map(|(v, _)| *v).collect(); - (0..values.len()).any(|i| members.merges(&values, i, true)) - }); - drop((members, stores)); - meter.release(bytes); - Ok(merged) -} diff --git a/crates/metal2vulkan/src/lower/arith/ops.rs b/crates/metal2vulkan/src/lower/arith/ops.rs index e6b9cde4f..1282f09f1 100644 --- a/crates/metal2vulkan/src/lower/arith/ops.rs +++ b/crates/metal2vulkan/src/lower/arith/ops.rs @@ -285,8 +285,7 @@ pub fn f16_binary_words(f: Form) -> u32 { /// ([`narrow::round`]), so no conversion barrier and no conversion pair, which a device's compiler /// spends most on (ANV's register allocation grows with the values the pairs add). /// -/// The instruction is Metal's where the profile takes `DriverDeviation::MetalHalfArithmetic`, and, -/// by the Vulkan spec, in an entry declaring the 16-bit float controls the module's roundings take +/// The instruction is Metal's, by the Vulkan spec, in an entry declaring the 16-bit float controls the module's roundings take /// ([`narrow::controlled_modes`]): the precision table "for IEEE754 half- (16 bit) and single- (32 /// bit) precision instructions" lists `OpFAdd`, `OpFSub` and `OpFMul` as "Correctly rounded", /// "according to IEEE 754 roundTiesToEven" under `RoundingModeRTE`, `DenormPreserve` keeps @@ -300,11 +299,7 @@ pub fn f16_binary_words(f: Form) -> u32 { /// The instruction takes the AIR's own contraction, as `float` arithmetic does /// ([`float_binary`]): one whose flags carry both `contract` and `reassoc` /// (`Contraction::Allowed`) is undecorated, a product a plain `OpFMul`, and the device's compiler -/// groups and fuses it with its neighbours as it chooses. On MoltenVK, Metal's fast and relaxed -/// compiles fold such an operation's narrowings and widening away and answer the `float` sum, -/// difference or product of the widened operands, unrounded (measured with -/// `DriverDeviation::MetalHalfArithmetic`), which selection records as -/// `PrecisionNote::FastMathRewrites`. Any other (`Contraction::Forbidden`) is kept apart: a sum or +/// groups and fuses it with its neighbours as it chooses. Any other (`Contraction::Forbidden`) is kept apart: a sum or /// difference decorated `NoContraction` (SPIRV-Cross writes its `[[clang::optnone]]` `spvFAdd` or /// `spvFSub`), a product as `Fma(a, b, -0.0)` decorated `NoContraction`, the product's value /// whether the device fuses it or not; a `NoContraction` `OpFMul`, which SPIRV-Cross writes as diff --git a/crates/metal2vulkan/src/lower/arith/pack.rs b/crates/metal2vulkan/src/lower/arith/pack.rs index 6a3fff243..c1b3f3a07 100644 --- a/crates/metal2vulkan/src/lower/arith/pack.rs +++ b/crates/metal2vulkan/src/lower/arith/pack.rs @@ -40,31 +40,6 @@ pub fn instruction(format: PackFormat, dir: PackDir) -> Option { }) } -/// Whether the device's conversion of `format` in direction `dir` on float lanes of `fmt` is one -/// measured to answer Metal's where the profile takes `DriverDeviation::MetalPackConversions`: -/// `unorm.rgb565` in `float`, and in `half` `unorm4x8`, `snorm4x8`, `unorm.rgb10a2` and -/// `unorm.rgb565` both ways and `unorm2x16` and `snorm2x16` packed. -pub fn measured(format: PackFormat, dir: PackDir, fmt: FloatFmt) -> bool { - use PackFormat as F; - match (fmt, dir) { - (FloatFmt::F32, _) => format == F::UnormRgb565, - (FloatFmt::Half, PackDir::Pack) => matches!( - format, - F::Unorm4x8 - | F::Snorm4x8 - | F::Unorm2x16 - | F::Snorm2x16 - | F::UnormRgb10a2 - | F::UnormRgb565 - ), - (FloatFmt::Half, PackDir::Unpack) => matches!( - format, - F::Unorm4x8 | F::Snorm4x8 | F::UnormRgb10a2 | F::UnormRgb565 - ), - _ => false, - } -} - /// The error of a conversion whose format or lanes the emission cannot take (a packed float /// format to pack to, a lane count not the format's): selection rules both out. fn unpackable() -> BuildError { diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index 0b7217f77..0c77eb50c 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -22,7 +22,7 @@ use super::ops::{self, BitcastPlan, CastKind}; use crate::air::ir::{BinOp as AirBin, FloatPredicate, IntFlags, IntPredicate}; use crate::device::DeviceProfile; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder, ProductForm, QuantizeForm}; +use crate::spirv::builder::{FunctionBuilder, ModuleBuilder, QuantizeForm}; use crate::spirv::error::BResult; use crate::spirv::ids::{FuncId, GlobalId, TypeId, Value}; use crate::spirv::interp::{run, Buffer, Config, Resources}; @@ -1040,20 +1040,14 @@ fn llvm_fcmp(pred: FloatPredicate, a: f64, b: f64) -> bool { /// A multiply rounded on its own is IEEE's product bit for bit on every pair of the value sets, /// `-0.0` operands, zero products of either sign, denormals, overflow, infinities, and NaNs -/// included, on `float` scalars and vectors and on `double`, in either of its forms (`OpFMul`, and -/// `Fma(a, b, -0.0)` where SPIRV-Cross renders the SPIR-V). +/// included, on `float` scalars and vectors and on `double`. #[test] fn a_multiply_without_contraction_is_the_product() { - for (form, bits, vals, lanes) in [ProductForm::Multiply, ProductForm::NegativeZeroFma] - .into_iter() - .flat_map(|form| { - [ - (form, 32u8, f32_values(), 1u8), - (form, 32, f32_values(), 4), - (form, 64, f64_values(), 1), - ] - }) - { + for (bits, vals, lanes) in [ + (32u8, f32_values(), 1u8), + (32, f32_values(), 4), + (64, f64_values(), 1), + ] { let f = vec(float(bits), lanes); let cases: Vec = pairs(&vals, &vals) .into_iter() @@ -1064,13 +1058,10 @@ fn a_multiply_without_contraction_is_the_product() { }) .collect(); check( - &format!("fmul without contraction f{bits} x{lanes} as {form:?}"), + &format!("fmul without contraction f{bits} x{lanes}"), &[f, f], f, - &|fb, x| { - fb.module().product_form(form); - ops::float_binary(fb, AirBin::FMul, f, Contraction::Forbidden, x[0], x[1]) - }, + &|fb, x| ops::float_binary(fb, AirBin::FMul, f, Contraction::Forbidden, x[0], x[1]), &cases, &|c| { let r = |l: usize| { @@ -1088,13 +1079,12 @@ fn a_multiply_without_contraction_is_the_product() { } } -/// An `f32` product by a constant with `-0.0` components is IEEE's product bit for bit in every -/// [`ProductForm`] (a NaN's bits aside), as `OpFMul` with the constant on either side, with and -/// without contraction, and as `OpVectorTimesScalar` by a `-0.0` scalar or of a constant vector, -/// and in every form no product the module emits has a `-0.0` component in a constant factor: it -/// multiplies by `+0.0` there and negates. +/// An `f32` product by a constant with `-0.0` components is IEEE's product bit for bit (a NaN's +/// bits aside), as `OpFMul` with the constant on either side, with and without contraction, and +/// as `OpVectorTimesScalar` by a `-0.0` scalar or of a constant vector, and no product the module +/// emits has a `-0.0` component in a constant factor: it multiplies by `+0.0` there and negates. #[test] -fn a_product_by_a_negative_zero_factor_keeps_its_sign_in_every_form() { +fn a_product_by_a_negative_zero_factor_keeps_its_sign() { const NZ: u64 = 0x8000_0000; const TWO: u64 = 0x4000_0000; #[derive(Clone, Copy, Debug)] @@ -1144,76 +1134,72 @@ fn a_product_by_a_negative_zero_factor_keeps_its_sign_in_every_form() { .count() }; let vals = f32_values(); - for form in [ProductForm::Multiply, ProductForm::NegativeZeroFma] { - for contract in [Contraction::Forbidden, Contraction::Allowed] { - for (lanes, shape, c) in factors { - let what = format!("{form:?} {contract:?} {shape:?} x{lanes} by {c:x?}"); - let x_lanes = match shape { - Shape::OfConstant => 1, - _ => lanes, - }; - let input = vec(float(32), x_lanes); - let out = vec(float(32), lanes); - let body = |fb: &mut FunctionBuilder<'_>, xs: &[Value]| -> BResult { - fb.module().product_form(form); - let f32_ty = fb.module().ty(Type::Float { width: 32 })?; - let parts = c - .iter() - .map(|bits| { - fb.module().constant(Constant::Scalar { - ty: f32_ty, - bits: ConstBits(*bits), - }) - }) - .collect::>>()?; - let k = if parts.len() == 1 { - parts[0] - } else { - let ty = fb.module().ty(Type::Vector { - elem: f32_ty, - len: parts.len() as u8, - })?; - fb.module().constant(Constant::Composite { - ty, - parts: parts.into(), - })? - }; - let k = fb.module().const_value(k)?; - let (op, a, b) = match shape { - Shape::Mul { left: false } => (BinOp::FMul, xs[0], k), - Shape::Mul { left: true } => (BinOp::FMul, k, xs[0]), - Shape::ByScalar => (BinOp::VectorTimesScalar, xs[0], k), - Shape::OfConstant => (BinOp::VectorTimesScalar, k, xs[0]), - }; - fb.binary_with(op, a, b, contract) - }; - let m = kernel_with(&[input], out, &body, true, false) - .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - assert_eq!(negative_factors(&m), 0, "{what}: a -0.0 factor"); - let cases: Vec = vals + for contract in [Contraction::Forbidden, Contraction::Allowed] { + for (lanes, shape, c) in factors { + let what = format!("{contract:?} {shape:?} x{lanes} by {c:x?}"); + let x_lanes = match shape { + Shape::OfConstant => 1, + _ => lanes, + }; + let input = vec(float(32), x_lanes); + let out = vec(float(32), lanes); + let body = |fb: &mut FunctionBuilder<'_>, xs: &[Value]| -> BResult { + let f32_ty = fb.module().ty(Type::Float { width: 32 })?; + let parts = c .iter() - .map(|x| vec![vec![*x; usize::from(x_lanes)]]) - .collect(); - let factor = |l: usize| f32::from_bits(c[if c.len() == 1 { 0 } else { l }] as u32); - check_module( - &what, - m, - &[input], - out, - &cases, - &|case| { - let x = |l: usize| { - f32::from_bits(case[0][if x_lanes == 1 { 0 } else { l }] as u32) - }; - Some( - (0..usize::from(lanes)) - .map(|l| u64::from((x(l) * factor(l)).to_bits())) - .collect(), - ) - }, - &|g, w| g == w || (is_nan(out, g) && is_nan(out, w)), - ); - } + .map(|bits| { + fb.module().constant(Constant::Scalar { + ty: f32_ty, + bits: ConstBits(*bits), + }) + }) + .collect::>>()?; + let k = if parts.len() == 1 { + parts[0] + } else { + let ty = fb.module().ty(Type::Vector { + elem: f32_ty, + len: parts.len() as u8, + })?; + fb.module().constant(Constant::Composite { + ty, + parts: parts.into(), + })? + }; + let k = fb.module().const_value(k)?; + let (op, a, b) = match shape { + Shape::Mul { left: false } => (BinOp::FMul, xs[0], k), + Shape::Mul { left: true } => (BinOp::FMul, k, xs[0]), + Shape::ByScalar => (BinOp::VectorTimesScalar, xs[0], k), + Shape::OfConstant => (BinOp::VectorTimesScalar, k, xs[0]), + }; + fb.binary_with(op, a, b, contract) + }; + let m = kernel_with(&[input], out, &body, true, false) + .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); + assert_eq!(negative_factors(&m), 0, "{what}: a -0.0 factor"); + let cases: Vec = vals + .iter() + .map(|x| vec![vec![*x; usize::from(x_lanes)]]) + .collect(); + let factor = |l: usize| f32::from_bits(c[if c.len() == 1 { 0 } else { l }] as u32); + check_module( + &what, + m, + &[input], + out, + &cases, + &|case| { + let x = + |l: usize| f32::from_bits(case[0][if x_lanes == 1 { 0 } else { l }] as u32); + Some( + (0..usize::from(lanes)) + .map(|l| u64::from((x(l) * factor(l)).to_bits())) + .collect(), + ) + }, + &|g, w| g == w || (is_nan(out, g) && is_nan(out, w)), + ); } } } @@ -2690,28 +2676,6 @@ 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.device_answers(NanEncoding::MetalCanonical)); - for a in [ - A::CanonicalExact, - A::Operand, - A::OperandSign, - A::DomainSign, - A::BaseToExponentOne, - ] { - assert!(!a.device_answers(NanEncoding::MetalCanonical), "{a:?}"); - } - // A device not measured to answer Metal's canonical NaN answers none of Metal's NaNs. - for a in [ - A::Canonical, - A::CanonicalExact, - A::Operand, - A::OperandSign, - A::DomainSign, - A::BaseToExponentOne, - ] { - assert!(!a.device_answers(NanEncoding::Native), "{a:?}"); - } } /// The float facts of a profile whose `float` fused multiply-add is `OpFmaKHR`, whose `half` one @@ -2721,25 +2685,17 @@ const KHR_FACTS: super::FloatFacts = super::FloatFacts { float: super::fma::Route::Khr, half: super::fma::Route::Native, }, - metal_functions: false, - device_denormals: false, - unary_denormals: false, - nans: crate::device::profile::NanEncoding::Native, - native_min_max: false, - nan_moves: false, }; /// `ldexp` on `float` is lowered on the bits ([`math::ldexp_bits`]), which answer a NaN operand /// itself, bit for bit, as Metal does (`NanAnswer::Operand`): no NaN of the device's reaches the -/// result, so the call records no `NativeNanEncoding` and leaves no NaN answer to the device, on a -/// device of either NaN encoding. A `half` `ldexp` multiplies, so its NaN is the device's product's -/// where Metal answers its canonical `half` NaN, and stays noted on a device not measured to answer -/// that. +/// result, so the call records no `NativeNanEncoding` and leaves no NaN answer to the device. A +/// `half` `ldexp` multiplies, so its NaN is the device's product's where Metal answers its canonical +/// `half` NaN, noted. #[test] fn float_ldexp_answers_metals_nan_itself() { use super::nan::NanAnswer as A; use crate::air::ir::FastMath; - use crate::device::profile::NanEncoding; use crate::pipeline::artifact::PrecisionNote; let form = |fmt| Form { held: Held::Float(fmt), @@ -2750,133 +2706,96 @@ fn float_ldexp_answers_metals_nan_itself() { let every = FastMath::ALL .iter() .fold(FastMath::NONE, |a, (b, _)| a.union(*b)); - for nans in [NanEncoding::Native, NanEncoding::MetalCanonical] { - let facts = super::FloatFacts { nans, ..KHR_FACTS }; - for fmf in [FastMath::NONE, every] { - let call = super::float_call(FloatFn::Ldexp, false, fmf, form(FloatFmt::F32), facts) - .expect("float ldexp"); - assert_eq!(call.nan, None, "{nans:?} {fmf:?}"); - let noted = (call.notes.always.iter()) - .chain(&call.notes.unless_metal_fast) - .any(|n| matches!(n, PrecisionNote::NativeNanEncoding)); - assert!(!noted, "{nans:?} {fmf:?}: {:?}", call.notes); - } - let half = super::float_call( - FloatFn::Ldexp, - false, - FastMath::NONE, - form(FloatFmt::Half), - facts, - ) - .expect("half ldexp"); - assert_eq!(half.nan, Some(A::Canonical), "{nans:?}"); - if nans == NanEncoding::Native { - assert!( - half.notes - .always - .contains(&PrecisionNote::NativeNanEncoding), - "{:?}", - half.notes - ); - } + let facts = KHR_FACTS; + for fmf in [FastMath::NONE, every] { + let call = super::float_call(FloatFn::Ldexp, false, fmf, form(FloatFmt::F32), facts) + .expect("float ldexp"); + assert_eq!(call.nan, None, "{fmf:?}"); + let noted = (call.notes.iter()).any(|n| matches!(n, PrecisionNote::NativeNanEncoding)); + assert!(!noted, "{fmf:?}: {:?}", call.notes); } + let half = super::float_call( + FloatFn::Ldexp, + false, + FastMath::NONE, + form(FloatFmt::Half), + facts, + ) + .expect("half ldexp"); + assert_eq!(half.nan, Some(A::Canonical)); + assert!( + half.notes.contains(&PrecisionNote::NativeNanEncoding), + "{:?}", + half.notes + ); } /// Precise `pow` on `float` leaves its NaNs to the device (the device's `Pow`, and the device's sum /// of NaN operands), where Metal's NaN is measured: the canonical NaN, but a NaN base to the /// exponent one, which is the base itself. It records `NativeNanEncoding` as fast `pow` and `atan2` -/// do, on a device whose arithmetic answers Metal's canonical NaN too (its sum of `pow(NaN, 1)`'s -/// operands is that NaN, not the base), and never `DeviceNanEncoding`, which is for a NaN Metal +/// do, and never `DeviceNanEncoding`, which is for a NaN Metal /// answers no NaN of (fast `sin` and `cos`). #[test] fn precise_pow_notes_its_measured_nan_as_the_devices() { use super::nan::NanAnswer as A; use crate::air::ir::FastMath; - use crate::device::profile::NanEncoding; use crate::pipeline::artifact::PrecisionNote; let f = Form { held: Held::Float(FloatFmt::F32), lanes: 1, }; - for nans in [NanEncoding::Native, NanEncoding::MetalCanonical] { - let facts = super::FloatFacts { nans, ..KHR_FACTS }; - let call = - super::float_call(FloatFn::Pow, false, FastMath::NONE, f, facts).expect("float pow"); - assert_eq!(call.nan, Some(A::BaseToExponentOne), "{nans:?}"); - assert!( - call.notes - .always - .contains(&PrecisionNote::NativeNanEncoding), - "{nans:?}: {:?}", - call.notes - ); - let every_note = call - .notes - .always + let facts = KHR_FACTS; + let call = super::float_call(FloatFn::Pow, false, FastMath::NONE, f, facts).expect("float pow"); + assert_eq!(call.nan, Some(A::BaseToExponentOne)); + assert!( + call.notes.contains(&PrecisionNote::NativeNanEncoding), + "{:?}", + call.notes + ); + let every_note = call.notes.iter(); + assert!( + !every_note + .clone() + .any(|n| *n == PrecisionNote::DeviceNanEncoding), + "{:?}", + call.notes + ); + let sin = super::float_call(FloatFn::Sin, true, FastMath::NONE, f, facts).expect("fast sin"); + assert_eq!(sin.nan, None); + assert!( + sin.notes .iter() - .chain(&call.notes.unless_metal_fast); - assert!( - !every_note - .clone() - .any(|n| *n == PrecisionNote::DeviceNanEncoding), - "{nans:?}: {:?}", - call.notes - ); - let sin = - super::float_call(FloatFn::Sin, true, FastMath::NONE, f, facts).expect("fast sin"); - assert_eq!(sin.nan, None, "{nans:?}"); - assert!( - sin.notes - .always - .iter() - .chain(&sin.notes.unless_metal_fast) - .any(|n| *n == PrecisionNote::DeviceNanEncoding), - "{nans:?}: {:?}", - sin.notes - ); - } + .any(|n| *n == PrecisionNote::DeviceNanEncoding), + "{:?}", + sin.notes + ); } -/// Class E: Metal's `float` `fneg` and `fabs` flip or clear the sign bit alone, a NaN's payload and -/// a denormal kept (`nan_signbits`, `nan_signbits_fast`). The lowering takes the device's -/// `floor`, `ceil` and `fabs` on `float` leave their denormals to the device, noted -/// `DeviceDenormals`, but where the profile takes `DriverDeviation::MetalUnaryDenormals` -/// (`denormal::Covered::Unary`, `denormal::moves_sign`); `trunc` follows the other deviation -/// alone, in either mode. +/// `floor`, `ceil`, `trunc` and `fabs` on `float` leave their denormals to the device, noted +/// `DeviceDenormals`, in either mode (class E's `fabs` keeps a denormal on Metal). #[test] -fn unary_denormals_follow_their_deviation() { +fn unary_denormals_are_the_device_s() { use crate::air::ir::FastMath; use crate::pipeline::artifact::PrecisionNote; let f = Form { held: Held::Float(FloatFmt::F32), lanes: 1, }; - for unary in [false, true] { - // A profile that takes the unary deviation (MoltenVK on an Apple9 GPU) takes - // `MetalFloatFunctions` too: its `fabs` is one of Metal's functions. - let facts = super::FloatFacts { - unary_denormals: unary, - metal_functions: unary, - ..KHR_FACTS - }; - for op in [FloatFn::Floor, FloatFn::Ceil, FloatFn::Abs, FloatFn::Trunc] { - for fast in [false, true] { - let call = super::float_call(op, fast, FastMath::NONE, f, facts) - .unwrap_or_else(|| panic!("{op:?}: no float call")); - assert_eq!( - call.notes.always.contains(&PrecisionNote::DeviceDenormals), - !(unary && op != FloatFn::Trunc), - "{op:?}, fast {fast}, unary {unary}" - ); - } + for op in [FloatFn::Floor, FloatFn::Ceil, FloatFn::Abs, FloatFn::Trunc] { + for fast in [false, true] { + let call = super::float_call(op, fast, FastMath::NONE, f, KHR_FACTS) + .unwrap_or_else(|| panic!("{op:?}: no float call")); + assert!( + call.notes.contains(&PrecisionNote::DeviceDenormals), + "{op:?}, fast {fast}" + ); } } } /// `OpFNegate` and `FAbs` on every format, whose NaN is the device's: a `float` `fabs` answers /// Metal's operand NaN by none of its own, noted `NativeNanEncoding` (and a `half` one Metal's -/// canonical NaN, class D), and off Metal's own functions records the device's precision and -/// denormals. +/// canonical NaN, class D), and records the device's precision and denormals. #[test] fn float_sign_operations_are_the_device_instructions() { use super::nan::NanAnswer as A; @@ -2903,7 +2822,7 @@ fn float_sign_operations_are_the_device_instructions() { PrecisionNote::NativeTranscendentals, PrecisionNote::DeviceDenormals, ] { - assert!(call.notes.always.contains(¬e), "{note:?} {fmf:?}"); + assert!(call.notes.contains(¬e), "{note:?} {fmf:?}"); } } let call = @@ -3429,7 +3348,7 @@ fn pi_scaled_functions_reduce_exactly_to_metal_answers() { /// [`FloatFn::words`] bounds what `sinpi`, `cospi`, and `tanpi` emit on every form: the exact /// reduction around the device's `Sin` and `Cos`, the axis arms and `tanpi`'s quarter turns -/// included, whether or not the device's functions are Metal's. The module's growth over an +/// included. The module's growth over an /// identity kernel is charged in full, its constants and the `GLSL.std.450` import included. #[test] fn pi_scaled_functions_stay_within_their_word_estimate() { diff --git a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs index 143ddfef5..cef35cca2 100644 --- a/crates/metal2vulkan/src/lower/arith/tests/narrow.rs +++ b/crates/metal2vulkan/src/lower/arith/tests/narrow.rs @@ -215,100 +215,6 @@ fn narrow_members_move_as_bits_through_structs() { } } -/// A select of a widened `half` against a value not held widened, merged by an `OpPhi` with -/// another widened `half`, is the merge Metal's compiler does not fold (`narrow::moves_unfolded`), -/// and so it is carried in a struct's member: a phi of structs, one built from the select by a -/// construct or an insert, the other holding a widened `half` in the same member, and a phi of a -/// member extracted from such a struct. Structs that hold the select and the widened `half` in -/// different members, or the select beside a constant, merge nothing of it. -#[test] -fn a_merge_of_a_select_is_followed_through_struct_members() { - use crate::spirv::builder::constructs::{ArmEnd, ArmFn, Merged}; - use crate::spirv::ir::Type; - // How the arms hand the phi their values: (then, else) from the select `t`, the widened - // halves `h` and `g`, the constant `one` and a struct type of two `f32` members. - #[derive(Clone, Copy, Debug)] - enum Shape { - Plain, - Struct, - Inserted, - Extracted, - Apart, - Constant, - } - let f = half(); - for (shape, unfolded) in [ - (Shape::Plain, true), - (Shape::Struct, true), - (Shape::Inserted, true), - (Shape::Extracted, true), - (Shape::Apart, false), - (Shape::Constant, false), - ] { - let body = move |fb: &mut FunctionBuilder<'_>, x: &[Value]| -> BResult { - let (h, g) = (x[0], x[1]); - let f32_ = fb.value_ty(h)?; - let st = fb.module().ty(Type::Struct { - members: vec![f32_, f32_].into(), - layout: None, - })?; - let zero = const_of(fb, f32_, 0)?; - let one = const_of(fb, f32_, u64::from(1.0f32.to_bits()))?; - let c = fb.binary(BinOp::FOrdLessThan, h, g)?; - let d = fb.binary(BinOp::FOrdGreaterThan, h, one)?; - let then: ArmFn<'_, ()> = Box::new(move |fb, _| { - let t = fb.select(d, h, zero)?; - let v = match shape { - Shape::Plain => t, - Shape::Struct | Shape::Apart | Shape::Constant => { - fb.composite_construct(st, &[t, one])? - } - Shape::Inserted => { - let u = fb.undef(st)?; - fb.composite_insert(t, u, &[0])? - } - Shape::Extracted => { - let s = fb.composite_construct(st, &[t, one])?; - fb.composite_extract(s, &[0])? - } - }; - Ok(ArmEnd::FallThrough(vec![v])) - }); - let other: ArmFn<'_, ()> = Box::new(move |fb, _| { - let v = match shape { - Shape::Plain | Shape::Extracted => g, - Shape::Struct => fb.composite_construct(st, &[g, one])?, - Shape::Inserted => { - let u = fb.undef(st)?; - fb.composite_insert(g, u, &[0])? - } - Shape::Apart => fb.composite_construct(st, &[one, g])?, - Shape::Constant => fb.composite_construct(st, &[one, one])?, - }; - Ok(ArmEnd::FallThrough(vec![v])) - }); - let Merged(merged) = fb.if_(&mut (), c, then, Some(other))?; - let p = merged[0]; - match shape { - Shape::Plain | Shape::Extracted => Ok(p), - // Both members out, so the widened `half` of either reaches the store. - _ => { - let a = fb.composite_extract(p, &[0])?; - let b = fb.composite_extract(p, &[1])?; - fb.select(c, a, b) - } - } - }; - let m = kernel_with(&[f, f], f, &body, true, false) - .unwrap_or_else(|e| panic!("{shape:?}: build: {e:?}")); - let budget = crate::budget::Budget::default(); - let mut meter = crate::budget::Meter::new(&budget); - let got = super::super::narrow::moves_unfolded(&m, &mut meter) - .unwrap_or_else(|e| panic!("{shape:?}: {e:?}")); - assert_eq!(got, unfolded, "{shape:?}"); - } -} - /// One half round trip through its format bits, `to_bits` then `from_bits` (their types and /// constants shared with the kernel's own load and store), is the device's narrowing and widening /// alone: at most 40 words. A load also decodes @@ -2158,35 +2064,31 @@ fn srgb_packs_read_no_table() { /// `frem`, other formats, and a chunk wider than four lanes never do. #[test] fn half_arithmetic_on_the_device_follows_the_profile() { - use super::super::F16Basis; let mut controlled = 0; for (stem, p) in committed_profiles().expect("profiles") { let controls = super::super::narrow::half_controls(&p); - let basis = controls.then_some(F16Basis::Controlled); for op in [AirBin::FAdd, AirBin::FSub, AirBin::FMul] { for lanes in 1..=4 { assert_eq!( super::super::f16_arithmetic(&p, op, vec(half(), lanes)), - basis, + controls, "{stem}: {op:?} on {lanes} lanes" ); } for f in [vec(half(), 8), float(32), bfloat(), float(64)] { - assert_eq!( - super::super::f16_arithmetic(&p, op, f), - None, + assert!( + !super::super::f16_arithmetic(&p, op, f), "{stem}: {op:?} on {f:?}" ); } } for op in [AirBin::FDiv, AirBin::FRem] { - assert_eq!( - super::super::f16_arithmetic(&p, op, half()), - None, + assert!( + !super::super::f16_arithmetic(&p, op, half()), "{stem}: {op:?}" ); } - controlled += usize::from(basis == Some(F16Basis::Controlled)); + controlled += usize::from(controls); } assert!( controlled >= 2, diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index 31b7bd8df..8c4de1c2b 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -99,10 +99,7 @@ pub struct Declared { /// Declare the plan's module-scope objects: the access family's views, the push block, then /// every other family's objects. fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult { - // Before any instruction: every multiply the device must round on its own takes the - // profile's form. - mb.product_form(plan.families.arith.product); - // And every `half` rounding's quantize the device's form. + // Before any instruction: 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_native_half_nans(plan.families.arith.native_half_nans); diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index a36a1b3b2..a13b8d697 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -3046,8 +3046,7 @@ fn names_class(fb: &mut FunctionBuilder<'_>, index: SValue, class: TexelClass) - /// another class widens them (`reinterpret`), so a store of it moves those bits as the slot's /// does, a NaN's included. Merged as values, each arm's `half` would be the device's widening of /// its bits, selected against the zero a null handle reads and merged with the other arms'; Metal's -/// compiler does not fold the widening of such a merge back to the bits (`narrow::moves_unfolded`), -/// and on the Apple M3 Max a NaN's bits became `0x7E00` there. The own arm's bits are its texel's +/// compiler does not fold the widening of such a merge back to the bits, and on the Apple M3 Max a NaN's bits became `0x7E00` there. The own arm's bits are its texel's /// narrowing (`narrow::to_bits`), the device's conversion of a `half` value, which a store of the /// merged value took before. fn read_crossed(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, r: &Read) -> BResult { @@ -3229,8 +3228,6 @@ fn write(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, w: &Write) -> BResul } ImageRef::Slot(_) => texel, }; - // The write's notes account for the texel's stored NaN (`moves_unfolded`). - fb.module().note_stored_texel(texel); let mem = texel_memory(cx, fb, &w.image)?; // A write to a sparse texture is dropped. let kept = sparse_writes_kept(cx, fb, &w.image)?; @@ -3416,7 +3413,6 @@ fn slice<'c>(cx: &mut EmitCx<'c>, fb: &mut FunctionBuilder<'_>, s: &Slice) -> BR lanes: 4, }; let texel = to_image(fb, &decl, form, held)?; - fb.module().note_stored_texel(texel); let ty = vec(fb, u, dims)?; let delta = if dims == 2 { fb.composite_construct(ty, &[x, y])? diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 01397d583..670e55712 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -1010,8 +1010,7 @@ pub struct TexturePlan { /// conversion because it stores Metal's half (`MetalHalfStorageWrites`) and its NaN /// (`MetalHalfStorageNans`), a write that may reach a normalized format, because it stores /// Metal's codes (`MetalNormStorageWrites`), and a `half` texel's NaN to a 16-bit float format - /// (`MetalHalfTexelWrites`); and a `half` read's NaN of a 32-bit float or packed small float - /// texel (`MetalHalfConversion`, `half_texel_nans`). The module requires them. + /// (`MetalHalfTexelWrites`). The module requires them. pub storage_properties: BTreeSet, } @@ -1678,10 +1677,7 @@ pub enum OneTexel { /// none of the families (the slot's `UnmeasuredTexels` specialization), a 16-bit normalized grid /// (`BicubicTexels::WIDE16`: three steps of each round twice), and a sample of a 32-bit float /// texel (`BicubicTexels::LINEAR`: Metal rounds toward zero, saturating), tests of the bound -/// format the runtime announces at a draw or dispatch binding such a texture. Not a sample's of a -/// 32-bit float texel on a profile that takes `DriverDeviation::MetalHalfConversion` (the module -/// then requires its property): there the device's `half` of every `float` word a read, sample or -/// gather hands back is measured to be Metal's (`device::driver_facts`). A heap color +/// format the runtime announces at a draw or dispatch binding such a texture. A heap color /// texture's and a depth texture's access records it outright. pub(crate) fn half_texels( cx: &mut SelectCx<'_>, @@ -1708,22 +1704,9 @@ pub(crate) fn half_texels( [NoteTest::equal(NoteOn::Unmeasured(index), 1, 1)].into(), [NoteTest::differ(NoteOn::Bound(index), B::WIDE16, 0)].into(), ]; - // A sample of a 32-bit float texel, but on a profile that takes - // `DriverDeviation::MetalHalfConversion`, whose `half` of every `float` word a read, sample or - // gather hands back is measured to be Metal's (the module then requires its property). + // A sample of a 32-bit float texel. if sample { - match cx - .profile - .takes_driver_deviation(DriverDeviation::MetalHalfConversion) - { - true => { - cx.families - .texture - .storage_properties - .insert(crate::device::requirements::VkProperty::MetalHalfConversion); - } - false => when.push([NoteTest::differ(NoteOn::Bound(index), B::LINEAR, 0)].into()), - } + when.push([NoteTest::differ(NoteOn::Bound(index), B::LINEAR, 0)].into()); } cx.note_when(PrecisionNote::HalfTexelConversion, when, m)?; let slot = slot_of(cx, index)?.slot; @@ -1740,10 +1723,7 @@ pub(crate) fn half_texels( /// only where the class of the format bound there may hold a NaN (none of `TexelFormat::NAN_FREE`'s /// families): a test of `SpecKey::BoundTexelFormat`, which the runtime reads from the bound texture /// and no pipeline's key carries. A normalized, sRGB or extended-range texel decodes to no NaN, so -/// the device's encoding of one cannot show. On a profile that takes -/// `DriverDeviation::MetalHalfConversion` (the module then requires its property), not where the -/// class is a 32-bit float or packed small float one either: the `half` the device makes of such a -/// texel is measured to be Metal's, its NaN `0x7e00` (`device::driver_facts`). Of a heap's element +/// the device's encoding of one cannot show. Of a heap's element /// or a depth texture, wherever it reads. pub(crate) fn half_texel_nans( cx: &mut SelectCx<'_>, @@ -1753,27 +1733,13 @@ pub(crate) fn half_texel_nans( ) -> Result<(), Error> { match image { ImageRef::Slot(index) if !shape.depth => { - use crate::metal::bicubic::BicubicTexels as B; use crate::metal::texel_format::TexelFormat; - let bound = |mask, bits| NoteTest::equal(NoteOn::Bound(index), mask, bits); - let when = match cx - .profile - .takes_driver_deviation(DriverDeviation::MetalHalfConversion) - { - // A half-float class, and a class of no family. - true => { - cx.families - .texture - .storage_properties - .insert(crate::device::requirements::VkProperty::MetalHalfConversion); - let family = B::LINEAR | B::HALF | TexelFormat::NAN_FREE; - vec![ - [bound(family, B::HALF), bound(TexelFormat::PACKED_MASK, 0)].into(), - [bound(family, 0)].into(), - ] - } - false => vec![[bound(TexelFormat::NAN_FREE, 0)].into()], - }; + let when = vec![[NoteTest::equal( + NoteOn::Bound(index), + TexelFormat::NAN_FREE, + 0, + )] + .into()]; cx.note_when(PrecisionNote::DeviceNanEncoding, when, m) } _ => { @@ -2374,10 +2340,7 @@ const NAN_FAMILIES: [( VkProperty::MetalHalfTexelWrites, )), ), - ( - NAN_WIDE, - Some((DriverDeviation::MetalNanMoves, VkProperty::MetalNanMoves)), - ), + (NAN_WIDE, None), ( NAN_SMALL, Some(( @@ -2396,15 +2359,14 @@ const NAN_FAMILIES: [( /// `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); a 32-bit one's is -/// the widened `float`'s bits as written, Metal's `0x7fc00000` where the device's widening is -/// Metal's (`DriverDeviation::MetalNanMoves`, whose property the module then requires); a packed +/// the widened `float`'s bits as written, the device's widening's; a packed /// small float one's is Metal's on a device of `DriverDeviation::MetalSmallFloatNans`, which /// stores every `float` NaN there as Metal does (the module requires its property); and every /// other float channel's is the device's. /// /// The write records `PrecisionNote::DeviceNanEncoding` where the stored NaN stays the device's: /// a 16-bit float channel's on a profile without `DriverDeviation::MetalHalfTexelWrites`, a 32-bit -/// one's without `DriverDeviation::MetalNanMoves`, a packed small float one's without +/// one's, a packed small float one's without /// `DriverDeviation::MetalSmallFloatNans`, and a float channel's of none of those families (a /// format that may hold a NaN). A slot whose choice declares no format (or a variant that states /// none) records it under the format bound there (`m` charged for the clauses), and a heap @@ -2419,14 +2381,13 @@ pub(super) fn half_write_nans( ) -> Result<(), Error> { use crate::device::requirements::VkProperty; use crate::vk::NumericFormat as N; - // Whether the stored NaN is exact (`Exact`), a 16-bit float channel's (`Sixteen`), a 32-bit - // one's (`Wide`) or a packed small float one's (`Small`), each Metal's on its measured - // deviation, or the device's (`Device`). + // Whether the stored NaN is exact (`Exact`), a 16-bit float channel's (`Sixteen`) or a packed + // small float one's (`Small`), each Metal's on its measured deviation, or the device's + // (`Device`). #[derive(PartialEq)] enum Stored { Exact, Sixteen, - Wide, Small, Device, Bound(u32), @@ -2440,7 +2401,6 @@ pub(super) fn half_write_nans( }; match (b.color, b.component_bits, b.packed_bits) { (Some(N::Sfloat), Some(16), None) => Stored::Sixteen, - (Some(N::Sfloat), Some(32), None) => Stored::Wide, (Some(N::Sfloat | N::Ufloat), _, _) => Stored::Device, _ => Stored::Exact, } @@ -2492,10 +2452,7 @@ pub(super) fn half_write_nans( VkProperty::MetalHalfTexelWrites, )), ), - ( - [bound(family, B::LINEAR), bound(packed, 0)].into(), - Some((DriverDeviation::MetalNanMoves, VkProperty::MetalNanMoves)), - ), + ([bound(family, B::LINEAR), bound(packed, 0)].into(), None), ( [bound(packed, PackedTexels::SmallFloat.class().0)].into(), Some(( @@ -2521,7 +2478,6 @@ pub(super) fn half_write_nans( DriverDeviation::MetalHalfTexelWrites, VkProperty::MetalHalfTexelWrites, )), - Stored::Wide => Some((DriverDeviation::MetalNanMoves, VkProperty::MetalNanMoves)), Stored::Small => Some(( DriverDeviation::MetalSmallFloatNans, VkProperty::MetalSmallFloatNans, diff --git a/crates/metal2vulkan/src/pipeline/artifact.rs b/crates/metal2vulkan/src/pipeline/artifact.rs index 9b5b0f393..d9ff22985 100644 --- a/crates/metal2vulkan/src/pipeline/artifact.rs +++ b/crates/metal2vulkan/src/pipeline/artifact.rs @@ -555,9 +555,7 @@ pub enum PrecisionNote { /// NaN operand's answer may be a number there (`precise::sin`, `precise::cos` and /// `precise::sincos` of a NaN answer `0` on the Apple M3 Max through MoltenVK 1.4.2, where /// Metal answers the NaN). Not recorded by precise `fmod`, whose answer is the one right value on - /// every device, nor, on a device whose `float` functions are Metal's own, in an entry Metal - /// compiles with fast math ([`EntryMath::Fast`]) by a call the device answers as Metal's own - /// function; there its fast `sinpi`, `cospi`, and `tanpi`, near-equivalents, still record it. + /// every device. DeviceTranscendentals, /// Float reductions use the device's association order. ReductionOrder, @@ -565,15 +563,9 @@ pub enum PrecisionNote { /// arithmetic, comparisons, and functions as the zero of its sign and flushes a denormal result /// to one, where a Vulkan device keeps or flushes them by its own float controls (this /// translation declares no `DenormFlushToZero`). Recorded where the module leaves an - /// operation's denormals to a device not measured to read them as Metal does: `+ - *`, the - /// comparisons, `fma`, `dot`, `sqrt`, `rsqrt`, `trunc`, `rint` and `ldexp` on `float` (by the - /// device's products) but on a device that takes - /// the measured `DriverDeviation::MetalFloatDenormals`, and those on such a device too in an - /// entry that declares the 16-bit float controls, where a driver may keep them (NVIDIA's on - /// the RTX 3090 and the RTX 5080 Laptop GPU) and no query tells which; `fneg`, `fabs`, `floor` - /// and `ceil` on - /// `float` but on a device that takes the measured `DriverDeviation::MetalUnaryDenormals`; and - /// on every device the divisions and the remainder, the device's maths functions + /// operation's denormals to the device: `+ - *`, the comparisons, `fma`, `dot`, `sqrt`, + /// `rsqrt`, `trunc`, `rint` and `ldexp` on `float` (by the device's products), `fneg`, `fabs`, + /// `floor` and `ceil` on `float`, the divisions and the remainder, the device's maths functions /// (`fast::fmod`'s fused multiply-add, `sign` and `fract` among them), `mix` by `FMix`, `fast::sqrt` /// by `Sqrt`, `dot` of vectors of other than two to four lanes, whose chunks' products the /// device sums where Metal flushes each one below `2^-126`, beside their own notes, and a @@ -638,10 +630,7 @@ pub enum PrecisionNote { /// precision bounds (e.g. 2.5 ULP division, a possibly unfused `Fma`) rather than correct /// rounding. A fast (`arcp`) division is the device's `OpFDiv`, where Metal's is `x` times a /// reciprocal it rounds within about 0.64 ulp but not correctly. Not recorded by precise - /// `fmod`, whose answer is the one right value on every device, nor, on a device whose `float` - /// functions are Metal's own (MoltenVK), in an entry Metal compiles with fast math - /// ([`EntryMath::Fast`]), by a fast division, which is Metal's own there, or by a call the - /// device answers as Metal's own function. + /// `fmod`, whose answer is the one right value on every device. DeviceArithmetic, /// Float operations LLVM requires to keep signed zeros, infinities, and NaNs run without /// `SignedZeroInfNanPreserve`, which the device does not support at their width. Without the @@ -830,11 +819,7 @@ pub enum PrecisionNote { /// 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. Not by such an - /// access at a texture slot bound to a 32-bit float or packed small float format on a profile - /// that takes [`DriverDeviation::MetalHalfConversion`](crate::error::DriverDeviation::MetalHalfConversion), - /// whose `half` of such a texel is measured to be Metal's (`0x7e00` for its NaN); the module - /// then requires `VkProperty::MetalHalfConversion`. Also recorded + /// controls (ANV, RADV), the NaN that conversion makes of the device's decode. 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 @@ -867,9 +852,7 @@ pub enum PrecisionNote { /// device converts the NaN as it likes, where Metal's fill keeps a half NaN's sign and payload /// and makes a small float's all ones. Not recorded by a texture write of a constant texel none /// of whose lanes is a NaN, nor where the write's stored NaN is measured to be Metal's: a - /// `half` texel's write to a 32-bit float format on a profile that takes - /// `DriverDeviation::MetalNanMoves` (MoltenVK on the Apple M3 Max's macOS 27 identity), and a - /// `float` or `half` texel's write to `RG11B10Float` on one that takes + /// `float` or `half` texel's write to `RG11B10Float` on a profile that takes /// `DriverDeviation::MetalSmallFloatNans` (that identity and lavapipe) (the module then /// requires the matching `VkProperty`). Validation derives no tolerance and no explanation from /// it, as for `DeviceDenormals`. @@ -953,10 +936,7 @@ pub enum PrecisionNote { /// result, and its nearest even `half` is Metal's `half` but for the classes the note is /// recorded under, by the slot's bound format (`SpecKey::TexelFormat`): a 32-bit float /// texel's sample, which Metal rounds toward zero (within one `half` ulp, but past `±65504` the - /// infinity of its sign where Metal saturates to `±65504`), but on a profile that takes - /// [`DriverDeviation::MetalHalfConversion`](crate::error::DriverDeviation::MetalHalfConversion), - /// whose `half` of every `float` word a read, sample or gather hands back is measured to be - /// Metal's (the module then requires `VkProperty::MetalHalfConversion`); a 16-bit normalized texel, whose + /// infinity of its sign where Metal saturates to `±65504`); a 16-bit normalized texel, whose /// `float` steps `65455 / 65535`, `65519 / 65535` and `32759 / 32767` round twice (one `half` /// ulp); and a format whose conversion is not measured (unbounded). A heap element and a depth /// texture record it wherever they are accessed. A two-plane YCbCr texture on the grid `8192` @@ -1757,21 +1737,15 @@ pub enum PrecisionNote { /// computed `half` NaN is `0x7FFF` (where 18 C3 cases differed in NaNs, signs of zero, /// `atan2` and `pow` at special operands, and `half` texel and pack conversions). /// - /// Not recorded for that rounding on a profile that takes - /// [`DriverDeviation::MetalHalfConversion`](crate::error::DriverDeviation::MetalHalfConversion) - /// (MoltenVK on the Apple M3 Max's macOS 27 identity) where every `half` the module rounds - /// through the conversion is a conversion of a `float` the function holds (an AIR `fptrunc` or - /// `air.convert` from `float`, whatever computed the `float`) or of a texel's value, measured to - /// answer Metal's `half(float)` there; the module then requires - /// `VkProperty::MetalHalfConversion`. A texel's value is an image instruction's texel, a texel - /// the module decodes itself (an extended-range, padded or bfloat code) or a merge of texels (a - /// heap read's fetched texel and its decode routine's): where Metal's `half` texel is not that - /// rounding of the value, the access records its own note ([`PrecisionNote::HalfTexelConversion`], - /// outright for a heap element; [`PrecisionNote::DevicePackConversion`] for a decoded texel). A - /// `half` operation or function the module computes in `float` and rounds keeps this note - /// there (Metal's `half` `tanh` answers 7 of the 65,536 `half`s otherwise than the conversion - /// of its `float` `tanh`), as does every other rounding - /// (`lower::arith::narrow::rounds_unmeasured`). + /// Recorded for every such rounding, a conversion of a `float` the function holds (an AIR + /// `fptrunc` or `air.convert` from `float`), of a texel's value, or of a `half` operation or + /// function the module computes in `float` (Metal's `half` `tanh` answers 7 of the 65,536 + /// `half`s otherwise than the conversion of its `float` `tanh`). A texel's value is an image + /// instruction's texel, a texel the module decodes itself (an extended-range, padded or bfloat + /// code) or a merge of texels (a heap read's fetched texel and its decode routine's): where + /// Metal's `half` texel is not that rounding of the value, the access records its own note + /// too ([`PrecisionNote::HalfTexelConversion`], outright for a heap element; + /// [`PrecisionNote::DevicePackConversion`] for a decoded texel). /// /// Every `half` a module reads from its bits (a load, a reinterpretation, a texel's bits) is /// the device's widening of them, on every device: an `OpFConvert` to 32 bits of the bits read @@ -1780,10 +1754,8 @@ pub enum PrecisionNote { /// bits) where they are not the bits it was read from: the device's narrowing of it, an /// `OpFConvert` to 16 bits read as a word with `shaderFloat16`, `GLSL.std.450 PackHalf2x16` /// without it. A module that reads or encodes one records this note too where that widening - /// or narrowing is neither under the float controls' `DenormPreserve` for 16 bits (ANV, RADV, - /// NVIDIA) nor measured to read and narrow every `half` as Metal's (MoltenVK's conversion is, - /// `DriverDeviation::MetalHalfArithmetic`, and the module requires it there), so on every - /// device without `shaderFloat16`: its bound is the last two items', a half denormal read or + /// or narrowing is not under the float controls' `DenormPreserve` for 16 bits (ANV, RADV, + /// NVIDIA), so on every device without `shaderFloat16`: its bound is the last two items', a half denormal read or /// encoded as the zero of its sign on a device that flushes 16-bit denormals (the Vulkan spec /// lets a device flush a denormal "obtained via unpacking an integer" without `DenormPreserve` /// for 16 bits, and gives `UnpackHalf2x16` and `PackHalf2x16` implementation-defined @@ -1833,13 +1805,8 @@ pub enum PrecisionNote { /// (an `OpFConvert` to 16 bits with `shaderFloat16`, `PackHalf2x16` without it), and a NaN /// narrows to a NaN whose bits are the device's, where Metal keeps a `half` NaN's sign and /// payload. Every other `half` widens to its value and narrows to its bits, but a denormal on a - /// device that may flush 16-bit ones ([`PrecisionNote::NativeHalfConversion`]). Not recorded, - /// on a device whose moves of a NaN are measured to be Metal's (MoltenVK on the Apple M3 Max's - /// macOS 27 identity, `DriverDeviation::MetalNanMoves`), for a `float` `fneg` or `fabs`, a - /// `half`'s widening to `float` or `fabs`, or a module's reads and encodes of a `half`'s bits - /// where it moves its `half` values through the registers alone, or into a texture write's - /// texel, whose store the write's [`PrecisionNote::DeviceNanEncoding`] accounts for. - /// Validation derives no tolerance from it. + /// device that may flush 16-bit ones ([`PrecisionNote::NativeHalfConversion`]). Validation + /// derives no tolerance from it. 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 @@ -1863,9 +1830,8 @@ pub enum PrecisionNote { /// Native device maths: Metal's `dot` on `float` and `half` is the device's `OpDot` (a `half` /// one summed in `float` and rounded once to `half`, or the device's 16-bit `OpDot` where the /// module computes `half` in 16 bits under the 16-bit float controls and holds its operands - /// there, `spirv::half_hold`), not Metal's fused chain of its products, on every device but - /// for a `float` one where the device's functions are Metal's own (MoltenVK, Metal's own - /// `dot`). **Recorded bound:** a `float` `dot` of `n` lanes within + /// there, `spirv::half_hold`), not Metal's fused chain of its products, on every device. + /// **Recorded bound:** a `float` `dot` of `n` lanes within /// `(3n - 1) * 2^-24 * sum |a_i * b_i|` of Metal's chain, plus `n * 2^-126` where a product is /// an `f32` denormal the device keeps (Vulkan's `OpDot` inherits `OpFMul`'s and `OpFAdd`'s /// rounding, `2n - 1` roundings, where Metal's chain rounds `n` times); a `half` one rounded @@ -1878,8 +1844,7 @@ pub enum PrecisionNote { /// (a `half` one computed in `float` and rounded once to `half`, or the device's 16-bit `FMix` /// where the module computes `half` in 16 bits under the 16-bit float controls and holds its /// operands there, `spirv::half_hold`), not Metal's `fma(t, y, fma(-t, x, x))`, on every - /// device but for a `float` one where the device's functions are Metal's own (MoltenVK, - /// Metal's own `mix`). **Recorded bound:** a `float` result within + /// device. **Recorded bound:** a `float` result within /// `2^-21 * (|x * (1 - t)| + |y * t|)` of Metal's (Vulkan's `FMix` inherits /// `x * (1 - t) + y * t`'s rounding, four roundings, where Metal's rounds twice); a `half` one /// rounded from `float` within `3 * 2^-10 * (|x * (1 - t)| + |y * t|) + 2^-23`, and a 16-bit @@ -1900,14 +1865,7 @@ pub enum PrecisionNote { /// encode the byte of that table's step. Also: a write of an 8-bit sRGB storage texture held /// through its UNORM alias (`StorageImageClass::SrgbEncode`, Vulkan having no sRGB storage /// view), at a slot or held by an argument buffer, encodes by `unorm4x8_srgb`'s pack. - /// Recorded on every device but for - /// a `float` conversion of the four named formats on a device whose functions are Metal's own - /// (MoltenVK: Metal's own `pack_float_to_*` and `unpack_*_to_float`), and but for the forms - /// measured to answer Metal's on a profile that takes - /// [`DriverDeviation::MetalPackConversions`](crate::error::DriverDeviation::MetalPackConversions) - /// (MoltenVK on the Apple M3 Max's macOS 27 identity: `unorm565` in `float`, and in `half` - /// `unorm4x8`, `snorm4x8`, `unorm10a2` and `unorm565` both ways and `unorm2x16` and - /// `snorm2x16` packed), which require `VkProperty::MetalPackConversions`. **Recorded bound:** + /// Recorded on every device. **Recorded bound:** /// Vulkan bounds the instructions by their definition (`round(clamp(c) * scale)` and /// `c / scale`): a packed code within one of Metal's, apart only where `clamp(c) * scale` lies /// within its `float` rounding of a half-integer (`Round` may tie either way); an unpacked @@ -2337,23 +2295,6 @@ pub enum PrecisionNote { DeviceFragmentRuns, } -/// The math mode of an entry's module, which decides, on a device whose `float` functions are -/// Metal's own (MoltenVK), how Metal compiles the entry's functions and its fast divisions, and -/// so which of its operations record a precision note: a module declares `SignedZeroInfNanPreserve` -/// where a `float` operation of the entry lacks one of the `nnan`, `ninf`, and `nsz` flags (an -/// entry Metal compiled without fast math) and the device supports the mode at the operation's -/// width. [`PrecisionNote::of_float_operator`] and [`PrecisionNote::of_math_call`] read it. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] -pub enum EntryMath { - /// The module declares no `SignedZeroInfNanPreserve`: Metal compiles it with fast math, its - /// fast division and its fast functions Metal's own. - Fast, - /// The module declares `SignedZeroInfNanPreserve`: Metal compiles it with its precise - /// functions and a correctly rounded division. - Precise, -} - /// Which lowering strategies a module used, with their word costs. /// /// Keys name `Strategy` variants (`Family::Variant`) for reporting only; translation never reads diff --git a/crates/metal2vulkan/src/pipeline/compile.rs b/crates/metal2vulkan/src/pipeline/compile.rs index 9b78c90f6..2041f16f8 100644 --- a/crates/metal2vulkan/src/pipeline/compile.rs +++ b/crates/metal2vulkan/src/pipeline/compile.rs @@ -3266,28 +3266,17 @@ fn lower_bounded( let device_quantize = quantize == crate::spirv::builder::QuantizeForm::Device && crate::lower::arith::narrow::quantizes(&module); // A `half` rounded through the device's conversion to 16 bits and back, with no quantize: the - // module records the native note, but where the device's conversion is measured to answer - // Metal's (`DriverDeviation::MetalHalfConversion`) and every such rounding is of a form the - // measurement covers (a `float` the function converts, or an image instruction's texel), - // which the module then requires. + // module records the native note. let converts = quantize == crate::spirv::builder::QuantizeForm::Converted && crate::lower::arith::narrow::rounds_by_conversion(&module, m)?; - let measured_conversion = converts - && p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfConversion) - && !crate::lower::arith::narrow::rounds_unmeasured(&module, m)?; // A `half` read from its bits by the device's widening, or encoded to them by its narrowing // (every profile: `OpFConvert` with `shaderFloat16`, `UnpackHalf2x16` and `PackHalf2x16` // without): a NaN's bits are the device's, recorded. Under the float controls its denormals - // are Metal's, as a single conversion's, also on a driver that folds the round trip; on a - // device whose conversion is measured to read and - // narrow every `half` as Metal's (`DriverDeviation::MetalHalfArithmetic`) the module requires - // that fact; elsewhere the device may flush them, within the native conversion's note. + // are Metal's, as a single conversion's, also on a driver that folds the round trip; elsewhere + // the device may flush them, within the native conversion's note. let widens = crate::lower::arith::narrow::widens_bits(&module, m)? || crate::lower::arith::narrow::encodes_bits(&module, m)?; - let measured_widening = widens - && quantize == crate::spirv::builder::QuantizeForm::Converted - && p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic); - let native_widening = widens && !controls && !measured_widening; + let native_widening = widens && !controls; // A `half` rounded through the conversion and its widening under the float controls: Metal's // `half(float)` by the Vulkan spec, but a driver's compiler may fold the pair into the value it // started from or fuse the `float` operation computing the value into the narrowing and round @@ -3295,17 +3284,6 @@ fn lower_bounded( // the rounding. let controlled = quantize == crate::spirv::builder::QuantizeForm::Controlled; let fused = controlled && crate::lower::arith::narrow::rounds_by_conversion(&module, m)?; - // Its NaN's bits, and those of a `half` held widened that a widening to `float` or a `half` - // `fabs` moves: Metal's where the device's widening and narrowing are measured to answer - // them (`DriverDeviation::MetalNanMoves`) and the module moves its `half` values only as - // measured, which it then requires; the device's, recorded, elsewhere. - let held_moves = plan.families.arith.held_nan_moves; - let unfolded = (widens || held_moves) - && p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves) - && crate::lower::arith::narrow::moves_unfolded(&module, m)?; - let moved_nans = widens - && p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves) - && !unfolded; // A `half` rounded through the device's conversion and its widening, each decorated // `NoContraction`, under the float controls that make it Metal's, computed by the device's // 16-bit arithmetic, which they make Metal's too, or read from its bits by the device's @@ -3320,16 +3298,13 @@ fn lower_bounded( module.declare_modes(&modes)?; } // Native half rounding and widening: a module that rounds through the device's quantize or - // conversion, or widens a `half` by the device where that is not measured or controlled to be - // Metal's, records each kind, and requires no fact. + // conversion, or widens a `half` by the device where that is not controlled to be Metal's, + // records each kind, and requires no fact. let native_half = [ - ( - (widens && !moved_nans) || (held_moves && unfolded), - PrecisionNote::NativeNanEncoding, - ), + (widens, PrecisionNote::NativeNanEncoding), (device_quantize, PrecisionNote::NativeHalfQuantize), ( - (converts && !measured_conversion) || native_widening || fused, + converts || native_widening || fused, PrecisionNote::NativeHalfConversion, ), ]; @@ -3404,39 +3379,6 @@ fn lower_bounded( false => VkProperty::MetalSampler, }); } - // A NaN's bits left to the device's widening, narrowing, negation or magnitude because they - // are Metal's. - if plan.families.arith.nan_moves || moved_nans || (held_moves && !unfolded) { - requirements - .properties - .insert(crate::device::requirements::VkProperty::MetalNanMoves); - } - // A `half` rounded by the device's conversion with no note because it is Metal's. - if measured_conversion { - requirements - .properties - .insert(crate::device::requirements::VkProperty::MetalHalfConversion); - } - // A packed format's conversion left to the device with no note because it is Metal's. - if plan.families.arith.metal_packs { - requirements - .properties - .insert(crate::device::requirements::VkProperty::MetalPackConversions); - } - // Metal's `float` and `half` minimum and maximum family left to the device's `NMin`, `NMax` - // and `NClamp` because they are Metal's. - if plan.families.arith.device_min_max { - requirements - .properties - .insert(crate::device::requirements::VkProperty::MetalMinMax); - } - // `half` `+ - * /` left to the device's 16-bit arithmetic because it is Metal's, and a `half` - // read from its bits by the device's widening, whose denormals that measurement makes Metal's. - if plan.families.arith.f16_arith || measured_widening { - requirements - .properties - .insert(crate::device::requirements::VkProperty::MetalHalfArithmetic); - } // A fragment's simdgroup lane read from its subgroup lane because the device's fragment // subgroups are Metal's simdgroups. if plan.families.simd.metal_lane { @@ -3451,27 +3393,6 @@ fn lower_bounded( .properties .insert(crate::device::requirements::VkProperty::MetalFullQuads); } - // `float` denormals left to the device because it reads them as Metal does: measured in - // entries that declare no float-controls mode. In one that declares the 16-bit controls a - // driver may keep them (NVIDIA's on the RTX 3090 and the RTX 5080 Laptop GPU), and no query - // tells which: there they are the device's own on every device, noted. - if plan.families.arith.device_denormals { - if !declares_controls { - requirements - .properties - .insert(crate::device::requirements::VkProperty::MetalFloatDenormals); - } else if !precision.contains(&PrecisionNote::DeviceDenormals) { - precision.push(PrecisionNote::DeviceDenormals); - precision.sort_unstable(); - } - } - // The negations, absolute values, floors and ceilings whose `float` denormals the device - // reads as Metal does. - if plan.families.arith.unary_denormals { - requirements - .properties - .insert(crate::device::requirements::VkProperty::MetalUnaryDenormals); - } // Center varyings read as they are as their pixel form, because the device reads them at // the pixel center as Metal does. if plan.families.stage_io.center_varyings_by_device { diff --git a/crates/metal2vulkan/src/pipeline/mod.rs b/crates/metal2vulkan/src/pipeline/mod.rs index f5aa08c4e..8c011bc3a 100644 --- a/crates/metal2vulkan/src/pipeline/mod.rs +++ b/crates/metal2vulkan/src/pipeline/mod.rs @@ -104,9 +104,9 @@ pub(crate) mod tile_map; pub(crate) mod vertex; pub use artifact::{ - ComputePipeline, ComputePipelineMetalInfo, EntryMath, ModuleStats, PrecisionNote, - Reconvergence, RenderPipeline, RuntimeDependency, SpecClause, SpecConstant, SpecTest, - SpecializationLayout, SpecializedNote, StageModule, StrategyCensus, StrategyUse, + ComputePipeline, ComputePipelineMetalInfo, ModuleStats, PrecisionNote, Reconvergence, + RenderPipeline, RuntimeDependency, SpecClause, SpecConstant, SpecTest, SpecializationLayout, + SpecializedNote, StageModule, StrategyCensus, StrategyUse, }; pub use descriptor::{ ColorAttachmentDescriptor, ComputePipelineDescriptor, DynamicLibraries, FunctionDescriptor, diff --git a/crates/metal2vulkan/src/pipeline/testing.rs b/crates/metal2vulkan/src/pipeline/testing.rs index 07696d91b..ed7e1d90b 100644 --- a/crates/metal2vulkan/src/pipeline/testing.rs +++ b/crates/metal2vulkan/src/pipeline/testing.rs @@ -185,14 +185,10 @@ pub fn storage_buffers(a: &FunctionArtifact) -> u32 { } /// Whether artifact `a` leaves a NaN's bits to the device, which the interpreter does not model: -/// it records `PrecisionNote::NativeNanEncoding`, or it requires `VkProperty::MetalNanMoves`, whose -/// measured device answers Metal's bits where the interpreter's conversions answer their own. +/// it records `PrecisionNote::NativeNanEncoding`. pub fn device_nan_bits(a: &FunctionArtifact) -> bool { a.precision .contains(&crate::pipeline::artifact::PrecisionNote::NativeNanEncoding) - || a.requirements - .properties - .contains(&crate::device::requirements::VkProperty::MetalNanMoves) } /// A fresh per-attempt meter with the standard caps and no deadline. diff --git a/crates/metal2vulkan/src/spirv/builder/mod.rs b/crates/metal2vulkan/src/spirv/builder/mod.rs index 314611725..a01c601a9 100644 --- a/crates/metal2vulkan/src/spirv/builder/mod.rs +++ b/crates/metal2vulkan/src/spirv/builder/mod.rs @@ -11,7 +11,7 @@ pub mod ops; pub use function::FunctionBuilder; pub(crate) use module::{geometry_per_vertex, mesh_arrayed, mesh_per_primitive}; -pub use module::{ModuleBuilder, NarrowFmt, ProductForm, QuantizeForm}; +pub use module::{ModuleBuilder, NarrowFmt, QuantizeForm}; #[cfg(test)] mod tests; diff --git a/crates/metal2vulkan/src/spirv/builder/module.rs b/crates/metal2vulkan/src/spirv/builder/module.rs index 7278d6328..54db9a256 100644 --- a/crates/metal2vulkan/src/spirv/builder/module.rs +++ b/crates/metal2vulkan/src/spirv/builder/module.rs @@ -90,16 +90,6 @@ pub struct ModuleBuilder { /// Every result that carries a non-uniform descriptor element (`Inst::carries_non_uniform`): /// decorated `NonUniform`, and refused where it would reach an undecorated operand. pub(super) non_uniform: BTreeSet, - /// The narrowings to 16 bits of the conversion pairs that round a `half` in a form measured - /// to answer Metal's on the devices whose driver takes `DriverDeviation::MetalHalfConversion` - /// (`ModuleBuilder::note_measured_rounding`). Nothing emitted depends on it: the compile - /// reads it to decide `PrecisionNote::NativeHalfConversion`. - pub(super) measured_roundings: BTreeSet, - /// The texels the texture family's writes store (`ModuleBuilder::note_stored_texel`), whose - /// stored NaN the write's own notes account for (`lower::texture::half_write_nans` and - /// `half_storage_facts`). Nothing emitted depends on it: the compile reads it to decide - /// `PrecisionNote::NativeNanEncoding` (`lower::arith::narrow::moves_unfolded`). - pub(super) stored_texels: BTreeSet, /// The `Function` variables the emitter holds workgroup uniform by construction /// (`FunctionBuilder::note_uniform_var`). Nothing emitted depends on it: a record for the /// checks of `spirv::testing::barriers`, kept only where they build. @@ -156,9 +146,6 @@ pub struct ModuleBuilder { /// The encode of a narrow vector computed for its lanes' stores in a block, with its offer /// group (`FunctionBuilder::note_encode`). pub(super) encodes: HashMap<(NarrowFmt, Value), (Value, BlockId, u32)>, - /// How a float multiply the device must round on its own is emitted - /// ([`ModuleBuilder::product_form`]). - pub(super) product_form: ProductForm, /// How the lowering rounds an `f32` to `half` ([`ModuleBuilder::quantize_form`]). quantize_form: QuantizeForm, /// Whether that rounding is the device's own rather than one measured to be Metal's @@ -172,27 +159,6 @@ pub struct ModuleBuilder { half_controls: bool, } -/// How a float multiply the device must round on its own and never fuse is emitted -/// ([`FunctionBuilder::binary_no_contraction`]). Lowering takes it from the profile's `float` -/// functions fact (`ArithPlan::product`). In either form an `f32` product by a constant with a -/// `-0.0` component multiplies by `+0.0` there and negates that component of the product. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum ProductForm { - /// `OpFMul` decorated `NoContraction`, for a device whose driver compiles the SPIR-V itself: - /// the device rounds the product once, keeps a `-0` product, and folds a zero factor as - /// Metal does (`x · 0` to `0` where the multiply carries `nsz`). It has no addend a device - /// could answer for a zero product. - #[default] - Multiply, - /// `GLSL.std.450 Fma(a, b, -0.0)` decorated `NoContraction`, for a device whose SPIR-V reaches - /// Metal's compiler through SPIRV-Cross (MoltenVK, the profile whose `float` functions are - /// Metal's): SPIRV-Cross renders a `NoContraction` `OpFMul` as `fma(l, r, 0)`, which answers - /// `+0` for a `-0` product, and this form as `fma(a, b, -0.0)`, which Metal's compiler treats - /// as Metal treats its own multiply. `a · b + (-0.0)` is `a · b` exactly whether the device - /// fuses it or not. - NegativeZeroFma, -} - /// How the lowering rounds an `f32` to `half` (`lower::arith::narrow`): the device's own /// rounding. Lowering takes it from the profile's `shaderFloat16` and float-controls properties /// (`ArithPlan::quantize`). `Controlled` gives Metal's conversion to `half` (to nearest even on the @@ -260,13 +226,6 @@ impl ModuleBuilder { ModuleBuilder::default() } - /// Emit every float multiply the device must round on its own in `form`. Emission sets it - /// before any instruction, from the profile's `float` functions fact; a builder that never - /// sets it emits [`ProductForm::Multiply`]. - pub fn product_form(&mut self, form: ProductForm) { - self.product_form = form; - } - /// Round an `f32` to `half` in `form`. Emission sets it before any instruction, from the /// profile; a builder that never sets it emits [`QuantizeForm::Device`]. pub fn set_quantize_form(&mut self, form: QuantizeForm) { @@ -285,19 +244,6 @@ impl ModuleBuilder { self.native_half = native; } - /// Record `narrowed`, the narrowing to 16 bits of a conversion pair that rounds a `half` in a - /// form measured to answer Metal's where the driver takes - /// `DriverDeviation::MetalHalfConversion` (`narrow::round_measured`). - pub fn note_measured_rounding(&mut self, narrowed: Value) { - self.measured_roundings.insert(narrowed); - } - - /// Record `texel`, a texel a texture write stores, whose stored NaN the write's own notes - /// account for (`lower::texture::emit`). - pub fn note_stored_texel(&mut self, texel: Value) { - self.stored_texels.insert(texel); - } - /// Whether the module's `half` rounding is the device's own /// ([`ModuleBuilder::set_native_half`]). pub fn native_half(&self) -> bool { @@ -378,8 +324,6 @@ impl ModuleBuilder { std::mem::size_of::<(GlobalId, crate::spv::Capability)>(), ) + tree_bytes(self.non_uniform.len(), std::mem::size_of::()) - + tree_bytes(self.measured_roundings.len(), std::mem::size_of::()) - + tree_bytes(self.stored_texels.len(), std::mem::size_of::()) + map_bytes(&self.bits) + map_bytes(&self.lanes) + map_bytes(&self.inserts) @@ -1376,8 +1320,6 @@ impl ModuleBuilder { unwritten_buffers: self.unwritten_buffers, enabling: self.enabling, non_uniform: self.non_uniform, - measured_roundings: self.measured_roundings, - stored_texels: self.stored_texels, #[cfg(test)] uniform_vars: self.uniform_vars, }) diff --git a/crates/metal2vulkan/src/spirv/builder/ops/arith.rs b/crates/metal2vulkan/src/spirv/builder/ops/arith.rs index 770265b74..3f16adc38 100644 --- a/crates/metal2vulkan/src/spirv/builder/ops/arith.rs +++ b/crates/metal2vulkan/src/spirv/builder/ops/arith.rs @@ -1,12 +1,11 @@ //! Arithmetic, bitwise, logical, comparison, linear-algebra, select, and bit-field constructors. use crate::spirv::builder::function::FunctionBuilder; -use crate::spirv::builder::module::ProductForm; use crate::spirv::builder::ops::{err, Num}; use crate::spirv::error::{BResult, OperandRule}; use crate::spirv::ids::{TypeId, Value}; use crate::spirv::ir::{ - BinOp, ConstBits, ConstKind, Constant, Contraction, ConvOp, GlslOp, Inst, Shape, Type, UnOp, + BinOp, ConstBits, ConstKind, Constant, Contraction, ConvOp, Inst, Shape, Type, UnOp, ValueOrigin, }; @@ -70,19 +69,7 @@ impl FunctionBuilder<'_> { /// the operation on its own and never fuses it with another. `op` must allow the decoration /// ([`BinOp::allows_no_contraction`]). /// - /// A multiply (`FMul`) takes the module's [`ProductForm`]: an `OpFMul` decorated - /// `NoContraction` where the device's driver compiles the SPIR-V itself, or `GLSL.std.450 - /// Fma(a, b, -0.0)` decorated `NoContraction` where it reaches Metal through SPIRV-Cross. `a * - /// b + (-0.0)` is `a * b` exactly whether the device fuses it or rounds the product and then - /// the sum (`x + (-0.0)` is `x` for every `x`, either zero included). SPIRV-Cross, which - /// MoltenVK uses, renders a `NoContraction` `OpFMul` as `fma(l, r, 0)`, which answers `+0` for - /// a `-0` product; it renders the `Fma` as `fma(a, b, -0.0)`. Elsewhere the `-0.0` addend is a - /// value the device may answer: Mesa folds `Fma(0, b, -0.0)` to it under `nsz`, where Metal's - /// multiply answers `+0`, and no per-instruction decoration keeps it from doing so on Mesa - /// 26.2. The `Fma`'s decoration is still needed: Mesa splits a contractable `Fma` into a - /// multiply and an add and folds the `-0.0` away, leaving a multiply that may be fused with a - /// following add allowing contraction (NIR's `fuse` option on older Mesa, or a backend such as - /// ACO). Mesa's SPIR-V reader marks a `NoContraction` result exact, so it is not split. + /// A multiply (`FMul`) is an `OpFMul` decorated `NoContraction`, which the device rounds once. pub fn binary_no_contraction(&mut self, op: BinOp, a: Value, b: Value) -> BResult { self.binary_with(op, a, b, Contraction::Forbidden) } @@ -220,13 +207,6 @@ impl FunctionBuilder<'_> { return Ok(r); } } - if op == BinOp::FMul - && contract == Contraction::Forbidden - && self.mb().product_form == ProductForm::NegativeZeroFma - { - let z = self.negative_zero(a)?; - return self.glsl_with(GlslOp::Fma, &[a, b, z], Contraction::Forbidden); - } self.emit(Inst::Binary { op, a, b, contract }, ty) } @@ -330,7 +310,7 @@ impl FunctionBuilder<'_> { /// The product `op` of `a` and `b` where one of them is an `f32` constant with a `-0.0` /// component, on every device: the product by that constant with each such component `+0.0` - /// (in the module's [`ProductForm`]), negated in those components of the result + /// (an `OpFMul`), negated in those components of the result /// (`OpFNegate`, and an `OpVectorShuffle` of the product and its negation where only some /// components are). `-(x · +0)` is `x · (−0)` for every `x`; a NaN's sign is the device's /// either way. So no product the module emits has a `-0.0` factor beside a `+0.0` one, which a @@ -428,24 +408,6 @@ impl FunctionBuilder<'_> { self.module().const_value(id) } - /// The `-0.0` of `v`'s float scalar or vector type: the sign bit alone in each component. - fn negative_zero(&mut self, v: Value) -> BResult { - let x = self.want(crate::spv::Op::FMul, 0, v, Num::is_float)?; - let s = self.module().constant(Constant::Scalar { - ty: x.elem, - bits: ConstBits(1u64 << (x.width - 1)), - })?; - let c = if x.n == 1 { - s - } else { - self.module().constant(Constant::Composite { - ty: x.ty, - parts: vec![s; usize::from(x.n)].into(), - })? - }; - self.module().const_value(c) - } - /// The value of `v` when it is a plain `bool` constant. pub fn const_bool(&self, v: Value) -> BResult> { Ok(match self.scalar_const(v)? { diff --git a/crates/metal2vulkan/src/spirv/half_hold.rs b/crates/metal2vulkan/src/spirv/half_hold.rs index 8698ebca6..d236650e7 100644 --- a/crates/metal2vulkan/src/spirv/half_hold.rs +++ b/crates/metal2vulkan/src/spirv/half_hold.rs @@ -1118,14 +1118,6 @@ fn rewrite( } block.term.for_each_value_mut(swap); } - m.measured_roundings.retain(|v| !replaced.contains_key(v)); - let texels = tree_bytes(m.stored_texels.len(), std::mem::size_of::()); - charge(meter, ledger, texels)?; - m.stored_texels = m - .stored_texels - .iter() - .map(|v| replaced.get(v).copied().unwrap_or(*v)) - .collect(); Ok(Some(held)) } diff --git a/crates/metal2vulkan/src/spirv/ir/edit.rs b/crates/metal2vulkan/src/spirv/ir/edit.rs index 0b3ea69b4..84700ec97 100644 --- a/crates/metal2vulkan/src/spirv/ir/edit.rs +++ b/crates/metal2vulkan/src/spirv/ir/edit.rs @@ -405,8 +405,6 @@ impl TypedModule { }; let values = &self.values; self.non_uniform.retain(|v| !removed(v, values)); - self.measured_roundings.retain(|v| !removed(v, values)); - self.stored_texels.retain(|v| !removed(v, values)); self.loops.retain(|l| at(&bmap, l.header.index()).is_some()); for l in &mut self.loops { l.header = block(l.header); diff --git a/crates/metal2vulkan/src/spirv/ir/module.rs b/crates/metal2vulkan/src/spirv/ir/module.rs index 84de08a74..973474a30 100644 --- a/crates/metal2vulkan/src/spirv/ir/module.rs +++ b/crates/metal2vulkan/src/spirv/ir/module.rs @@ -1471,13 +1471,6 @@ pub struct TypedModule { /// The values decorated `NonUniform`: every result that carries a non-uniform descriptor /// element ([`Inst::carries_non_uniform`]), recorded as the builder appends it. pub(in crate::spirv) non_uniform: std::collections::BTreeSet, - /// The narrowings to 16 bits of the conversion pairs that round a `half` in a form measured - /// to answer Metal's where the driver takes `DriverDeviation::MetalHalfConversion` - /// (`ModuleBuilder::measured_roundings`), recorded as the builder emits them. - pub(in crate::spirv) measured_roundings: std::collections::BTreeSet, - /// The texels the texture family's writes store, whose stored NaN the write's own notes - /// account for (`ModuleBuilder::stored_texels`), recorded as the builder emits them. - pub(in crate::spirv) stored_texels: std::collections::BTreeSet, /// The `Function` variables the emitter holds workgroup uniform by construction: the `cont` /// flag of a predicated loop that iterates together, which the lowering's uniformity analysis /// proved. An in-memory record for checks (`spirv::testing::barriers`), kept only where they @@ -1503,17 +1496,6 @@ impl TypedModule { &self.consts } - /// The narrowings to 16 bits of the conversion pairs that round a `half` in a form measured to - /// answer Metal's (`ModuleBuilder::note_measured_rounding`). - pub fn measured_roundings(&self) -> &std::collections::BTreeSet { - &self.measured_roundings - } - - /// The texels the texture family's writes store (`ModuleBuilder::note_stored_texel`). - pub fn stored_texels(&self) -> &std::collections::BTreeSet { - &self.stored_texels - } - /// The SSA value of a constant. pub fn const_value(&self, c: ConstId) -> BResult { self.const_values diff --git a/crates/metal2vulkan/src/spirv/roll/mod.rs b/crates/metal2vulkan/src/spirv/roll/mod.rs index 3eeeb5391..315aa43f3 100644 --- a/crates/metal2vulkan/src/spirv/roll/mod.rs +++ b/crates/metal2vulkan/src/spirv/roll/mod.rs @@ -1854,8 +1854,6 @@ fn verify( for (x, y) in pairs { if m.value(x)?.ty != m.value(y)?.ty || m.non_uniform.contains(&x) != m.non_uniform.contains(&y) - || m.measured_roundings.contains(&x) != m.measured_roundings.contains(&y) - || m.stored_texels.contains(&x) != m.stored_texels.contains(&y) { return Ok(None); } diff --git a/crates/metal2vulkan/src/spirv/serialize/tests/families.rs b/crates/metal2vulkan/src/spirv/serialize/tests/families.rs index 5a8399e16..b24589d64 100644 --- a/crates/metal2vulkan/src/spirv/serialize/tests/families.rs +++ b/crates/metal2vulkan/src/spirv/serialize/tests/families.rs @@ -5,7 +5,7 @@ use super::{assert_spirv_valid, float, int, vec}; use crate::spirv::builder::ops::group::GroupMode; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder, ProductForm}; +use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; use crate::spirv::ids::{FuncId, TypeId, Value}; use crate::spirv::ir::{ AtomicOp, BinOp, Constant, Contraction, ConvOp, ExecMode, ExecModel, GlslOp, GroupArith, @@ -287,18 +287,10 @@ fn binary_operations() { /// `NoContraction`: every float arithmetic opcode takes it, `spirv-val` accepts the decoration, and /// exactly the decorated results carry it; other opcodes refuse it. A multiply rounded on its own -/// takes the module's [`ProductForm`]: an `OpFMul` decorated `NoContraction` by default, or -/// `GLSL.std.450 Fma(a, b, -0.0)` decorated `NoContraction`, its addend the `-0.0` of its type, -/// where the module's SPIR-V reaches Metal through SPIRV-Cross. An `Fma` built -/// without the decoration stays undecorated, and no other `GLSL.std.450` instruction takes it. +/// is an `OpFMul` decorated `NoContraction`. An `Fma` built without the decoration stays +/// undecorated, and no other `GLSL.std.450` instruction takes it. #[test] fn no_contraction_decorates_float_arithmetic() { - for form in [ProductForm::Multiply, ProductForm::NegativeZeroFma] { - no_contraction_under(form); - } -} - -fn no_contraction_under(form: ProductForm) { use crate::spirv::error::{BuildError, OperandRule}; let mut decorated = Vec::new(); let mut plain = Vec::new(); @@ -307,7 +299,6 @@ fn no_contraction_under(form: ProductForm) { let m = compute( |t| vec![t.f32_, t.vec4, t.f16, t.f64_, t.u32_], |f, p, _| { - f.module().product_form(form); let [x, xv, h, d, u] = p else { unreachable!() }; for a in [x, xv, h, d] { for op in [BinOp::FAdd, BinOp::FSub, BinOp::FDiv, BinOp::FRem] { @@ -384,51 +375,27 @@ fn no_contraction_under(form: ProductForm) { assert!(plain_fma.is_some()); // Results are emitted in order, each operand's group holding its four decorated results, // its plain multiply, and (as an `OpFMul`) its multiply without contraction. - let group = match form { - ProductForm::Multiply => 6, - ProductForm::NegativeZeroFma => 5, - }; - let products = match form { - ProductForm::Multiply => fused.len(), - ProductForm::NegativeZeroFma => 0, - }; - assert_eq!( - arith.len(), - decorated.len() + plain.len() + products, - "{form:?}" - ); + let group = 6; + assert_eq!(arith.len(), decorated.len() + plain.len() + fused.len()); let plain_ids: Vec = arith .chunks(group) .filter_map(|c| c.get(4).copied()) .collect(); assert_eq!(plain_ids.len(), plain.len()); - assert_eq!(targets.len(), decorated.len() + fused.len(), "{form:?}"); - // Each multiply without contraction is, in the `Fma` form, one `Fma` decorated - // `NoContraction` whose addend is `-0.0`: the sign bit alone in its last word (`half`, - // `float`, `double`, and a `float` vector). The plain `Fma`, emitted last, is undecorated. - let (fused_fmas, plain_fmas) = fmas.split_at(fmas.len() - 1); - assert_eq!(fused_fmas.len(), fused.len() - products, "{form:?}"); - let signs = [0x8000_0000u32, 0x8000_0000, 0x8000, 0x8000_0000]; - for (&(r, addend), sign) in fused_fmas.iter().zip(signs) { - assert!(targets.contains(&r), "%{r} not decorated"); - assert_eq!(constants.get(&addend), Some(&sign), "%{r}'s addend"); - } - assert!( - !targets.contains(&plain_fmas[0].0), - "the plain Fma decorated" - ); - if form != ProductForm::NegativeZeroFma { - // No `-0.0` addend at all: each multiply is the `OpFMul` after its group's plain one. - assert!(!constants - .values() - .any(|w| [0x8000_0000, 0x8000].contains(w))); - for c in arith.chunks(group).filter(|c| c.len() == group) { - assert!(targets.contains(&c[5]), "%{} not decorated", c[5]); - } + assert_eq!(targets.len(), decorated.len() + fused.len()); + // The one `Fma`, the plain one, is undecorated. + assert_eq!(fmas.len(), 1); + assert!(!targets.contains(&fmas[0].0), "the plain Fma decorated"); + // No `-0.0` addend at all: each multiply is the `OpFMul` after its group's plain one. + assert!(!constants + .values() + .any(|w| [0x8000_0000, 0x8000].contains(w))); + for c in arith.chunks(group).filter(|c| c.len() == group) { + assert!(targets.contains(&c[5]), "%{} not decorated", c[5]); } for t in &targets { assert!( - (arith.contains(t) && !plain_ids.contains(t)) || fused_fmas.iter().any(|f| f.0 == *t), + arith.contains(t) && !plain_ids.contains(t), "%{t} decorated" ); } diff --git a/crates/metal2vulkan/src/tests/engine_access.rs b/crates/metal2vulkan/src/tests/engine_access.rs index b5aaeb7a5..22ff7907c 100644 --- a/crates/metal2vulkan/src/tests/engine_access.rs +++ b/crates/metal2vulkan/src/tests/engine_access.rs @@ -965,8 +965,7 @@ fn offsets(size: u64) -> Vec { /// bounds. Probes are skipped where the offset breaks the access's stated alignment (undefined in /// Metal). A `half` NaN loaded, or stored from a constant, need only come back a NaN where the /// module reads a `half` from its bits by the device's widening or encodes one by its narrowing -/// (`PrecisionNote::NativeNanEncoding`, or `VkProperty::MetalNanMoves`, measured on a device the -/// interpreter is not: `device_nan_bits`), whose NaN encoding is the device's. +/// (`PrecisionNote::NativeNanEncoding`, `device_nan_bits`), whose NaN encoding is the device's. #[test] fn every_leaf_path_is_exact_in_bounds_and_contained_out_of_bounds() { let size = 32u64; @@ -1274,8 +1273,8 @@ fn push_with_table(plan: &Plan) -> Vec { /// and leaves the allocation unchanged. Robust buffer access does not cover device addresses, so /// the check is emitted on a robust profile too. A `half` NaN loaded, or stored from a constant, /// need only come back a NaN where the module reads a `half` from its bits by the device's -/// widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`, or -/// `VkProperty::MetalNanMoves`: `device_nan_bits`), whose NaN encoding is the device's. +/// widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`, +/// `device_nan_bits`), whose NaN encoding is the device's. #[test] fn a_device_address_slot_is_exact_and_contained() { let size = 32u64; @@ -1984,8 +1983,8 @@ fn profile_without(stem: &str, features: &[VkFeature]) -> DeviceProfile { /// follows the binder contract (descriptor base congruent to the Metal address modulo 4), and a /// sub-word store through a unit leaves its neighbours unchanged. A `half` NaN loaded, or stored /// from a constant, need only come back a NaN where the module reads a `half` from its bits by the -/// device's widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`, or -/// `VkProperty::MetalNanMoves`: `device_nan_bits`), whose NaN encoding is the device's. +/// device's widening or encodes one by its narrowing (`PrecisionNote::NativeNanEncoding`, +/// `device_nan_bits`), whose NaN encoding is the device's. #[test] fn narrow_units_are_exact_at_every_bind_residual() { let size = 32u64; diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index 3ef3bb59e..b2cce283a 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -16,7 +16,7 @@ //! (`engine_native_maths`). use crate::air::{self, SpecRequest}; -use crate::device::profile::{DeviceProfile, FloatFunctions}; +use crate::device::profile::DeviceProfile; use crate::device::requirements::VkFeature; use crate::device::requirements::VkProperty; use crate::device::{Device, DevicePolicy}; @@ -1158,12 +1158,9 @@ fn arith_kernels_validate_and_compute_on_every_profile() { plan.estimate.words ); if let Some(n) = kk.note { - // A maths function off Metal's own functions records the device's - // precision. + // A maths function records the device's precision. let n = match n { - PrecisionNote::DeviceTranscendentals - if p.fields().float_functions != FloatFunctions::Metal => - { + PrecisionNote::DeviceTranscendentals => { PrecisionNote::NativeTranscendentals } n => n, @@ -1434,8 +1431,8 @@ fn fma16_and_marks(words: &[u32]) -> (usize, usize) { /// On `Device::from_queries`' profile (`HalfFma::Native`) a `half` fused multiply-add is the /// device's 16-bit `Fma` wherever the profile computes `half` under the 16-bit float controls /// (`fma::Route::F16Native`: RADV, ANV and NVIDIA's captures): the module computes it on 16-bit -/// floats with no conversion around it, so no instruction is decorated `NoContraction`; it requires -/// no `VkProperty::MetalHalfFma`, and it records `PrecisionNote::NativeFma`, as the device's +/// floats with no conversion around it, so no instruction is decorated `NoContraction`, and it +/// records `PrecisionNote::NativeFma`, as the device's /// `float` `Fma` rounded to `half` does where the profile lacks those controls (lavapipe, which /// does not keep 16-bit denormals, and vk12-floor, without `shaderFloat16`). The 16-bit `Fma` /// rounds [`half_fma_kernel`]'s sum once on the interpreter, the `float` one twice. @@ -1475,12 +1472,6 @@ fn a_half_fused_multiply_add_is_the_devices_16_bit_fma_on_from_queries() { "{what}: {:?}", a.precision ); - assert!( - !a.requirements - .properties - .contains(&VkProperty::MetalHalfFma), - "{what}" - ); let (fmas, marks) = fma16_and_marks(&a.module.words); if controls { assert_eq!((fmas, marks), (1, 0), "{what}: 16-bit Fma, NoContraction"); @@ -1534,9 +1525,8 @@ fn opaque_vector(name: &str, half: bool, vals: &[f32]) -> String { /// `dot` on `float` and `half` is the device's `OpDot` on every profile, with and without fast /// math, on two to four lanes; of more, each chunk's `OpDot` summed. Metal's is the products' fused -/// chain: a `float` one on a profile whose `float` functions are Metal's (moltenvk-m3) reaches -/// Metal's own `dot`, with no note; every other records `NativeDot` (a `half` one summed in its -/// `float` container), and a chunked one `DeviceArithmetic`. No fused multiply-add is emitted. +/// chain: each records `NativeDot` (a `half` one summed in its `float` container), and a chunked +/// one `DeviceArithmetic`. No fused multiply-add is emitted. #[test] fn dot_is_the_devices_op_dot_on_every_profile() { let vals = |n: usize, k: f32| (0..n).map(|i| k * (i as f32 + 1.5)).collect::>(); @@ -1632,7 +1622,6 @@ fn dot_is_the_devices_op_dot_on_every_profile() { { let policy = DevicePolicy::default(); let p = profile(stem, policy).expect("profile"); - let metal = p.fields().float_functions == FloatFunctions::Metal; for kk in &ks { let what = format!("{} on {stem}", kk.name); let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); @@ -1641,7 +1630,6 @@ fn dot_is_the_devices_op_dot_on_every_profile() { assert!(count_op(&words, crate::spv::Op::Dot) > 0, "{what}: OpDot"); assert_eq!(fma(&words), 0, "{what}: a fused chain"); let chunked = kk.name.ends_with("_chunked"); - let float = kk.name.contains("_float"); if chunked { assert!( a.precision.contains(&PrecisionNote::DeviceArithmetic), @@ -1649,9 +1637,8 @@ fn dot_is_the_devices_op_dot_on_every_profile() { a.precision ); } else { - assert_eq!( + assert!( a.precision.contains(&PrecisionNote::NativeDot), - !(metal && float), "{what}: {:?}", a.precision ); @@ -1856,8 +1843,7 @@ fn every_profile() -> Vec { /// Metal's fast division answers `0x7FC00000` for a NaN divisor of either sign, a NaN numerator, /// `0 / 0` and `inf / inf`; the module leaves that NaN to the device's `OpFDiv` on every profile /// (RADV answered `0xffc00000` for a negative NaN divisor, a probe cases 9496749c and 3921d3e2), -/// selecting none, so the module is the same on both sides of `MetalCanonicalNans`, and records -/// `PrecisionNote::NativeNanEncoding` where the device is not measured to answer Metal's. Its +/// selecting none, and records `PrecisionNote::NativeNanEncoding`. Its /// `f32` denormals are the device's on every committed profile. The operands are integer bits, so /// the division is the kernel's only float operation, and it records the device's arithmetic, its /// division and its denormals, and never `DeviceNanEncoding`. The interpreter answers a NaN, its @@ -1902,8 +1888,6 @@ fn a_fast_division_leaves_its_nans_to_the_device() { nans_are_the_device_s(&bitcode, &ks, false, &[], &|_| true); for stem in every_profile() { let p = profile(&stem, crate::device::DevicePolicy::default()).expect("profile"); - let device_nans = - p.takes_driver_deviation(crate::error::DriverDeviation::MetalCanonicalNans); for kk in &ks { let what = format!("{} on {stem}", kk.name); let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); @@ -1919,9 +1903,8 @@ fn a_fast_division_leaves_its_nans_to_the_device() { a.precision ); } - assert_eq!( + assert!( a.precision.contains(&PrecisionNote::NativeNanEncoding), - !device_nans, "{what}: {:?}", a.precision ); @@ -1945,8 +1928,7 @@ fn a_fast_division_leaves_its_nans_to_the_device() { /// gives 0x3D59E381). Metal answers `0x7FC00000` for `0 / 0`; the module selects no NaN, so the /// quotient is a NaN whose bits are the device's (the interpreter's are its host CPU's: x86-64's /// default NaN, `0xFFC00000`, has its sign set, arm64's is `0x7FC00000`), noted -/// `NativeNanEncoding` exactly where the profile does not state the device answers Metal's -/// (`DriverDeviation::MetalCanonicalNans`). A `half` division under every flag set, `arcp` +/// `NativeNanEncoding`. A `half` division under every flag set, `arcp` /// included, is the `float` quotient rounded once to `half`. #[test] fn a_division_without_arcp_is_the_devices_quotient() { @@ -2003,8 +1985,6 @@ fn a_division_without_arcp_is_the_devices_quotient() { }; for stem in ["moltenvk-m3", "lavapipe", "runtime-floor"] { let p = profile(stem, crate::device::DevicePolicy::default()).expect("profile"); - let device_nans = - p.takes_driver_deviation(crate::error::DriverDeviation::MetalCanonicalNans); for kk in &ks { let what = format!("{} on {stem}", kk.name); let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); @@ -2024,9 +2004,8 @@ fn a_division_without_arcp_is_the_devices_quotient() { Some(want) => assert_eq!(got, want, "{what}: {got:#x}"), None => { assert!(stores_nan(got, false), "{what}: {got:#x}"); - assert_eq!( + assert!( a.precision.contains(&PrecisionNote::NativeNanEncoding), - !device_nans, "{what}: {:?}", a.precision ); @@ -2367,11 +2346,9 @@ fn float_ops_without_contract_and_reassoc_are_no_contraction() { let mul_rewritable = matches!(kk.name, "mul_add_reassoc_contract" | "mul_add_fast"); let add_rewritable = mul_rewritable || kk.name == "mul_strict_add_fast"; // A multiply carrying both flags is the device's `OpFMul`, undecorated; any other is - // the profile's product with `NoContraction`. - let metal = p.fields().float_functions == FloatFunctions::Metal; + // an `OpFMul` with `NoContraction`. let mul = match (muls.as_slice(), fmas.as_slice()) { - ([m], []) if mul_rewritable || !metal => *m, - ([], [m]) if !mul_rewritable && metal => *m, + ([m], []) => *m, _ => panic!("{what}: one multiply in the profile's form: {muls:?} {fmas:?}"), }; assert_eq!( @@ -2614,17 +2591,10 @@ fn half_rounding_follows_the_operation() { // Where the device's float controls make the conversion Metal's, each rounding is // that conversion and its widening too. let controlled = form == crate::spirv::builder::QuantizeForm::Controlled; - // Where the device's 16-bit `+ - *` is Metal's, measured or under the 16-bit float - // controls, the operations among the roundings: sixteen of each chain's seventeen. The - // conversion's rounding stays the module's. - let ha = (p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic) - && p.fields().leaf.float16) - || controlled; - assert!( - !ha || converted || controlled, - "{what}: the half arithmetic beside the conversion" - ); - let kept = if ha { 16 } else { 0 }; + // Where the device's 16-bit `+ - *` is Metal's, under the 16-bit float controls, the + // operations among the roundings: sixteen of each chain's seventeen. The conversion's + // rounding stays the module's. + let kept = if controlled { 16 } else { 0 }; // Each 16-bit operation reads the previous one's 16-bit result itself, and narrows // `%x0`, the conversion's rounding, which stays a pair (the first operation reads it // twice); the last result is widened once. @@ -2689,70 +2659,6 @@ fn half_rounding_follows_the_operation() { } } -/// Where the device's 16-bit `+ - *` is measured Metal's, a `half` sum is that instruction, which -/// rounds nothing of the module's: it requires `MetalHalfArithmetic`. A kernel there whose -/// `half`s (each read from its bits by a bitcast) only the device's 16-bit `fma` reads takes them -/// as 16-bit floats, with no widening, and requires nothing of that measurement. -#[test] -fn a_measured_half_sum_requires_the_arithmetic_fact_alone() { - let halves = format!( - "{}{}{} %h = bitcast i16 %t to half\n %g = bitcast i16 %s to half\n %u = bitcast i16 %v to half\n", - on("t", 16, 0x3C01), - on("s", 16, 0x4100), - on("v", 16, 0x3800) - ); - let ks = [ - Kernel { - name: "half_sum", - body: format!("{halves} %x = fadd half %h, %g\n %r = fpext half %x to float\n"), - float: true, - want: None, - needs: &[], - note: None, - }, - Kernel { - name: "half_fma", - body: format!( - "{halves} %x = call half @llvm.fma.f16(half %h, half %g, half %u)\n %r = fpext half %x to float\n" - ), - float: true, - want: None, - needs: &[], - note: None, - }, - ]; - let text = module(&ks).replace( - DECLS, - &format!("{DECLS}declare half @llvm.fma.f16(half, half, half)\n"), - ); - let Some(bitcode) = assemble("half-conversion-fact", &text) else { - return; - }; - let mut converting = 0; - for stem in PROFILES { - let p = profile(stem, crate::device::DevicePolicy::default()).expect("profile"); - let converted = crate::lower::arith::narrow::quantize_form(&p) - == crate::spirv::builder::QuantizeForm::Converted; - let ha = p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfArithmetic) - && p.fields().leaf.float16; - converting += usize::from(converted); - for kk in &ks { - let what = format!("{} on {stem}", kk.name); - let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); - link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - assert_eq!( - a.requirements - .properties - .contains(&crate::device::requirements::VkProperty::MetalHalfArithmetic), - ha && kk.name == "half_sum", - "{what}: {:?}", - a.requirements.properties - ); - } - } - assert!(converting > 0, "no profile rounds through the conversion"); -} - /// Without `shaderFloat16` every `half` rounding is the device's `OpQuantizeToF16` alone, with no /// denormal arithmetic (no `RoundEven`) whatever the operation: a transcendental, `ldexp`, a /// quotient, a square root, `fract`'s difference and the one rounding of a fused sum (`fmuladd` @@ -2832,12 +2738,10 @@ fn a_half_rounding_without_float16_is_the_quantize_alone() { let round_even = count_ops(&words, |w| { w[0] & 0xFFFF == crate::spv::Op::ExtInst as u32 && w.len() > 4 && w[4] == 2 }); - let fused = matches!(kk.name, "half_mix" | "half_fmuladd") - && p.takes_driver_deviation(crate::error::DriverDeviation::MetalHalfFma); // A rounding through the conversion holds neither, under the float controls or not. let converts = crate::lower::arith::narrow::quantize_form(&p) != crate::spirv::builder::QuantizeForm::Device; - let want = match fused || converts { + let want = match converts { true => (0, 0), false => (quantizes, 0), }; @@ -3322,11 +3226,10 @@ fn nans_are_the_device_s( } } -/// A NaN of `float` arithmetic is the device's on every profile: the module selects none, whatever -/// the profile's `MetalCanonicalNans` fact, and records `PrecisionNote::NativeNanEncoding` where -/// the device is not measured to answer Metal's: for `+`, whose canonical NaN the fact covers, -/// where the fact is absent, and for `round`, which returns a NaN operand's own bits on Metal, -/// whatever the fact. The interpreter keeps a NaN operand's payload, as such a device would. +/// A NaN of `float` arithmetic is the device's on every profile: the module selects none, and +/// records `PrecisionNote::NativeNanEncoding` for `+`, which answers Metal's canonical NaN, and for +/// `round`, which returns a NaN operand's own bits on Metal. The interpreter keeps a NaN operand's +/// payload, as such a device would. #[test] fn a_float_nan_is_the_device_s_on_every_profile() { let ks = [ @@ -3501,9 +3404,8 @@ fn float_denormals_are_the_devices_and_noted() { /// `air.sincos` answers the NaN its `sin` and `cos` answer as calls of their own, since Metal's /// `sincos` is its `sin` and `cos` word for word (cases 7b283404 and f6524207, every pair): precise -/// `sin` and `cos` without fast-math flags answer the canonical NaN, which the device answers where -/// the profile takes `MetalCanonicalNans`; elsewhere either result, read or not, is noted -/// `PrecisionNote::NativeNanEncoding`, and neither is selected. +/// `sin` and `cos` without fast-math flags answer the canonical NaN; either result, read or not, is +/// noted `PrecisionNote::NativeNanEncoding`, and neither is selected. #[test] fn sincos_answers_the_device_s_nan() { let kernel = |name: &'static str, read: &str| { @@ -3678,8 +3580,7 @@ fn half_nan_kernel(name: &'static str, body: String, want: Option) -> Kerne /// Class B: Metal's `half` `+`, `*`, and `air.fma.f16`, with or without fast-math flags, and its /// narrowing of a `float` to `half` (`fptrunc`, and `air.convert` from class E's version) answer /// the canonical `half` NaN `0x7E00`, as `half` `-` (class K's) does. The NaN is the device's on -/// every profile, selected nowhere, and noted `PrecisionNote::NativeNanEncoding` where the profile -/// does not take `MetalCanonicalNans`. +/// every profile, selected nowhere, and noted `PrecisionNote::NativeNanEncoding`. #[test] fn half_nans_answer_the_device_s_nan() { let hx = oh("hx", 0xFE01); @@ -3742,9 +3643,7 @@ fn half_nans_answer_the_device_s_nan() { /// dropped, by `fpext` and by its intrinsic form `air.convert`. A `half` is held widened, so /// `fpext` emits no device operation: the NaN is the device's widening of the `half`'s bits where /// the profile has `shaderFloat16` (both profiles here), and the module selects nothing and notes -/// `PrecisionNote::NativeNanEncoding` whatever the device fact states, but where the device's -/// widening is measured to answer Metal's (`DriverDeviation::MetalNanMoves`, on `moltenvk-m3`), -/// where it requires that. The interpreter's widening keeps the payload, as a device may. +/// `PrecisionNote::NativeNanEncoding`. The interpreter's widening keeps the payload, as a device may. #[test] fn a_widened_half_nan_keeps_its_payload_on_every_profile() { let hx = oh("hx", 0xFE01); @@ -3782,10 +3681,8 @@ fn a_widened_half_nan_keeps_its_payload_on_every_profile() { /// Class D: Metal's `half` `fneg` and `fabs` answer the canonical `half` NaN `0x7E00`, with or /// without fast-math flags. A device computes both exactly on the held value's sign, so a NaN's /// payload is kept on every profile: the module selects nothing and notes -/// `PrecisionNote::NativeNanEncoding` whatever the device fact states, as for an `fadd` whose only -/// use is the `fneg`; but `fabs` where the device's is measured to answer Metal's -/// (`DriverDeviation::MetalNanMoves`, on `moltenvk-m3`: the held value is its widening's canonical -/// NaN there), where it requires that. The interpreter keeps a `half` NaN's payload through the +/// `PrecisionNote::NativeNanEncoding`, as for an `fadd` whose only use is the `fneg`. The +/// interpreter keeps a `half` NaN's payload through the /// held value, as a device may (the value stored unchanged is `0xFE01`, and notes nothing). #[test] fn half_sign_operations_keep_a_nan_s_payload_on_every_profile() { @@ -3970,8 +3867,7 @@ fn half_moves_are_the_devices_bits() { } /// Every normalized format's `air.pack` and `air.unpack`, in `float` and `half`: the device's -/// conversion, noted `DevicePackConversion` but where it reaches Metal's own function (a `float` -/// form `GLSL.std.450` names, where the profile's `float` functions are Metal's), on every profile, +/// conversion, noted `DevicePackConversion` on every profile, /// requiring no property but the float controls the module declares. #[test] fn pack_conversions_are_the_devices() { @@ -3986,7 +3882,7 @@ fn pack_conversions_are_the_devices() { ("snorm.rgb10a2", 4, 32), ("unorm.rgb565", 3, 16), ]; - let (mut forms, mut ks) = (Vec::new(), Vec::new()); + let mut ks = Vec::new(); let mut decls = String::new(); for (format, lanes, width) in formats { for packs in [true, false] { @@ -4050,7 +3946,6 @@ fn pack_conversions_are_the_devices() { if packs { "pack" } else { "unpack" }, format.replace('.', "_") ); - forms.push((format, half)); ks.push(Kernel { want: None, ..k(Box::leak(name.into_boxed_str()), body, 0) @@ -4064,16 +3959,12 @@ fn pack_conversions_are_the_devices() { }; for stem in ["lavapipe", "moltenvk-m3"] { let p = profile(stem, DevicePolicy::default()).expect("profile"); - let metal_functions = p.fields().float_functions == FloatFunctions::Metal; - for (&(format, half), kk) in forms.iter().zip(&ks) { + for kk in &ks { let what = format!("{} on {stem}", kk.name); let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let glsl = matches!(format, "unorm4x8" | "snorm4x8" | "unorm2x16" | "snorm2x16"); - let own = metal_functions && !half && glsl; - assert_eq!( + assert!( a.precision.contains(&PrecisionNote::DevicePackConversion), - !own, "{what}: {:?}", a.precision ); @@ -4093,11 +3984,7 @@ fn pack_conversions_are_the_devices() { /// NaN keeps its payload, signaling or not, and a denormal stays. The lowering is the device's /// `OpFNegate` and `FAbs` on every profile (RADV's `fneg` keeps a NaN's sign, NVIDIA's `fabs` /// answers `0x7FFFFFFF`, RADV and ANV flush a denormal): no NaN is selected and nothing moves on -/// the bits, the NaN noted `NativeNanEncoding` but where the device's are measured to be Metal's -/// (`DriverDeviation::MetalNanMoves`, on `moltenvk-m3`), where the module requires that, and -/// `fneg`'s denormal `DeviceDenormals` but where the device keeps it as Metal does -/// (`DriverDeviation::MetalUnaryDenormals`, on `moltenvk-m3`), where the module requires that and -/// `fabs` records no `DeviceDenormals` either. The interpreter keeps the payload and the +/// the bits, the NaN noted `NativeNanEncoding`, and `fneg`'s denormal `DeviceDenormals`. The interpreter keeps the payload and the /// denormal, as a device may. #[test] fn float_sign_operations_are_the_devices_on_every_profile() { @@ -4182,40 +4069,18 @@ fn float_sign_operations_are_the_devices_on_every_profile() { assert_eq!(fabs(&words) > 0, abs, "{what}"); assert_eq!(nan_tests(&words), (0, 0), "{what}"); if neg || abs { - let moves = p.takes_driver_deviation(crate::error::DriverDeviation::MetalNanMoves); - assert_eq!( + assert!( a.precision.contains(&PrecisionNote::NativeNanEncoding), - !moves, "{what}: {:?}", a.precision ); - assert_eq!( - a.requirements - .properties - .contains(&crate::device::requirements::VkProperty::MetalNanMoves), - moves, - "{what}" - ); } - // A denormal is the device's but where it is measured to keep it as Metal does - // (`DriverDeviation::MetalUnaryDenormals`), which the module then requires. - if neg || abs { - let unary = - p.takes_driver_deviation(crate::error::DriverDeviation::MetalUnaryDenormals); - if neg || unary { - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceDenormals), - !unary, - "{what}: {:?}", - a.precision - ); - } - assert_eq!( - a.requirements - .properties - .contains(&crate::device::requirements::VkProperty::MetalUnaryDenormals), - unary, - "{what}" + // A negated denormal is the device's. + if neg { + assert!( + a.precision.contains(&PrecisionNote::DeviceDenormals), + "{what}: {:?}", + a.precision ); } let got = interpret(&bitcode, kk.name, &p); @@ -4229,10 +4094,8 @@ fn float_sign_operations_are_the_devices_on_every_profile() { /// and with some, answer an operand bit for bit (`nan_minmax`, `nan_minmax_fast`, and their /// zeros-and-denormals cases, every lane; for the other flag states): a NaN loses, two NaNs and a /// tie answer the second operand, and a denormal compares as zero but is returned itself. On every -/// profile the device's `NMin`, `NMax`, or `NClamp` decides it: where the profile takes -/// `DriverDeviation::MetalMinMax` measured to be Metal's (the interpreter models them so), and the -/// module requires `VkProperty::MetalMinMax`; elsewhere noted `PrecisionNote::NativeMinMax`. No -/// device note is recorded. +/// profile the device's `NMin`, `NMax`, or `NClamp` decides it, noted `PrecisionNote::NativeMinMax` +/// (the interpreter models them as Metal's). No device note is recorded. #[test] fn float_min_max_are_the_device_s_on_every_profile() { let two = |a: u32, b: u32| format!("{}{}", ob("x", a), ob("y", b)); @@ -4379,21 +4242,12 @@ fn float_min_max_are_the_device_s_on_every_profile() { let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); let (_, words) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); - let device = p.takes_driver_deviation(crate::error::DriverDeviation::MetalMinMax); assert!(device_pick(&words) > 0, "{what}"); - assert_eq!( + assert!( a.precision.contains(&PrecisionNote::NativeMinMax), - !device, "{what}: {:?}", a.precision ); - assert_eq!( - a.requirements - .properties - .contains(&crate::device::requirements::VkProperty::MetalMinMax), - device, - "{what}" - ); for note in [ PrecisionNote::DeviceDenormals, PrecisionNote::DeviceNanEncoding, @@ -4495,9 +4349,8 @@ fn half_fmod_is_its_float_remainder_on_every_profile() { /// Class I: Metal's `mix(x, y, t)` on `float` and `half` is `fma(t, y, fma(-t, x, x))`, with and /// without fast-math flags (`nan_functions`: `mix(inf, 1, 0)` is the canonical NaN; `nan_half`: /// `mix(-0.3, 0.7, 0.2)` is `0xAE68`, where the blend gives `0xAE66`). On every profile the module -/// takes the device's `FMix` and no fused multiply-add: a `float` one on a profile whose `float` -/// functions are Metal's (moltenvk-m3) reaches Metal's own `mix`, with no note; every other records -/// `NativeMix` (a `half` one the blend in its `float` container, rounded once). +/// takes the device's `FMix` and no fused multiply-add, and records `NativeMix` (a `half` one the +/// blend in its `float` container, rounded once). #[test] fn mix_is_the_devices_fmix_on_every_profile() { let three = |a: u32, b: u32, c: u32| format!("{}{}{}", ob("x", a), ob("y", b), ob("z", c)); @@ -4571,7 +4424,6 @@ fn mix_is_the_devices_fmix_on_every_profile() { .chain(["lavapipe", "amd-rdna3-radv"]) { let p = profile(stem, crate::device::DevicePolicy::default()).expect("profile"); - let metal = p.fields().float_functions == FloatFunctions::Metal; for kk in &ks { let what = format!("{} on {stem}", kk.name); let a = compile(&bitcode, kk.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); @@ -4579,10 +4431,8 @@ fn mix_is_the_devices_fmix_on_every_profile() { link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); assert!(blend(&words) > 0, "{what}: FMix"); assert_eq!(fma(&words), 0, "{what}: a fused form"); - let half = kk.name.starts_with("half_"); - assert_eq!( + assert!( a.precision.contains(&PrecisionNote::NativeMix), - !(metal && !half), "{what}: {:?}", a.precision ); @@ -4592,10 +4442,9 @@ fn mix_is_the_devices_fmix_on_every_profile() { /// Class K: Metal's `half` functions answer the canonical `half` NaN `0x7E00` with and without /// fast-math flags (`nan_half`, `nan_half_fast`): `llvm.fmuladd`, `ldexp` (unlike `float`'s, which -/// returns the operand), and `sqrt`, which the device answers where the profile takes -/// `MetalCanonicalNans` and which are noted `PrecisionNote::NativeNanEncoding` elsewhere. `round` -/// and `fract` return a NaN operand itself on Metal, and `asin`'s domain error takes the operand's -/// sign: each the device's NaN on every profile, noted whatever the fact. None is selected. +/// returns the operand), and `sqrt`, noted `PrecisionNote::NativeNanEncoding`. `round` and `fract` +/// return a NaN operand itself on Metal, and `asin`'s domain error takes the operand's sign: each +/// the device's NaN on every profile, noted. None is selected. /// `round`'s zero is C99's (`-0` for `round(-0.3)`, where Metal answers `+0`), and `fract` of an /// infinity the device's `Fract`'s NaN (Metal's: `+0`, and `0x3BFF` with every flag). #[test] diff --git a/crates/metal2vulkan/src/tests/engine_bicubic.rs b/crates/metal2vulkan/src/tests/engine_bicubic.rs index ce23c6847..552e82e0f 100644 --- a/crates/metal2vulkan/src/tests/engine_bicubic.rs +++ b/crates/metal2vulkan/src/tests/engine_bicubic.rs @@ -21,7 +21,7 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; -use crate::device::profile::{DeviceProfile, FloatFunctions}; +use crate::device::profile::DeviceProfile; use crate::device::DevicePolicy; use crate::error::{Error, Feature, Needs, Unsupported}; use crate::lower::select::Plan; @@ -1261,11 +1261,9 @@ fn the_emulation_validates_on_every_committed_profile() { /// The ids the footprint's three `f32` operations produce in the entry point of a linked module /// `words`, and whether each is rounded on its own. The operations are the normalized coordinate /// times the extent (a product of an `OpConvertUToF` result), `y = 256 x` (a product by the -/// constant 256), and `r = y - floor(y)` (an `OpFSub` of a GLSL `Floor` result). A product -/// rounded on its own is `GLSL.std.450 Fma(a, b, -0.0)` where the profile's `float` functions are -/// Metal's (`metal`), and an `OpFMul` elsewhere; it and the subtraction are rounded on their own -/// when decorated `NoContraction`. -fn footprint_ops(words: &[u32], metal: bool) -> [Vec<(u32, bool)>; 3] { +/// constant 256), and `r = y - floor(y)` (an `OpFSub` of a GLSL `Floor` result). A product and +/// the subtraction are rounded on their own when decorated `NoContraction`. +fn footprint_ops(words: &[u32]) -> [Vec<(u32, bool)>; 3] { let insts: Vec<&[u32]> = { let (mut v, mut i) = (Vec::new(), 5); while i < words.len() { @@ -1322,27 +1320,9 @@ fn footprint_ops(words: &[u32], metal: bool) -> [Vec<(u32, bool)>; 3] { && glsl.contains(&w[3]) && w[4] == crate::spv::GlslStd450Op::Floor as u32 }); - let negative_zero = insts - .iter() - .filter(|w| { - op(w) == crate::spv::Op::Constant as u32 - && floats.contains(&w[1]) - && w[3] == 0x8000_0000 - }) - .map(|w| w[2]) - .collect::>(); - // The product of `a` and `b` rounded on its own, in the profile's form: `Fma(a, b, -0.0)` - // where its `float` functions are Metal's, an `OpFMul` elsewhere. + // The product of `a` and `b`: an `OpFMul`. let product = |w: &[u32], of: &[u32]| { - if metal { - op(w) == crate::spv::Op::ExtInst as u32 - && glsl.contains(&w[3]) - && w[4] == crate::spv::GlslStd450Op::Fma as u32 - && negative_zero.contains(&w[7]) - && (of.contains(&w[5]) || of.contains(&w[6])) - } else { - op(w) == crate::spv::Op::FMul as u32 && (of.contains(&w[3]) || of.contains(&w[4])) - } + op(w) == crate::spv::Op::FMul as u32 && (of.contains(&w[3]) || of.contains(&w[4])) }; let decorated: Vec = insts .iter() @@ -1368,9 +1348,8 @@ fn footprint_ops(words: &[u32], metal: bool) -> [Vec<(u32, bool)>; 3] { /// The footprint's `x = c n` (normalized coordinates only), `y = 256 x`, and `r = y - floor(y)` are /// each rounded on its own on every committed profile, one of each per plane axis, so no device -/// fuses them into the arithmetic after them: the products in the profile's form (`Fma(a, b, -0.0)` -/// where its `float` functions are Metal's, an `OpFMul` elsewhere), each decorated `NoContraction` -/// as the subtraction is. A re-bless of the golden table would not notice the form dropped; this +/// fuses them into the arithmetic after them: the products an `OpFMul`, each decorated +/// `NoContraction` as the subtraction is. A re-bless of the golden table would not notice the form dropped; this /// test does. #[test] fn the_footprint_arithmetic_is_no_contraction() { @@ -1386,8 +1365,7 @@ fn the_footprint_arithmetic_is_no_contraction() { let a = compile(&bc, "k", &p).unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); let (_, spv) = link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name} on {stem}: {e}")); - let metal = p.fields().float_functions == FloatFunctions::Metal; - let [cn, y, r] = footprint_ops(&spv, metal); + let [cn, y, r] = footprint_ops(&spv); for (what, ops, want) in [ ("c n", cn, products), ("256 x", y, 2), diff --git a/crates/metal2vulkan/src/tests/engine_cross_class.rs b/crates/metal2vulkan/src/tests/engine_cross_class.rs index d35393b86..de9ab7a15 100644 --- a/crates/metal2vulkan/src/tests/engine_cross_class.rs +++ b/crates/metal2vulkan/src/tests/engine_cross_class.rs @@ -343,9 +343,8 @@ fn run( /// Every read through a slot of another class gives the words the slot of the texture's own /// class gives, a `half` result their low 16 bits: Metal's rule. A `ushort` result of an integer /// texture is the low 16 bits too, of a float texture the `half` read's bits. Where the module -/// widens a `half` from its bits by the device and records `PrecisionNote::NativeNanEncoding` or -/// requires `VkProperty::MetalNanMoves` (both profiles here, which have `shaderFloat16`; -/// `device_nan_bits`), a `half` result's NaN is the device's widening's, which the interpreter is +/// widens a `half` from its bits by the device and records `PrecisionNote::NativeNanEncoding` +/// (both profiles here, which have `shaderFloat16`; `device_nan_bits`), a `half` result's NaN is the device's widening's, which the interpreter is /// not, so a NaN pattern need only come back a NaN. #[test] fn accesses_through_another_class_are_the_native_words() { diff --git a/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs b/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs index 88f397330..587423706 100644 --- a/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs +++ b/crates/metal2vulkan/src/tests/engine_extended_range/heap.rs @@ -770,8 +770,7 @@ declare void @air.write_texture_2d.v4f16(ptr addrspace(1), <2 x i32>, <4 x half> /// families of the textures its handles can name (`SpecKey::HeapNanFamilies`): on every committed /// profile with a heap, one clause for each family, as each stores the device's NaN (a 16-bit /// float format, a 32-bit one, a packed small float one, and a float format of none of those), -/// and no `VkProperty::MetalHalfTexelWrites`, `MetalNanMoves` or `MetalSmallFloatNans` is -/// required. A plan gives the key from the command's resident textures (`R16Float` 1, +/// and no `VkProperty::MetalHalfTexelWrites` or `MetalSmallFloatNans` is required. A plan gives the key from the command's resident textures (`R16Float` 1, /// `RGBA32Float` 2, `RG11B10Float` 4, `RGBA8Unorm` and `R32Uint` 0), and the note holds under the /// plan's values exactly where a resident texture is of a family of a clause. #[test] @@ -819,7 +818,6 @@ fn a_heap_half_write_s_nan_note_follows_the_families_its_command_can_name() { assert_eq!(noted(&a.specialized), 15, "{stem}: every family"); for property in [ VkProperty::MetalHalfTexelWrites, - VkProperty::MetalNanMoves, VkProperty::MetalSmallFloatNans, ] { assert!( diff --git a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs index 1c862822b..5c1d96b82 100644 --- a/crates/metal2vulkan/src/tests/engine_float_call_notes.rs +++ b/crates/metal2vulkan/src/tests/engine_float_call_notes.rs @@ -3,20 +3,17 @@ //! product computes as a near-equivalent of Metal's, so the two must never diverge from what a //! compile records. //! -//! Every float function of the `air` math table, on `float`, `half`, and `bfloat`, called with -//! and without the `fast_` prefix and with and without fast-math flags, and every float binary +//! Every float function of the `air` math table, on `float`, `half`, and `bfloat`, called with and +//! without the `fast_` prefix and with and without fast-math flags, and every float binary //! operator, is compiled alone (its operands loaded from a buffer and its result stored) on one -//! committed profile per class of the facts the notes read: the `float` fused multiply-add route, -//! whether the `float` functions are Metal's, whether the device reads `f32` denormals as Metal -//! does, and whether its moves of a NaN are Metal's (`nan::moves_answered`). Each artifact's notes are exactly what the exported function answers for that call -//! in that entry's math mode. The loads and stores around it record none, but a `half` kernel's -//! widening and rounding, which the module records once by the profile's own form: its rounding's -//! note (`narrow::native_rounding`), and under the float controls `NativeHalfConversion` where the -//! module rounds through the conversion pair (`narrow::rounds_by_conversion`), which the test sets -//! aside, and a module's widening of a -//! `half` from its bits or narrowing of one to them by the device (every profile), whose NaN's -//! bits are the device's (`narrow::widens_bits`, `narrow::encodes_bits`, `NativeNanEncoding`) but -//! where the device's moves of a NaN are measured to be Metal's (`narrow::moves_unfolded`), and +//! committed profile per class of the facts the notes read: the `float` fused multiply-add route. +//! Each artifact's notes are exactly what the exported function answers for that call. The loads +//! and stores around it record none, but a `half` kernel's widening and rounding, which the module +//! records once by the profile's own form: its rounding's note (`narrow::native_rounding`), and +//! under the float controls `NativeHalfConversion` where the module rounds through the conversion +//! pair (`narrow::rounds_by_conversion`), which the test sets aside, and a module's widening of a +//! `half` from its bits or narrowing of one to them by the device (every profile), whose NaN's bits +//! are the device's (`narrow::widens_bits`, `narrow::encodes_bits`, `NativeNanEncoding`), and //! without `shaderFloat16` its denormals too (`UnpackHalf2x16`, `PackHalf2x16`, //! `NativeHalfConversion`), which the test adds to the operation's notes. //! @@ -24,13 +21,10 @@ use crate::air::intrinsics::{AirIntrinsic, Elem, Math, NumTy, Operand}; use crate::air::ir::{BinOp, FastMath}; -use crate::device::profile::{FloatFunctions, NanEncoding}; use crate::device::DeviceProfile; -use crate::error::DriverDeviation; use crate::lower::arith::fma::{self, Route}; -use crate::lower::arith::libm::Mode; -use crate::lower::arith::{denormal, float_binop_notes, float_call_notes, nan, narrow, FloatFmt}; -use crate::pipeline::artifact::{EntryMath, PrecisionNote}; +use crate::lower::arith::{float_binop_notes, float_call_notes, narrow, FloatFmt}; +use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::testing::{ compile, llvm_assemble, meter, typed_module, AssembleError, Scratch, }; @@ -288,19 +282,12 @@ fn assemble(token: &str, chunk: usize, text: &str) -> Option> { } } -/// What the notes of a float operation read of a profile: its `float` fused multiply-add route, -/// whether its `float` functions are Metal's, whether the device reads `f32` denormals as Metal -/// does, and whether its moves of a NaN are Metal's. -type NoteClass = (Route, bool, bool, bool); +/// What the notes of a float operation read of a profile: its `float` fused multiply-add route. +type NoteClass = Route; /// The note class of profile `p`. fn note_class(p: &DeviceProfile) -> NoteClass { - ( - fma::float_route(p), - p.fields().float_functions == FloatFunctions::Metal, - denormal::device_flushes(p), - nan::moves_answered(p), - ) + fma::float_route(p) } /// One committed profile per note class (the first by name). @@ -311,7 +298,7 @@ fn one_profile_per_class() -> BTreeMap { { out.entry(note_class(&p)).or_insert((stem, p)); } - let routes: BTreeSet = out.keys().map(|(route, _, _, _)| *route).collect(); + let routes: BTreeSet = out.keys().copied().collect(); assert_eq!( routes, BTreeSet::from([Route::Khr, Route::Native]), @@ -320,21 +307,6 @@ fn one_profile_per_class() -> BTreeMap { out } -/// The mode of the `float` functions of an entry on `p` whose one float operation carries flags -/// `fmf` (`None` where the profile's are the device's): precise where the operation lacks one of -/// `nnan`, `ninf`, and `nsz` and the profile declares `SignedZeroInfNanPreserve` for `f32`, the -/// container of every format here (`arith::fp_env`, `libm::module_mode`). -fn entry_mode(p: &DeviceProfile, fmf: FastMath) -> Option { - let relaxed = FastMath::NNAN.union(FastMath::NINF).union(FastMath::NSZ); - let preserves = - !fmf.contains(relaxed) && p.fields().float_controls.f32.signed_zero_inf_nan_preserve; - (p.fields().float_functions == FloatFunctions::Metal).then_some(if preserves { - Mode::Precise - } else { - Mode::Fast - }) -} - #[test] fn exported_float_notes_are_the_ones_a_compile_records() { let profiles = one_profile_per_class(); @@ -354,10 +326,9 @@ fn exported_float_notes_are_the_ones_a_compile_records() { Op::Call { name, math, fmf } => { let notes = float_call_notes(*math, *fmf, p); assert!(notes.is_some(), "{what}: {name} is not a float function"); - notes.map(|notes| notes.in_entry(entry_mode(p, *fmf))) + notes } - Op::Binop { op, fmt, fmf } => float_binop_notes(*op, *fmt, *fmf, p) - .map(|notes| notes.in_entry(entry_mode(p, *fmf))), + Op::Binop { op, fmt, fmf } => float_binop_notes(*op, *fmt, *fmf, p), }; let mut want = want.unwrap_or_else(|| panic!("{what}: no exported notes")); let a = @@ -381,12 +352,8 @@ fn exported_float_notes_are_the_ones_a_compile_records() { let crosses = narrow::widens_bits(&m, &mut meter()) .and_then(|w| Ok(w || narrow::encodes_bits(&m, &mut meter())?)) .unwrap_or_else(|e| panic!("{what}: {e:?}")); - // Its NaN's bits Metal's where the device's moves are measured to be and - // the module moves its `half` values only so. - let moved = nan::moves_answered(p) - && !narrow::moves_unfolded(&m, &mut meter()) - .unwrap_or_else(|e| panic!("{what}: {e:?}")); - if crosses && !moved { + // Its NaN's bits the device's. + if crosses { want.insert(PrecisionNote::NativeNanEncoding); } if crosses && form == crate::spirv::builder::QuantizeForm::Device { @@ -404,96 +371,81 @@ fn exported_float_notes_are_the_ones_a_compile_records() { } /// The binary operators' notes beside the functions': a remainder and a division are the device's -/// arithmetic, and a `float` operator leaves the device its denormals where the profile does not -/// take `DriverDeviation::MetalFloatDenormals`, and a remainder and a division on every profile. +/// arithmetic, and a `float` operator leaves the device its denormals. /// Metal's precise division (an `fdiv` on `float` without `arcp`, or on `half` under every flag /// set) is the device's `OpFDiv`, noted `NativeDivision`. A `float` remainder without every flag is /// the device's `OpFRem`, and with every flag Metal's `fast::fmod`, whose notes it records. Metal's /// fast division (an `fdiv` on `float` with `arcp`) is the device's `OpFDiv` too, and records the -/// device's arithmetic, its division and its denormals, but where the profile's `float` functions -/// are Metal's, in an entry Metal compiles with fast math, whose quotient is Metal's own. Metal -/// answers its canonical NaN for a `float` or `half` `+ - * /` and a `float` remainder; each leaves -/// that NaN to the device, noted `NativeNanEncoding` where the profile is not measured to answer -/// Metal's (`NanEncoding::Native`), a fast `float` division but in Metal's own fast-math entry. +/// device's arithmetic, its division and its denormals. Metal answers its canonical NaN for a +/// `float` or `half` `+ - * /` and a `float` remainder; each leaves that NaN to the device, noted +/// `NativeNanEncoding`. /// No operator records `DeviceNanEncoding`. #[test] fn a_float_division_is_the_devices_arithmetic_unless_it_is_metals_precise_one() { - for (class, (stem, p)) in one_profile_per_class() { - let (_, metal_functions, _, _) = class; - let flushes = p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals); - let native_nans = nan::encoding(&p) == NanEncoding::Native; + for (stem, p) in one_profile_per_class().into_values() { for (_, _, _, fmt) in ELEMS { for op in BinOp::ALL { for fmf in [FastMath::NONE, FastMath::ARCP, every_flag()] { let notes = float_binop_notes(op, fmt, fmf, &p); assert_eq!(notes.is_some(), op.is_float(), "{op:?}"); let Some(notes) = notes else { continue }; - for mode in [Mode::Fast, Mode::Precise] { - let metal = metal_functions.then_some(mode); - let notes = notes.clone().in_entry(metal); - let single = fmt == FloatFmt::F32; - let precise = op == BinOp::FDiv - && (fmt == FloatFmt::Half || (single && !fmf.contains(FastMath::ARCP))); - let what = format!("{op:?} on {fmt:?} under {fmf:?} on {stem}, {metal:?}"); - assert!(!notes.contains(&PrecisionNote::DeviceNanEncoding), "{what}"); - if precise { - let want: BTreeSet<_> = [PrecisionNote::NativeDivision] - .into_iter() - .chain(single.then_some(PrecisionNote::DeviceDenormals)) - .chain(native_nans.then_some(PrecisionNote::NativeNanEncoding)) - .collect(); - assert_eq!(notes, want, "{what}"); - continue; - } - if op == BinOp::FRem && single && fmf == every_flag() { - let Some(AirIntrinsic::Math(fmod)) = - AirIntrinsic::parse("air.fast_fmod.f32") - else { - panic!("air.fast_fmod.f32 does not parse"); - }; - let want = float_call_notes(fmod, fmf, &p) - .expect("fast fmod is a float function") - .in_entry(metal); - assert_eq!(notes, want, "{what}"); - continue; - } - if op == BinOp::FDiv && single { - let want = if metal == Some(Mode::Fast) { - BTreeSet::new() - } else { - [ - PrecisionNote::DeviceArithmetic, - PrecisionNote::NativeDivision, - PrecisionNote::DeviceDenormals, - ] - .into_iter() - .chain(native_nans.then_some(PrecisionNote::NativeNanEncoding)) - .collect() - }; - assert_eq!(notes, want, "{what}"); - continue; - } - assert_eq!( - notes.contains(&PrecisionNote::DeviceArithmetic), - matches!(op, BinOp::FDiv | BinOp::FRem), - "{what}" - ); - // Metal's canonical NaN: a `float` or `half` `+ - *`, and a `float` - // remainder. - let canonical = (matches!(fmt, FloatFmt::F32 | FloatFmt::Half) - && matches!(op, BinOp::FAdd | BinOp::FSub | BinOp::FMul)) - || (op == BinOp::FRem && single); - assert_eq!( - notes.contains(&PrecisionNote::NativeNanEncoding), - native_nans && canonical, - "{what}" - ); - assert_eq!( - notes.contains(&PrecisionNote::DeviceDenormals), - single && (op == BinOp::FRem || !flushes), - "{what}" - ); + let single = fmt == FloatFmt::F32; + let precise = op == BinOp::FDiv + && (fmt == FloatFmt::Half || (single && !fmf.contains(FastMath::ARCP))); + let what = format!("{op:?} on {fmt:?} under {fmf:?} on {stem}"); + assert!(!notes.contains(&PrecisionNote::DeviceNanEncoding), "{what}"); + if precise { + let want: BTreeSet<_> = [PrecisionNote::NativeDivision] + .into_iter() + .chain(single.then_some(PrecisionNote::DeviceDenormals)) + .chain([PrecisionNote::NativeNanEncoding]) + .collect(); + assert_eq!(notes, want, "{what}"); + continue; } + if op == BinOp::FRem && single && fmf == every_flag() { + let Some(AirIntrinsic::Math(fmod)) = + AirIntrinsic::parse("air.fast_fmod.f32") + else { + panic!("air.fast_fmod.f32 does not parse"); + }; + let want = + float_call_notes(fmod, fmf, &p).expect("fast fmod is a float function"); + assert_eq!(notes, want, "{what}"); + continue; + } + if op == BinOp::FDiv && single { + let want: BTreeSet<_> = [ + PrecisionNote::DeviceArithmetic, + PrecisionNote::NativeDivision, + PrecisionNote::DeviceDenormals, + ] + .into_iter() + .chain([PrecisionNote::NativeNanEncoding]) + .collect(); + assert_eq!(notes, want, "{what}"); + continue; + } + assert_eq!( + notes.contains(&PrecisionNote::DeviceArithmetic), + matches!(op, BinOp::FDiv | BinOp::FRem), + "{what}" + ); + // Metal's canonical NaN: a `float` or `half` `+ - *`, and a `float` + // remainder. + let canonical = (matches!(fmt, FloatFmt::F32 | FloatFmt::Half) + && matches!(op, BinOp::FAdd | BinOp::FSub | BinOp::FMul)) + || (op == BinOp::FRem && single); + assert_eq!( + notes.contains(&PrecisionNote::NativeNanEncoding), + canonical, + "{what}" + ); + assert_eq!( + notes.contains(&PrecisionNote::DeviceDenormals), + single, + "{what}" + ); } } } @@ -506,7 +458,7 @@ fn a_float_division_is_the_devices_arithmetic_unless_it_is_metals_precise_one() /// either mode, with or without flags; a `half` one records `NativeTranscendentals` for its zero /// remainder's sign, its `float` remainder's, where Metal's `half` answers `+0` /// (`FloatFn::half_zero_of_float`). Precise `sqrt` and `rsqrt`, which Metal documents correctly rounded, are the -/// device's `Sqrt` and `InverseSqrt`: off Metal's own functions they record the device's precision +/// device's `Sqrt` and `InverseSqrt`: they record the device's precision /// (`NativeTranscendentals`), as precise `exp`, which Apple bounds by ulps, does. #[test] fn precise_fmod_records_no_precision_note_and_the_roots_the_devices() { @@ -519,43 +471,34 @@ fn precise_fmod_records_no_precision_note_and_the_roots_the_devices() { Some(AirIntrinsic::Math(call)) => call, _ => panic!("{name} is a math call"), }; - for ((_, metal_functions, _, _), (stem, p)) in one_profile_per_class() { + for (stem, p) in one_profile_per_class().into_values() { for name in ["air.fmod.f32", "air.fmod.f16"] { for fmf in [FastMath::NONE, every_flag()] { - for math in [EntryMath::Fast, EntryMath::Precise] { - let notes = PrecisionNote::of_math_call(parse(name), fmf, &p, math) - .unwrap_or_else(|| panic!("{name} is a float function")); - let half_zero = name.ends_with("f16"); - assert!( - function_notes.iter().all(|note| { - notes.contains(note) - == (half_zero && *note == PrecisionNote::NativeTranscendentals) - }), - "{name} under {fmf:?} on {stem}, {math:?}: {notes:?}" - ); - } - } - } - if !metal_functions { - for name in [ - "air.sqrt.f32", - "air.rsqrt.f32", - "air.sqrt.f16", - "air.rsqrt.f16", - "air.exp.f32", - ] { - let notes = PrecisionNote::of_math_call( - parse(name), - FastMath::NONE, - &p, - EntryMath::Precise, - ) - .unwrap_or_else(|| panic!("{name} is a float function")); + let notes = PrecisionNote::of_math_call(parse(name), fmf, &p) + .unwrap_or_else(|| panic!("{name} is a float function")); + let half_zero = name.ends_with("f16"); assert!( - notes.contains(&PrecisionNote::NativeTranscendentals), - "{name} on {stem}: {notes:?}" + function_notes.iter().all(|note| { + notes.contains(note) + == (half_zero && *note == PrecisionNote::NativeTranscendentals) + }), + "{name} under {fmf:?} on {stem}: {notes:?}" ); } } + for name in [ + "air.sqrt.f32", + "air.rsqrt.f32", + "air.sqrt.f16", + "air.rsqrt.f16", + "air.exp.f32", + ] { + let notes = PrecisionNote::of_math_call(parse(name), FastMath::NONE, &p) + .unwrap_or_else(|| panic!("{name} is a float function")); + assert!( + notes.contains(&PrecisionNote::NativeTranscendentals), + "{name} on {stem}: {notes:?}" + ); + } } } diff --git a/crates/metal2vulkan/src/tests/engine_metal_denormals.rs b/crates/metal2vulkan/src/tests/engine_metal_denormals.rs index 80086784a..b9f98b22d 100644 --- a/crates/metal2vulkan/src/tests/engine_metal_denormals.rs +++ b/crates/metal2vulkan/src/tests/engine_metal_denormals.rs @@ -6,12 +6,10 @@ //! //! Each kernel loops over its rows (three operand words a row in `[[buffer(0)]]`) and stores one //! answer word a row in `[[buffer(1)]]`. The CPU SPIR-V interpreter keeps denormals, as a device -//! without `DriverDeviation::MetalFloatDenormals` may, so on each such committed profile (one per -//! fused multiply-add route) an entry that records no `PrecisionNote::DeviceDenormals` must answer -//! every row as Metal did. `llvm-as` assembles the module; without it the tests skip visibly. +//! may, so on each committed profile (one per fused multiply-add route) an entry that records no +//! `PrecisionNote::DeviceDenormals` must answer every row as Metal did. `llvm-as` assembles the module; without it the tests skip visibly. use crate::device::{DevicePolicy, DeviceProfile}; -use crate::error::DriverDeviation; use crate::lower::arith::fma; use crate::pipeline::artifact::PrecisionNote; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; @@ -257,14 +255,13 @@ fn interpret(bc: &[u8], name: &str, p: &DeviceProfile, rows: &[([u32; 3], [u32; .collect() } -/// The committed profiles under `policy` whose device may keep denormals (no -/// `DriverDeviation::MetalFloatDenormals`), one per fused multiply-add route. +/// The committed profiles under `policy`, one per fused multiply-add route: each device may keep +/// denormals. fn profiles(policy: DevicePolicy) -> Vec<(String, DeviceProfile)> { let mut seen = BTreeSet::new(); committed_profiles_with(policy) .expect("profiles") .into_iter() - .filter(|(_, p)| !p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals)) .filter(|(_, p)| seen.insert(fma::float_route(p))) .collect() } diff --git a/crates/metal2vulkan/src/tests/engine_metal_math.rs b/crates/metal2vulkan/src/tests/engine_metal_math.rs index bcd168a6f..3ae39a6ce 100644 --- a/crates/metal2vulkan/src/tests/engine_metal_math.rs +++ b/crates/metal2vulkan/src/tests/engine_metal_math.rs @@ -28,7 +28,6 @@ //! `llvm-as` assembles the modules; without it the tests skip visibly. use crate::air::{self, SpecRequest}; -use crate::device::profile::FloatFunctions; use crate::lower::emit::emit_module; use crate::lower::select::{select, LowerInputs}; use crate::lower::simd::WidestPin; @@ -62,12 +61,8 @@ struct Kernel { has: &'static [u32], lacks: &'static [u32], /// Whether the module takes the device's instruction for a function Metal defines otherwise, - /// recording `NativeTranscendentals` wherever the device's functions are not Metal's own. + /// recording `NativeTranscendentals`. native: bool, - /// Whether the instruction on MoltenVK is not Metal's own function for the call - /// (`DeviceTranscendentals` there): MSL's precise `tanh` for `fast::tanh`, its `float` one - /// rounded for a `half` one. - off_metal: bool, /// The stored word on the interpreter, when it models the kernel. want: Option, } @@ -79,7 +74,6 @@ const KERNELS: [Kernel; 7] = [ has: &[TANH], lacks: &[EXP2], native: true, - off_metal: true, want: None, }, Kernel { @@ -88,7 +82,6 @@ const KERNELS: [Kernel; 7] = [ has: &[TANH], lacks: &[EXP2], native: false, - off_metal: false, want: None, }, Kernel { @@ -97,7 +90,6 @@ const KERNELS: [Kernel; 7] = [ has: &[TANH], lacks: &[EXP2], native: true, - off_metal: true, want: None, }, Kernel { @@ -106,7 +98,6 @@ const KERNELS: [Kernel; 7] = [ has: &[FSIGN], lacks: &[], native: true, - off_metal: false, want: Some(0xBF80_0000), }, Kernel { @@ -115,7 +106,6 @@ const KERNELS: [Kernel; 7] = [ has: &[FSIGN], lacks: &[], native: true, - off_metal: false, want: Some(0xBF80_0000), }, Kernel { @@ -124,7 +114,6 @@ const KERNELS: [Kernel; 7] = [ has: &[SIN, ROUND_EVEN], lacks: &[], native: false, - off_metal: false, want: None, }, Kernel { @@ -133,7 +122,6 @@ const KERNELS: [Kernel; 7] = [ has: &[SIN, ROUND_EVEN], lacks: &[], native: false, - off_metal: false, want: None, }, ]; @@ -259,21 +247,16 @@ fn metal_math_variants_select_their_forms() { "{what}: GLSL.std.450 {i} present ({ext:?})" ); } - let metal = p.fields().float_functions == FloatFunctions::Metal; assert!(!div, "{what}: OpFDiv"); - // The device's instruction: noted `NativeTranscendentals` wherever the device's - // functions are not Metal's own. On MoltenVK `sign` is MSL's own; `fast::tanh` is - // MSL's precise `tanh`, and a `half` `tanh` MSL's `float` one rounded to `half`. + // The device's instruction: noted `NativeTranscendentals`. if k.native { - assert_eq!( + assert!( a.precision.contains(&PrecisionNote::NativeTranscendentals), - !metal, "{what}: {:?}", a.precision ); - assert_eq!( - a.precision.contains(&PrecisionNote::DeviceTranscendentals), - metal && k.off_metal, + assert!( + !a.precision.contains(&PrecisionNote::DeviceTranscendentals), "{what}: {:?}", a.precision ); diff --git a/crates/metal2vulkan/src/tests/engine_metal_routines.rs b/crates/metal2vulkan/src/tests/engine_metal_routines.rs index adbcbc855..c5247a58d 100644 --- a/crates/metal2vulkan/src/tests/engine_metal_routines.rs +++ b/crates/metal2vulkan/src/tests/engine_metal_routines.rs @@ -420,8 +420,7 @@ fn half_nan(bits: u32) -> bool { /// infinities and NaNs returned with their bits and exponent 0, `ilogb` `INT_MAX` for an infinity /// and `INT_MIN` for a NaN, lane by lane. The one exception: a module that records /// `NativeNanEncoding` answers a `half` NaN's mantissa with a NaN of the device's bits; every -/// `half` kernel records it, on a profile whose moves of a NaN are measured to be Metal's -/// (`DriverDeviation::MetalNanMoves`) too, since the routines read the widened value's bits. +/// `half` kernel records it, since the routines read the widened value's bits. #[test] fn frexp_and_ilogb_answer_as_metals_routines() { let Some(bc) = assemble() else { @@ -434,8 +433,7 @@ fn frexp_and_ilogb_answer_as_metals_routines() { let a = compile(&bc, k.name, &p).unwrap_or_else(|e| panic!("{what}: {e:?}")); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); let device_nans = a.precision.contains(&PrecisionNote::NativeNanEncoding); - // The routines read a `half`'s widened bits, which the device's measured moves of a - // NaN do not cover (`narrow::moves_unfolded`): noted on every profile. + // The routines read a `half`'s widened bits: noted on every profile. assert!(!k.half || device_nans, "{what}: {:?}", a.precision); let got = interpret(&bc, k, &p, &what); for (i, &(x, mantissa, exponent, ilogb)) in k.inputs().iter().enumerate() { diff --git a/crates/metal2vulkan/src/tests/engine_native_half.rs b/crates/metal2vulkan/src/tests/engine_native_half.rs index 71ca56ff7..3fa591c8e 100644 --- a/crates/metal2vulkan/src/tests/engine_native_half.rs +++ b/crates/metal2vulkan/src/tests/engine_native_half.rs @@ -193,8 +193,7 @@ fn half_rounding_is_the_devices_on_every_profile() { } /// On lavapipe and MoltenVK (`shaderFloat16`, no `DenormPreserve` for 16 bits) each kernel rounds -/// its `half` through the conversion, records `NativeHalfConversion` and requires no -/// `VkProperty::MetalHalfConversion`; on a profile without `shaderFloat16` it quantizes and +/// its `half` through the conversion and records `NativeHalfConversion`; on a profile without `shaderFloat16` it quantizes and /// records `NativeHalfQuantize`; RADV takes the controlled conversion and holds `half` at 16 bits /// under those controls: its sum, between exact conversions, records nothing, and its narrowing /// widened back, a conversion pair a driver's compiler may fold, records `NativeHalfConversion`. @@ -202,7 +201,7 @@ fn half_rounding_is_the_devices_on_every_profile() { /// whose conversion and quantize round to nearest even, the native modules answer Metal's /// `half(float)`, but for the quantize's zero below the smallest normal half. #[test] -fn native_half_rounding_records_its_kind_and_requires_no_fact() { +fn native_half_rounding_records_its_kind() { let Some(bc) = bitcode() else { return; }; @@ -225,12 +224,6 @@ fn native_half_rounding_records_its_kind_and_requires_no_fact() { link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); let noted: Vec<_> = natives.iter().filter(|n| a.precision.contains(n)).collect(); assert_eq!(noted, note.iter().collect::>(), "{what}"); - assert!( - !a.requirements - .properties - .contains(&VkProperty::MetalHalfConversion), - "{what}" - ); } } // Metal's `half(float)` on the interpreter's nearest-even conversion and quantize: a tie to @@ -392,7 +385,7 @@ fn decodes(m: &TypedModule) -> (usize, usize) { /// where the device flushes 16-bit denormals, a denormal); on NVIDIA, under the float controls (its /// driver folds only the conversion's round trip, `narrow::half_controls`), `NativeNanEncoding` /// alone; on the floor (no `shaderFloat16`) it is `UnpackHalf2x16` of each word, recording both -/// notes. None requires `VkProperty::MetalHalfArithmetic`. A `half4` widens as one vector (two +/// notes. A `half4` widens as one vector (two /// words unpacked and shuffled where the device unpacks). Each module passes L3 and answers the /// `half`s' values on the interpreter (whose widening is exact). #[test] @@ -445,13 +438,6 @@ fn a_half_decode_is_the_devices_widening_inside_loops_and_out() { "{what}: {:?}", a.precision ); - assert!( - !a.requirements - .properties - .contains(&VkProperty::MetalHalfArithmetic), - "{what}: {:?}", - a.requirements.properties - ); let res = Resources { buffers: vec![Buffer { slot: Some(ResourceSlot { @@ -1006,11 +992,10 @@ fn half_load_module() -> String { /// controls (ANV, RADV, the RTX 50 series) its entry declares them (`narrow::controlled_modes`, so /// a half denormal widens exactly) and it records no other note; elsewhere (lavapipe and MoltenVK: /// the device's conversion, no float controls) it records `NativeHalfConversion`, whose bound holds -/// a denormal the device flushes. None requires `VkProperty::MetalHalfArithmetic` or -/// `VkProperty::MetalNanMoves`. Without it (Pascal, +/// a denormal the device flushes. Without it (Pascal, /// the LunarG baseline, SwiftShader, the floor) the widening is one `UnpackHalf2x16` of the word, /// a 16-bit unit's zero extension where the profile has 16-bit storage, with no 16-bit float type, -/// recording `NativeHalfConversion` too and requiring no fact. Each passes L3; on the interpreter +/// recording `NativeHalfConversion` too. Each passes L3; on the interpreter /// a half denormal, a zero's sign, `65504` and an infinity read as their values, and a NaN as a /// NaN; the `half` stored back unchanged keeps its bits, NaNs included. #[test] @@ -1029,21 +1014,12 @@ fn a_half_read_from_memory_is_the_devices_widening_on_every_profile() { link_and_validate(&a, p).unwrap_or_else(|e| panic!("{what}: L3: {e}")); let r = rounding(&a.module.words); assert_eq!(r.narrowings, 0, "{what}: {r:?}"); - let fact = a - .requirements - .properties - .contains(&VkProperty::MetalHalfArithmetic); let nan = a.precision.contains(&PrecisionNote::NativeNanEncoding); - let moved = a - .requirements - .properties - .contains(&VkProperty::MetalNanMoves); let conversion = a.precision.contains(&PrecisionNote::NativeHalfConversion); - assert!(!moved, "{what}: {:?}", a.requirements.properties); match form { QuantizeForm::Device => { assert_eq!((r.widenings, r.unpacks), (0, 1), "{what}: {r:?}"); - assert!(nan && conversion && !fact, "{what}: {:?}", a.precision); + assert!(nan && conversion, "{what}: {:?}", a.precision); } QuantizeForm::Controlled => { assert_eq!((r.widenings, r.unpacks), (1, 0), "{what}: {r:?}"); @@ -1053,11 +1029,11 @@ fn a_half_read_from_memory_is_the_devices_widening_on_every_profile() { "{what}: {mode:?} {r:?}" ); } - assert!(nan && !conversion && !fact, "{what}: {:?}", a.precision); + assert!(nan && !conversion, "{what}: {:?}", a.precision); } QuantizeForm::Converted => { assert_eq!((r.widenings, r.unpacks), (1, 0), "{what}: {r:?}"); - assert!(nan && conversion && !fact, "{what}: {:?}", a.precision); + assert!(nan && conversion, "{what}: {:?}", a.precision); for mode in [M::RoundingModeRTE, M::DenormPreserve] { assert!( !r.modes.contains(&(mode as u32, 16)), @@ -1169,7 +1145,7 @@ fn f16_arithmetic(words: &[u32]) -> Vec<(crate::spv::Op, bool)> { /// profiles): under fast math its one 16-bit instruction is undecorated, a product a plain /// `OpFMul`; under `contract` alone or no flag it is kept apart, decorated `NoContraction`, a /// product `Fma(a, b, -0.0)`. A lone operation has no neighbour to be rewritten with, so the module -/// notes nothing, as for `float`, and requires no `VkProperty::MetalHalfArithmetic`. On the +/// notes nothing, as for `float`. On the /// interpreter each answers the rounded result either way. #[test] fn half_arithmetic_on_the_device_takes_the_airs_contraction() { @@ -1204,13 +1180,6 @@ fn half_arithmetic_on_the_device_takes_the_airs_contraction() { "{what}: {:?}", a.precision ); - assert!( - !a.requirements - .properties - .contains(&VkProperty::MetalHalfArithmetic), - "{what}: {:?}", - a.requirements.properties - ); } let run = |name: &str, x: [f32; 2]| interpret(&bc, name, p, x); let (x, y) = (1.0 + 2f32.powi(-10), 2f32.powi(-11)); diff --git a/crates/metal2vulkan/src/tests/engine_native_maths.rs b/crates/metal2vulkan/src/tests/engine_native_maths.rs index 3e4cb746a..b7cbd4c85 100644 --- a/crates/metal2vulkan/src/tests/engine_native_maths.rs +++ b/crates/metal2vulkan/src/tests/engine_native_maths.rs @@ -12,7 +12,7 @@ //! `llvm-as` assembles the module; without it the tests skip visibly. use crate::air::{self, SpecRequest}; -use crate::device::profile::{DeviceProfile, FloatFunctions}; +use crate::device::profile::DeviceProfile; use crate::device::DevicePolicy; use crate::lower::emit::emit_module; use crate::lower::select::{select, LowerInputs}; @@ -24,7 +24,6 @@ use crate::pipeline::testing::{ }; use crate::pipeline::PrecisionNote; use crate::spirv::interp::{run, Buffer, Config, Resources}; -use crate::spirv::testing::committed_profiles_with; const OP_FUNCTION: u32 = 54; @@ -211,16 +210,6 @@ fn ulps(got: f32, want: f64) -> f64 { (f64::from(got) - want).abs() / ulp } -/// On every committed profile the maths functions are the device's. -#[test] -fn the_maths_functions_are_the_device_s() { - let profiles = committed_profiles_with(DevicePolicy::default()).expect("profiles"); - assert!(profiles.len() >= 10, "{} profiles", profiles.len()); - for (stem, p) in &profiles { - assert_eq!(p.fields().float_functions, FloatFunctions::Native, "{stem}"); - } -} - /// On lavapipe each kernel records its kind, passes L3, and is its entry alone (no routine). #[test] fn each_kernel_records_its_kind() { diff --git a/crates/metal2vulkan/src/tests/engine_opencl_mode.rs b/crates/metal2vulkan/src/tests/engine_opencl_mode.rs index 2eba84c3a..ada2b1bb1 100644 --- a/crates/metal2vulkan/src/tests/engine_opencl_mode.rs +++ b/crates/metal2vulkan/src/tests/engine_opencl_mode.rs @@ -925,12 +925,9 @@ attributes #4 = { nounwind willreturn memory(argmem: write) }\n\ /// A `float` narrowed to a stored `half` (`vstore_half_rtz`, and a plain `fptrunc` stored) is the /// device's conversion, whose NaN's bits are its own (NVIDIA's 0x7fff where Metal stores 0x7e00): /// on every committed profile the kernel's module records `NativeNanEncoding`, which the runtime -/// announces as `native-nan-encoding`, but where the device's narrowing is measured to move a NaN -/// as Metal's (`DriverDeviation::MetalNanMoves`), which the module then requires. +/// announces as `native-nan-encoding`. #[test] fn an_opencl_mode_half_store_records_the_devices_nan_encoding() { - use crate::device::requirements::VkProperty; - use crate::error::DriverDeviation; use crate::pipeline::PrecisionNote; let b = Budget::standard(); let mut checked = 0; @@ -948,22 +945,10 @@ fn an_opencl_mode_half_store_records_the_devices_nan_encoding() { Err(e) => panic!("{what}: {e}"), }; let notes = &p.stage.precision_notes; - match dev - .profile() - .takes_driver_deviation(DriverDeviation::MetalNanMoves) - { - true => assert!( - notes.contains(&PrecisionNote::NativeNanEncoding) - || p.requirements - .properties - .contains(&VkProperty::MetalNanMoves), - "{what}: {notes:?}" - ), - false => assert!( - notes.contains(&PrecisionNote::NativeNanEncoding), - "{what}: {notes:?}" - ), - } + assert!( + notes.contains(&PrecisionNote::NativeNanEncoding), + "{what}: {notes:?}" + ); checked += 1; } } diff --git a/crates/metal2vulkan/src/tests/engine_rate_map.rs b/crates/metal2vulkan/src/tests/engine_rate_map.rs index bc7c080f8..1430e486b 100644 --- a/crates/metal2vulkan/src/tests/engine_rate_map.rs +++ b/crates/metal2vulkan/src/tests/engine_rate_map.rs @@ -1,10 +1,8 @@ //! Rasterization-rate maps end to end (Apple's layout): `rasterization_rate_map_decoder`'s `float2` //! maps compile to Apple's GPU decoder of Metal's parameter data on every tested profile, pass L3, //! and record no `RasterizationRateMap` note (the decoder is Apple's arithmetic over Metal's -//! bytes). Its `float` arithmetic is the device's: Metal's on a device measured to read `float` -//! denormals as Metal does (`DriverDeviation::MetalFloatDenormals`, MoltenVK's), the device's own -//! denormals elsewhere, noted `DeviceDenormals`, and its `NaN` the device's, noted -//! `NativeNanEncoding` where the profile is not measured to answer Metal's. On the CPU interpreter, +//! bytes). Its `float` arithmetic is the device's: its denormals the device's own, noted +//! `DeviceDenormals`, and its `NaN` the device's, noted `NativeNanEncoding`. On the CPU interpreter, //! which keeps `float` denormals as lavapipe does, the module computes the shader decoder's //! arithmetic over the same bytes with denormals kept ([`kept`]): bit for bit, the sign of a zero //! included (a `NaN` is any `NaN`), in both directions, for every layer (a layer past the map's @@ -27,10 +25,8 @@ use std::sync::atomic::{AtomicU64, Ordering}; use crate::air::canon::rate_map_data as format; use crate::bind::{RasterizationRateMap, RateMapAxis, RateMapDescriptor, RateMapLayerDescriptor}; -use crate::device::profile::NanEncoding; use crate::device::requirements::VkFeature; use crate::device::{Device, DeviceDescription, DevicePolicy, DeviceProfile}; -use crate::lower::arith::{denormal, nan}; use crate::lower::select::Plan; use crate::pipeline::interface::PushLoc; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; @@ -273,8 +269,7 @@ fn maps() -> Vec<(&'static str, RasterizationRateMap)> { /// Both maps of every layer, as the shader decoder's arithmetic computes them with the device's /// denormals ([`kept`]), on every profile, with the notes of the device's arithmetic: no -/// `RasterizationRateMap`, `DeviceDenormals` where the profile does not read `float` denormals as -/// Metal does, and `NativeNanEncoding` where it is not measured to answer Metal's `NaN`. The +/// `RasterizationRateMap`, `DeviceDenormals` and `NativeNanEncoding`. The /// answers are `bind::RasterizationRateMap`'s shader decoders' (Metal's) at every point of a /// map's own layers; only a layer past a map's, whose tables are other words read as `float`s, /// some of them denormal, answers otherwise at some points. @@ -294,15 +289,13 @@ fn the_decoder_answers_as_the_map() { "{what}: {:?}", a.precision ); - assert_eq!( + assert!( a.precision.contains(&PrecisionNote::DeviceDenormals), - !denormal::device_flushes(&p), "{what}: {:?}", a.precision ); - assert_eq!( + assert!( a.precision.contains(&PrecisionNote::NativeNanEncoding), - nan::encoding(&p) == NanEncoding::Native, "{what}: {:?}", a.precision ); diff --git a/crates/metal2vulkan/src/tests/engine_simd_emulated.rs b/crates/metal2vulkan/src/tests/engine_simd_emulated.rs index 865df756f..3e73ee68b 100644 --- a/crates/metal2vulkan/src/tests/engine_simd_emulated.rs +++ b/crates/metal2vulkan/src/tests/engine_simd_emulated.rs @@ -826,9 +826,8 @@ fn simd_uniform_runs_emulated_at_every_width() { /// out of both forms (1,145 against 462 words, 2.48x, to 1,136 against 453, 2.51x): the emulation's /// 683 words over the subgroup form did not change, so the hold moved to 2.55x. Through /// `Device::from_queries` the kernel is 1,164 words on `lavapipe` against 453 (2.57x), held at -/// 2.6x, still below the flag form's 112 extra words (about 2.75x against 453). The subgroup form is `moltenvk-m3`'s -/// without its driver's measured deviation (`MetalCanonicalNans`), which neither emulated profile -/// has, so both forms carry the same NaN selects (the input's `fadd` before the reduction: 14 +/// 2.6x, still below the flag form's 112 extra words (about 2.75x against 453). The subgroup form is +/// `moltenvk-m3`'s, so both forms carry the same NaN selects (the input's `fadd` before the reduction: 14 /// words, 1,150 against 467 on `lavapipe`, 2.46x) and the ratio stays the emulation's. A profile /// with no measured half-rounding fact (`lavapipe`, `vk12-floor`) rounds each `half` add in integer /// arithmetic, twenty instructions, where `moltenvk-m3`'s measured conversion takes three. That diff --git a/crates/metal2vulkan/src/tests/engine_texture.rs b/crates/metal2vulkan/src/tests/engine_texture.rs index 6326c3df2..85f2dd6c0 100644 --- a/crates/metal2vulkan/src/tests/engine_texture.rs +++ b/crates/metal2vulkan/src/tests/engine_texture.rs @@ -427,7 +427,7 @@ const OP_IS_NAN: u16 = 156; /// `DeviceNanEncoding`; bound in `RGBA16Float` it records the note too; bound in `RGBA8Unorm` it /// records none. Where the choice declares no format and no class, the write records the note /// under the format bound there. A choice declaring `RGBA16Float` records the note on every -/// profile. No write requires `VkProperty::MetalHalfTexelWrites` or `VkProperty::MetalNanMoves`. +/// profile. No write requires `VkProperty::MetalHalfTexelWrites`. #[test] fn a_half_texel_write_records_the_device_nan_encoding_where_it_may_not_be_metal_s() { use crate::device::requirements::VkProperty; @@ -456,7 +456,6 @@ fn a_half_texel_write_records_the_device_nan_encoding_where_it_may_not_be_metal_ let required = |a: &FunctionArtifact| { let properties = &a.requirements.properties; properties.contains(&VkProperty::MetalHalfTexelWrites) - || properties.contains(&VkProperty::MetalNanMoves) }; let tests = |a: &FunctionArtifact| opcodes(&a.module.words).contains(&OP_IS_NAN); for pf in [ diff --git a/crates/metal2vulkan/src/tests/engine_tiny_products.rs b/crates/metal2vulkan/src/tests/engine_tiny_products.rs index 7f90c7de3..3a68b6580 100644 --- a/crates/metal2vulkan/src/tests/engine_tiny_products.rs +++ b/crates/metal2vulkan/src/tests/engine_tiny_products.rs @@ -9,13 +9,11 @@ //! `2^-126` there, and the module takes the device's multiply (announced once per device, //! `float-tininess-after-rounding`). //! -//! The CPU SPIR-V interpreter rounds first and keeps denormals, as a device without -//! `DriverDeviation::MetalFloatDenormals` may, so on each such committed profile (one per fused -//! multiply-add route) it shows what the device answers. `llvm-as` assembles the fixtures; without +//! The CPU SPIR-V interpreter rounds first and keeps denormals, as a device may, so on each +//! committed profile (one per fused multiply-add route) it shows what the device answers. `llvm-as` assembles the fixtures; without //! it the tests skip visibly. use crate::device::{DevicePolicy, DeviceProfile}; -use crate::error::DriverDeviation; use crate::lower::arith::fma; use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; use crate::pipeline::testing::{ @@ -138,15 +136,13 @@ fn interpret(bc: &[u8], entry: &str, p: &DeviceProfile, threads: &[Thread]) -> V .collect() } -/// The committed profiles whose device may keep denormals (no -/// `DriverDeviation::MetalFloatDenormals`), as the interpreter does, one per fused multiply-add -/// route. +/// The committed profiles, one per fused multiply-add route: each device may keep denormals, as +/// the interpreter does. fn keeping() -> Vec<(String, DeviceProfile)> { let mut seen = BTreeSet::new(); committed_profiles_with(DevicePolicy::default()) .expect("profiles") .into_iter() - .filter(|(_, p)| !p.takes_driver_deviation(DriverDeviation::MetalFloatDenormals)) .filter(|(_, p)| seen.insert(fma::float_route(p))) .collect() } diff --git a/crates/metal2vulkan/src/tests/engine_typed_threadgroup.rs b/crates/metal2vulkan/src/tests/engine_typed_threadgroup.rs index 5b7260f5d..3812f0287 100644 --- a/crates/metal2vulkan/src/tests/engine_typed_threadgroup.rs +++ b/crates/metal2vulkan/src/tests/engine_typed_threadgroup.rs @@ -179,8 +179,7 @@ fn run_both(m: &TypedModule, res: &Resources) -> Vec { } /// Whether entry `entry` of `bc` on `prof` reads a `half` from its bits by the device's widening -/// (`PrecisionNote::NativeNanEncoding`, or `VkProperty::MetalNanMoves` on a device the interpreter -/// is not: `device_nan_bits`), whose reinterpretation of a NaN's bits is the device's. +/// (`PrecisionNote::NativeNanEncoding`, `device_nan_bits`), whose reinterpretation of a NaN's bits is the device's. fn native_halves(bc: &[u8], entry: &str, prof: &DeviceProfile) -> bool { device_nan_bits(&compile(bc, entry, prof).expect("compile")) } diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index 6e72a96d8..30cecd8e2 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -927,7 +927,6 @@ enum metal2vulkan::pipeline::BufferForm #[cfg_attr(feature = "serde", derive(ser enum metal2vulkan::pipeline::BufferKind #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum BufferKind enum metal2vulkan::pipeline::ChannelWrite #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum ChannelWrite enum metal2vulkan::pipeline::DescriptorView #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum DescriptorView -enum metal2vulkan::pipeline::EntryMath #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum EntryMath enum metal2vulkan::pipeline::EntryRef #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum EntryRef<'a> enum metal2vulkan::pipeline::FactorLane #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum FactorLane enum metal2vulkan::pipeline::HandleClass #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[non_exhaustive] pub enum HandleClass @@ -6650,8 +6649,8 @@ method metal2vulkan-runtime::MemoryClass::block_len pub const fn block_len(self) method metal2vulkan-runtime::PhysicalDevice::check pub fn check(&self) -> Result method metal2vulkan-runtime::PhysicalDevice::raw pub fn raw(&self) -> vk::PhysicalDevice method metal2vulkan-runtime::PixelFormatInfo::describes_a_format pub fn describes_a_format(&self) -> bool -method metal2vulkan-runtime::PrecisionNote::of_float_operator pub fn of_float_operator(op: AirBin, width: FloatWidth, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option> -method metal2vulkan-runtime::PrecisionNote::of_math_call pub fn of_math_call(call: Math, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option> +method metal2vulkan-runtime::PrecisionNote::of_float_operator pub fn of_float_operator(op: AirBin, width: FloatWidth, fmf: FastMath, p: &DeviceProfile) -> Option> +method metal2vulkan-runtime::PrecisionNote::of_math_call pub fn of_math_call(call: Math, fmf: FastMath, p: &DeviceProfile) -> Option> method metal2vulkan-runtime::RenderCommandEncoder::draw_indexed_primitives pub fn draw_indexed_primitives(&mut self, primitive_type: PrimitiveType, index_count: u32, indices: IndexBuffer<'_>, instance_count: u32, base_vertex: i32, base_instance: u32) -> Result<(), Error> method metal2vulkan-runtime::RenderCommandEncoder::draw_patches pub fn draw_patches(&mut self, number_of_patch_control_points: u32, patch_start: u32, patch_count: u32, patch_index_buffer: Option<(&Buffer, u64)>, instance_count: u32, base_instance: u32) -> Result<(), Error> method metal2vulkan-runtime::RenderCommandEncoder::draw_primitives pub fn draw_primitives(&mut self, primitive_type: PrimitiveType, vertex_start: u32, vertex_count: u32, instance_count: u32, base_instance: u32) -> Result<(), Error> @@ -7282,8 +7281,8 @@ method metal2vulkan::pipeline::MeshPipelineDescriptor::reflection pub fn reflect method metal2vulkan::pipeline::MeshPipelineDescriptor::slot_writes pub fn slot_writes(&self, budget: &crate::Budget) -> Result method metal2vulkan::pipeline::MeshPipelineDescriptor::stages_using_direct_arguments pub fn stages_using_direct_arguments(&self, budget: &crate::Budget, entries: &StageEntries) -> Result, Error> method metal2vulkan::pipeline::MeshPipelineDescriptor::unwritten_fragment_inputs pub fn unwritten_fragment_inputs(&self, budget: &crate::Budget, entries: &StageEntries) -> Result, Error> -method metal2vulkan::pipeline::PrecisionNote::of_float_operator pub fn of_float_operator(op: AirBin, width: FloatWidth, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option> -method metal2vulkan::pipeline::PrecisionNote::of_math_call pub fn of_math_call(call: Math, fmf: FastMath, p: &DeviceProfile, math: EntryMath) -> Option> +method metal2vulkan::pipeline::PrecisionNote::of_float_operator pub fn of_float_operator(op: AirBin, width: FloatWidth, fmf: FastMath, p: &DeviceProfile) -> Option> +method metal2vulkan::pipeline::PrecisionNote::of_math_call pub fn of_math_call(call: Math, fmf: FastMath, p: &DeviceProfile) -> Option> method metal2vulkan::pipeline::PrivateRenderState::new pub const fn new() -> PrivateRenderState method metal2vulkan::pipeline::RenderPipeline::content_digest pub fn content_digest(&self) -> Hash256 method metal2vulkan::pipeline::RenderPipeline::footprint pub fn footprint(&self) -> u64 @@ -10265,24 +10264,16 @@ variant metal2vulkan::device::VkProperty::MetalCenterVaryings MetalCenterVarying variant metal2vulkan::device::VkProperty::MetalDepth16BiasedStores MetalDepth16BiasedStores variant metal2vulkan::device::VkProperty::MetalDepth16Stores MetalDepth16Stores variant metal2vulkan::device::VkProperty::MetalFirstVertexIndices MetalFirstVertexIndices -variant metal2vulkan::device::VkProperty::MetalFloatDenormals MetalFloatDenormals variant metal2vulkan::device::VkProperty::MetalFragmentSimdgroups MetalFragmentSimdgroups variant metal2vulkan::device::VkProperty::MetalFullQuads MetalFullQuads -variant metal2vulkan::device::VkProperty::MetalHalfArithmetic MetalHalfArithmetic -variant metal2vulkan::device::VkProperty::MetalHalfConversion MetalHalfConversion -variant metal2vulkan::device::VkProperty::MetalHalfFma MetalHalfFma variant metal2vulkan::device::VkProperty::MetalHalfStorageNans MetalHalfStorageNans variant metal2vulkan::device::VkProperty::MetalHalfStorageWrites MetalHalfStorageWrites variant metal2vulkan::device::VkProperty::MetalHalfTexelWrites MetalHalfTexelWrites variant metal2vulkan::device::VkProperty::MetalInterpolation MetalInterpolation -variant metal2vulkan::device::VkProperty::MetalMinMax MetalMinMax -variant metal2vulkan::device::VkProperty::MetalNanMoves MetalNanMoves variant metal2vulkan::device::VkProperty::MetalNormStorageWrites MetalNormStorageWrites variant metal2vulkan::device::VkProperty::MetalNormalizedVertexFetch MetalNormalizedVertexFetch -variant metal2vulkan::device::VkProperty::MetalPackConversions MetalPackConversions variant metal2vulkan::device::VkProperty::MetalSampler MetalSampler variant metal2vulkan::device::VkProperty::MetalSmallFloatNans MetalSmallFloatNans -variant metal2vulkan::device::VkProperty::MetalUnaryDenormals MetalUnaryDenormals variant metal2vulkan::device::VkProperty::MetalVertexSimdgroups MetalVertexSimdgroups variant metal2vulkan::device::VkProperty::ProvokingVertexModePerPipeline ProvokingVertexModePerPipeline variant metal2vulkan::device::VkProperty::RequiredSubgroupSizeStage RequiredSubgroupSizeStage(Stage) @@ -10433,30 +10424,20 @@ variant metal2vulkan::error::DescriptorError::VertexStepRate VertexStepRate { st variant metal2vulkan::error::DriverDeviation::CubeGradientRoute CubeGradientRoute variant metal2vulkan::error::DriverDeviation::GraphicsCubeGradientTangents GraphicsCubeGradientTangents variant metal2vulkan::error::DriverDeviation::MetalAlphaCoverage MetalAlphaCoverage -variant metal2vulkan::error::DriverDeviation::MetalCanonicalNans MetalCanonicalNans variant metal2vulkan::error::DriverDeviation::MetalCenterVaryings MetalCenterVaryings variant metal2vulkan::error::DriverDeviation::MetalDepth16BiasedStores MetalDepth16BiasedStores variant metal2vulkan::error::DriverDeviation::MetalDepth16Stores MetalDepth16Stores variant metal2vulkan::error::DriverDeviation::MetalFirstVertexIndices MetalFirstVertexIndices -variant metal2vulkan::error::DriverDeviation::MetalFloatDenormals MetalFloatDenormals -variant metal2vulkan::error::DriverDeviation::MetalFloatFunctions MetalFloatFunctions variant metal2vulkan::error::DriverDeviation::MetalFragmentSimdgroups MetalFragmentSimdgroups variant metal2vulkan::error::DriverDeviation::MetalFullQuads MetalFullQuads -variant metal2vulkan::error::DriverDeviation::MetalHalfArithmetic MetalHalfArithmetic -variant metal2vulkan::error::DriverDeviation::MetalHalfConversion MetalHalfConversion -variant metal2vulkan::error::DriverDeviation::MetalHalfFma MetalHalfFma variant metal2vulkan::error::DriverDeviation::MetalHalfStorageNans MetalHalfStorageNans variant metal2vulkan::error::DriverDeviation::MetalHalfStorageWrites MetalHalfStorageWrites variant metal2vulkan::error::DriverDeviation::MetalHalfTexelWrites MetalHalfTexelWrites variant metal2vulkan::error::DriverDeviation::MetalInterpolation MetalInterpolation -variant metal2vulkan::error::DriverDeviation::MetalMinMax MetalMinMax -variant metal2vulkan::error::DriverDeviation::MetalNanMoves MetalNanMoves variant metal2vulkan::error::DriverDeviation::MetalNormStorageWrites MetalNormStorageWrites variant metal2vulkan::error::DriverDeviation::MetalNormalizedVertexFetch MetalNormalizedVertexFetch -variant metal2vulkan::error::DriverDeviation::MetalPackConversions MetalPackConversions variant metal2vulkan::error::DriverDeviation::MetalSampler MetalSampler variant metal2vulkan::error::DriverDeviation::MetalSmallFloatNans MetalSmallFloatNans -variant metal2vulkan::error::DriverDeviation::MetalUnaryDenormals MetalUnaryDenormals variant metal2vulkan::error::DriverDeviation::MetalVertexSimdgroups MetalVertexSimdgroups variant metal2vulkan::error::DriverDeviation::SimdgroupLockstep SimdgroupLockstep variant metal2vulkan::error::DynamicLibraryProblem::FunctionConstants FunctionConstants @@ -10853,8 +10834,6 @@ variant metal2vulkan::pipeline::ChannelWrite::Unorm Unorm { bits: u8 } variant metal2vulkan::pipeline::DescriptorView::Storage Storage variant metal2vulkan::pipeline::DescriptorView::UniformVec4 UniformVec4 variant metal2vulkan::pipeline::DescriptorView::UniformWords UniformWords -variant metal2vulkan::pipeline::EntryMath::Fast Fast -variant metal2vulkan::pipeline::EntryMath::Precise Precise variant metal2vulkan::pipeline::EntryRef::Index Index(u32) variant metal2vulkan::pipeline::EntryRef::Name Name(&'a str) variant metal2vulkan::pipeline::FactorLane::One One diff --git a/crates/metal2vulkan/tests/api_surface.rs b/crates/metal2vulkan/tests/api_surface.rs index 194048ac0..78da1dc16 100644 --- a/crates/metal2vulkan/tests/api_surface.rs +++ b/crates/metal2vulkan/tests/api_surface.rs @@ -316,7 +316,6 @@ surface! { struct ComputePipelineMetalInfo N; struct CompileReport N; struct EntryDescriptor N; - enum EntryMath E; struct EntryPlan N; enum EntryRef E; struct LinkedSource O; @@ -936,7 +935,7 @@ use metal2vulkan::library::{CompiledFunction, Library}; use metal2vulkan::metal::{PixelFormat, VertexFormat}; use metal2vulkan::pipeline::{ ColorAttachmentDescriptor, ComputePipeline, ComputePipelineDescriptor, EntryDescriptor, - EntryMath, EntryRef, FunctionDescriptor, LoweringInputs, PrecisionNote, RenderPipeline, + EntryRef, FunctionDescriptor, LoweringInputs, PrecisionNote, RenderPipeline, RenderPipelineDescriptor, Stage, StageSource, VertexAttributeDescriptor, VertexBufferLayoutDescriptor, VertexDescriptor, }; @@ -1222,12 +1221,11 @@ fn the_precision_contract_names_each_float_operations_notes() { .fold(FastMath::NONE, |all, (flag, _)| all.union(*flag)); let lavapipe = device("lavapipe"); let lavapipe = lavapipe.profile(); - let fdiv = |p: &metal2vulkan::device::DeviceProfile, math| { - PrecisionNote::of_float_operator(BinOp::FDiv, FloatWidth::F32, fast, p, math) - }; - assert!(fdiv(lavapipe, EntryMath::Fast) - .expect("a float operator") - .contains(&PrecisionNote::DeviceArithmetic)); + assert!( + PrecisionNote::of_float_operator(BinOp::FDiv, FloatWidth::F32, fast, lavapipe) + .expect("a float operator") + .contains(&PrecisionNote::DeviceArithmetic) + ); let native = device_under("lavapipe", DevicePolicy::default()); assert_eq!( PrecisionNote::of_float_operator( @@ -1235,7 +1233,6 @@ fn the_precision_contract_names_each_float_operations_notes() { FloatWidth::F32, FastMath::NONE, native.profile(), - EntryMath::Precise ), Some(BTreeSet::from([ PrecisionNote::DeviceDenormals, @@ -1244,20 +1241,13 @@ fn the_precision_contract_names_each_float_operations_notes() { ])) ); assert_eq!( - PrecisionNote::of_float_operator( - BinOp::Add, - FloatWidth::F32, - fast, - lavapipe, - EntryMath::Fast - ), + PrecisionNote::of_float_operator(BinOp::Add, FloatWidth::F32, fast, lavapipe,), None ); let Some(AirIntrinsic::Math(tanh)) = AirIntrinsic::parse("air.fast_tanh.f32") else { panic!("air.fast_tanh.f32 is a math call"); }; - let notes = PrecisionNote::of_math_call(tanh, fast, lavapipe, EntryMath::Fast) - .expect("a float function"); + let notes = PrecisionNote::of_math_call(tanh, fast, lavapipe).expect("a float function"); assert!( notes.contains(&PrecisionNote::NativeTranscendentals), "{notes:?}" diff --git a/docs/HOWTO.md b/docs/HOWTO.md index dbab24cdb..162d058d0 100644 --- a/docs/HOWTO.md +++ b/docs/HOWTO.md @@ -45,10 +45,7 @@ A `half` computed in `float` rounds through the device's conversion to 16 bits a `half(float)` under the float controls the entry declares, where the driver keeps that pair (ANV, RADV). Elsewhere it rounds through the device's own conversion, or its `OpQuantizeToF16` alone without `shaderFloat16` (which may flush a value below the smallest normal `half`), and the -pipeline records `NativeHalfConversion` or `NativeHalfQuantize`; not `NativeHalfConversion` on -MoltenVK on the Apple M3 Max's macOS 27 identity (`DriverDeviation::MetalHalfConversion`), where -every such `half` is a conversion of a `float` the function holds or of a texel, measured to be -Metal's. NVIDIA's driver (615.71.09) folds the pair even under the float controls, so its +pipeline records `NativeHalfConversion` or `NativeHalfQuantize`. NVIDIA's driver (615.71.09) folds the pair even under the float controls, so its rounding there is the device's conversion, or none; its pipelines still declare the float controls and compute a `half` `+`, `-`, `*`, `/` and `sqrt` with the device's 16-bit instructions, as ANV's and RADV's do. RADV's compiler fuses a `float` addition, subtraction, multiply or fused @@ -60,11 +57,9 @@ A `half` read from memory or from its bits is the device's widening on every dev `OpFConvert` of the bits read as a 16-bit float with `shaderFloat16`, `GLSL.std.450 UnpackHalf2x16` without it), and a `half` stored or reinterpreted as bits, unless they are the bits it was loaded from, the device's narrowing (an `OpFConvert` to 16 bits, `GLSL.std.450 -PackHalf2x16` without `shaderFloat16`); the pipeline records `NativeNanEncoding` (a NaN's bits; -not on MoltenVK on the Apple M3 Max's macOS 27 identity, `DriverDeviation::MetalNanMoves`, where -the `half` moves through the registers alone or into a texture write's texel) and, where that conversion is neither under the -float controls nor measured to be Metal's, `NativeHalfConversion` (a denormal the device may -flush). +PackHalf2x16` without `shaderFloat16`); the pipeline records `NativeNanEncoding` (a NaN's bits) +and, where that conversion is not under the float controls, `NativeHalfConversion` (a denormal the +device may flush). To read AIR without translating it (list a metallib's functions, decode a module into typed IR, read its entry points' bindings, canonicalize an entry under function-constant values), depend on