diff --git a/crates/metal2vulkan-devtools/src/fuzz.rs b/crates/metal2vulkan-devtools/src/fuzz.rs index f11006d6e..66052407b 100644 --- a/crates/metal2vulkan-devtools/src/fuzz.rs +++ b/crates/metal2vulkan-devtools/src/fuzz.rs @@ -74,8 +74,7 @@ impl Default for Target { /// index the generators build is a small non-negative `i32`, so the three spellings name the same /// element; they reach different index forms of the engine (a zero-extended word, a /// sign-extended word, and an `i32` index the GEP itself extends), and [`IndexForm::Narrow32`] -/// programs compute no 64-bit index or offset, which a profile without `shaderInt64` (`vk12-floor`) -/// runs without two-word emulation. +/// programs compute no 64-bit index or offset. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum IndexForm { /// `zext i32 %v to i64`, the Metal front end's spelling of an unsigned index. diff --git a/crates/metal2vulkan-validation/runtime-sources.sha256 b/crates/metal2vulkan-validation/runtime-sources.sha256 index 89a1f4767..1f07dba9c 100644 --- a/crates/metal2vulkan-validation/runtime-sources.sha256 +++ b/crates/metal2vulkan-validation/runtime-sources.sha256 @@ -1 +1 @@ -eccf4a8b077f3b9b365540dbda6a5493442fa17f1a555aa1934c69e13a5f6d93 +596a528ed6d2aa047bed0f8a3fc06b7b586690bebc90c3a1f060a3b4dbe505b2 diff --git a/crates/metal2vulkan/src/device/derive.rs b/crates/metal2vulkan/src/device/derive.rs index 69559ea06..57dd6e612 100644 --- a/crates/metal2vulkan/src/device/derive.rs +++ b/crates/metal2vulkan/src/device/derive.rs @@ -155,7 +155,6 @@ fn derive_fields(desc: &DeviceDescription) -> ProfileFields { let leaf = LeafCaps { int8: has(VkFeature::ShaderInt8), int16: has(VkFeature::ShaderInt16), - int64: has(VkFeature::ShaderInt64), float16: has(VkFeature::ShaderFloat16), float64: has(VkFeature::ShaderFloat64), storage_buffer_8bit: has(VkFeature::StorageBuffer8BitAccess), diff --git a/crates/metal2vulkan/src/device/metal.rs b/crates/metal2vulkan/src/device/metal.rs index 31125004e..4c136d08f 100644 --- a/crates/metal2vulkan/src/device/metal.rs +++ b/crates/metal2vulkan/src/device/metal.rs @@ -245,7 +245,6 @@ fn unsupported_features(profile: &DeviceProfile) -> Vec { let f = profile.fields(); let feature = Capability::Feature; let mut out = Vec::new(); - // 64-bit integer arithmetic needs no `shaderInt64`: it is held as two words. if !f.leaf.float64 { out.push(Unsupported::needs( Feature::Float64Arithmetic, diff --git a/crates/metal2vulkan/src/device/profile.rs b/crates/metal2vulkan/src/device/profile.rs index b9a6d6dd8..86eb80d7a 100644 --- a/crates/metal2vulkan/src/device/profile.rs +++ b/crates/metal2vulkan/src/device/profile.rs @@ -457,7 +457,6 @@ impl EnabledCaps { pub struct LeafCaps { pub int8: bool, pub int16: bool, - pub int64: bool, pub float16: bool, pub float64: bool, pub storage_buffer_8bit: bool, diff --git a/crates/metal2vulkan/src/device/tests/subgroup.rs b/crates/metal2vulkan/src/device/tests/subgroup.rs index 551b55b8e..b3fe76017 100644 --- a/crates/metal2vulkan/src/device/tests/subgroup.rs +++ b/crates/metal2vulkan/src/device/tests/subgroup.rs @@ -646,8 +646,6 @@ fn metal_properties_report_d3_d4_values() { assert!(m.simd.kernel.matrix); assert!(!m.simd.fragment.matrix); let has = |f: &Feature| m.unsupported_features.iter().any(|u| u.feature == *f); - // 64-bit integers are two words without `shaderInt64`, on every pipeline. - assert!(!has(&Feature::Int64Arithmetic)); assert!(has(&Feature::RasterOrderGroups)); // No pixel interlock: framebuffer fetch reads input attachments ordered between draws, a // note, not a refusal. @@ -659,8 +657,4 @@ fn metal_properties_report_d3_d4_values() { assert_eq!(m.argument_buffers_tier, ArgumentBuffersTier::Tier2); assert!(m.simd.kernel.matrix); assert!(m.simd.kernel.cross_lane.contains(OpBits::SHUFFLE)); - assert!(!m - .unsupported_features - .iter() - .any(|u| u.feature == Feature::Int64Arithmetic)); } diff --git a/crates/metal2vulkan/src/error/mod.rs b/crates/metal2vulkan/src/error/mod.rs index fa88f6b0d..7ba61cfa7 100644 --- a/crates/metal2vulkan/src/error/mod.rs +++ b/crates/metal2vulkan/src/error/mod.rs @@ -638,8 +638,6 @@ pub enum Feature { ArgumentBufferObjects, /// Dereferencing a pointer loaded from memory or made from an integer. DereferenceLoadedPointer, - /// Comparing pointers with different roots. - PointerCompare, /// A resource handle used as a byte pointer, or conflicting handle provenance. HandleAsPointer, /// A constant global whose address escapes. @@ -660,8 +658,6 @@ pub enum Feature { DescriptorCount, // ---- Arithmetic ---- - /// 64-bit integer arithmetic. - Int64Arithmetic, /// 64-bit float arithmetic. Float64Arithmetic, diff --git a/crates/metal2vulkan/src/lower/access/copy.rs b/crates/metal2vulkan/src/lower/access/copy.rs index c25e54594..48a4dd8ea 100644 --- a/crates/metal2vulkan/src/lower/access/copy.rs +++ b/crates/metal2vulkan/src/lower/access/copy.rs @@ -46,9 +46,7 @@ //! which is exact for any overlap. Buffer endpoints with different or several candidate slots may //! alias through the binding (one buffer bound at two slots), and a wide endpoint may reach any //! buffer: those compare the endpoints' Metal addresses instead (`Overlap::Addressed`; a static -//! candidate's is its `SlotGuestBase` plus its displacement, a wide pointer's its root entry's -//! `guest + bind_offset + offset`), which needs `shaderInt64` for the `u64` addresses -//! (`Unsupported{PointerCompare}` naming it otherwise). +//! candidate's is its `SlotGuestBase` plus its displacement, a wide pointer's the `u64` it holds). //! //! **Volatile** intrinsics lower as the others, every unit accessed exactly once and in order, with //! every word load and store of a unit carrying `Volatile` (a volatile load or store's operand; the @@ -184,8 +182,7 @@ pub enum Source { pub enum Length { /// `count` whole units, then `tail` bytes (below the unit). Const { count: u32, tail: u32 }, - /// The operand `len`, an `i32` (held in a `u32`) or an `i64` (`wide`, held in a `u64`, or as - /// two `u32` words without `shaderInt64`). + /// The operand `len`, an `i32` (held in a `u32`) or an `i64` (`wide`, held in a `u64`). Dynamic { len: ValueId, wide: bool }, } @@ -538,11 +535,6 @@ pub fn select( let wide = match cx.lowered_repr(n, ty)? { DemoteTy::Scalar(ScalarTy::Int { bits: 32 }) => false, DemoteTy::Scalar(ScalarTy::Int { bits: 64 }) => true, - // An `i64` held as two words without `shaderInt64`. - DemoteTy::Vector { - elem: ScalarTy::Int { bits: 32 }, - len: 2, - } => true, _ => return Err(refuse(AccessCause::AccessType)), }; Span::Dynamic(Length::Dynamic { @@ -739,7 +731,7 @@ fn directed(cx: &mut SelectCx<'_>, dst: &Endpoint, from: &Endpoint) -> Result, statics: &[&Access]) -> Result { for a in statics { - dynamic::plan_static_guest(cx, &a.targets, crate::error::Feature::PointerCompare)?; + dynamic::plan_static_guest(cx, &a.targets)?; } Ok(Overlap::Addressed) } @@ -1026,7 +1018,7 @@ fn span(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, op: &MemOp) -> BResul width: 32, signed: false, })?; - if wide && !cx.plan.families.arith.wide && op.only_wide() { + if wide && op.only_wide() { // A `u64` length between wide endpoints, counted exactly. if op.unit == 1 { return Ok((Count::Wide(len), Count::Const(0))); @@ -1039,19 +1031,12 @@ fn span(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, op: &MemOp) -> BResul return Ok((Count::Wide(units), Count::Value(tail))); } let len = if wide { - // A `u64`, or the two words `(low, high)` of a profile without `shaderInt64`. - let (low, over) = if cx.plan.families.arith.wide { - let low = fb.composite_extract(len, &[0])?; - let high = fb.composite_extract(len, &[1])?; - let zero = k32(fb, 0)?; - (low, fb.binary(BinOp::INotEqual, high, zero)?) - } else { - let low = fb.convert(ConvOp::UConvert, len, u32_)?; - let k = psb::k64(fb, 32)?; - let high = fb.binary(BinOp::ShiftRightLogical, len, k)?; - let zero = psb::k64(fb, 0)?; - (low, fb.binary(BinOp::INotEqual, high, zero)?) - }; + // A `u64`: its low word, or `u32::MAX` where its high word is not zero. + let low = fb.convert(ConvOp::UConvert, len, u32_)?; + let k = psb::k64(fb, 32)?; + let high = fb.binary(BinOp::ShiftRightLogical, len, k)?; + let zero = psb::k64(fb, 0)?; + let over = fb.binary(BinOp::INotEqual, high, zero)?; let max = k32(fb, u32::MAX)?; fb.select(over, max, low)? } else { diff --git a/crates/metal2vulkan/src/lower/access/dynamic.rs b/crates/metal2vulkan/src/lower/access/dynamic.rs index 5886e0bec..18cdbddbf 100644 --- a/crates/metal2vulkan/src/lower/access/dynamic.rs +++ b/crates/metal2vulkan/src/lower/access/dynamic.rs @@ -66,7 +66,7 @@ use crate::air::ir::{ }; use crate::budget::Meter; use crate::device::requirements::VkFeature; -use crate::error::{AccessCause, Capability, Error, Feature, LowerFamily, Unsupported}; +use crate::error::{AccessCause, Error, LowerFamily}; use crate::lower::arith::{Form, Held}; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; @@ -1147,20 +1147,8 @@ pub(super) fn static_guest_address( } /// Plan the Metal addresses of the static-root candidates `targets` ([`static_guest_address`]): -/// their `SlotGuestBase` push fields, summed with displacements in `u64` arithmetic that needs -/// `shaderInt64` (named in the refusal of `feature` otherwise). -pub(super) fn plan_static_guest( - cx: &mut SelectCx<'_>, - targets: &[Target], - feature: Feature, -) -> Result<(), Error> { - if !cx.profile.fields().leaf.int64 { - return Err(Unsupported::needs( - feature, - Capability::Feature(crate::device::requirements::VkFeature::ShaderInt64), - ) - .into()); - } +/// their `SlotGuestBase` push fields, summed with displacements in `u64` arithmetic. +pub(super) fn plan_static_guest(cx: &mut SelectCx<'_>, targets: &[Target]) -> Result<(), Error> { for t in targets { let slot = cx .memory diff --git a/crates/metal2vulkan/src/lower/access/emit.rs b/crates/metal2vulkan/src/lower/access/emit.rs index 502dd3477..65c803758 100644 --- a/crates/metal2vulkan/src/lower/access/emit.rs +++ b/crates/metal2vulkan/src/lower/access/emit.rs @@ -653,8 +653,8 @@ pub(super) fn index_u32( let zero = k32(fb, 0)?; fb.select(x, one, zero) } - // A `u64`, or two words without `shaderInt64`. - IndexForm::Wide => crate::lower::arith::wide::low_word(fb, x), + // A `u64`. + IndexForm::Wide => crate::lower::arith::ops::low_word(fb, x), } } diff --git a/crates/metal2vulkan/src/lower/access/function_table.rs b/crates/metal2vulkan/src/lower/access/function_table.rs index 06cde9422..7b6ebeefd 100644 --- a/crates/metal2vulkan/src/lower/access/function_table.rs +++ b/crates/metal2vulkan/src/lower/access/function_table.rs @@ -41,7 +41,6 @@ use std::borrow::Cow; use crate::air::intrinsics::{AirIntrinsic, FunctionTable}; use crate::air::ir::{Callee, Inst, InstKind, ValueId}; use crate::error::Error; -use crate::lower::arith::legal; use crate::lower::emit::EmitCx; use crate::lower::select::{DescriptorCounts, Plan, SelectCx}; use crate::memory::handles::{self, EntryField}; @@ -55,7 +54,6 @@ use crate::spirv::error::BResult; use crate::spirv::ids::FuncId; use crate::spirv::ir::{BinOp, ConvOp, Type as SType}; -use super::handle::HandleIds; use super::psb::{k64, PsbMem}; /// Where a function's table reads find the tables' words. @@ -71,9 +69,6 @@ pub enum TableWords { /// How a function reads tables by their resource ids. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct TableReads { - /// How the directory's ids are held: one `u64`, or two words on a profile without - /// `shaderInt64`. - pub ids: HandleIds, /// Where the words are. pub words: TableWords, } @@ -170,16 +165,12 @@ pub fn select(cx: &mut SelectCx<'_>, inst: &Inst) -> Result, E let [id, word] = call.args[..] else { return Err(cx.invariant("a table word read of another arity")); }; - let ids = match legal::holds_wide(cx.profile) { - true => HandleIds::Words, - false => HandleIds::U64, - }; let addressed = cx.inputs.addressed_function_tables; let (words, storage_buffers) = match addressed { true => (TableWords::Addressed, 1), false => (TableWords::Snapshot, 2), }; - let reads = TableReads { ids, words }; + let reads = TableReads { words }; if cx.families.access.function_tables.is_none() { cx.families.access.function_tables = Some(reads); cx.descriptors = cx.descriptors.plus(&DescriptorCounts { @@ -206,8 +197,7 @@ pub fn select(cx: &mut SelectCx<'_>, inst: &Inst) -> Result, E pub fn routine_words(tables: Option) -> impl Iterator { tables .map(|reads| { - let words = - handles::lookup_routine_words(reads.ids == HandleIds::U64, lookup_form(reads)); + let words = handles::lookup_routine_words(lookup_form(reads)); ("access.function_table.word", u64::from(words)) }) .into_iter() @@ -222,18 +212,14 @@ fn lookup_form(reads: TableReads) -> handles::Lookup { } } -/// Declare the stage's function-table directory (an entry array, or a word view on a profile -/// without `shaderInt64`), the module's search of it, and the stage's snapshot (none for an -/// addressed read), when the plan reads a table by its resource id. +/// Declare the stage's function-table directory (an entry array), the module's search of it, and +/// the stage's snapshot (none for an addressed read), when the plan reads a table by its resource +/// id. pub fn declare(mb: &mut ModuleBuilder, plan: &Plan) -> BResult> { let Some(reads) = plan.families.access.function_tables else { return Ok(None); }; - let directory = handles::declare_table( - mb, - directory_symbol(plan.stage), - reads.ids == HandleIds::U64, - )?; + let directory = handles::declare_table(mb, directory_symbol(plan.stage))?; let lookup = handles::define_lookup(mb, directory, lookup_form(reads))?; if reads.words == TableWords::Addressed { return Ok(Some(FunctionTables { @@ -261,22 +247,14 @@ pub fn emit( return Err(cx.fail("a table word read without its directory")); }; let id = cx.operand(fb, s.id)?; - let (lo, hi) = match s.reads.ids { - HandleIds::Words => ( - fb.composite_extract(id, &[0])?, - fb.composite_extract(id, &[1])?, - ), - HandleIds::U64 => { - let u32_ty = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - let lo = fb.convert(ConvOp::UConvert, id, u32_ty)?; - let shift = k32(fb, 32)?; - let high = fb.binary(BinOp::ShiftRightLogical, id, shift)?; - (lo, fb.convert(ConvOp::UConvert, high, u32_ty)?) - } - }; + let u32_ty = fb.module().ty(SType::Int { + width: 32, + signed: false, + })?; + let lo = fb.convert(ConvOp::UConvert, id, u32_ty)?; + let shift = k32(fb, 32)?; + let high = fb.binary(BinOp::ShiftRightLogical, id, shift)?; + let hi = fb.convert(ConvOp::UConvert, high, u32_ty)?; let Some(element) = fb.call(tables.lookup, &[lo, hi])? else { return Err(cx.fail("a directory search without a result")); }; diff --git a/crates/metal2vulkan/src/lower/access/handle.rs b/crates/metal2vulkan/src/lower/access/handle.rs index c59e84203..e855ac42f 100644 --- a/crates/metal2vulkan/src/lower/access/handle.rs +++ b/crates/metal2vulkan/src/lower/access/handle.rs @@ -1151,14 +1151,6 @@ fn lookup( /// handle's arithmetic (`OpCompositeExtract` of 5 words each, and the rest's). const LOOKUP_CALL_WORDS: u32 = 24; -/// How a function-table directory search reads an entry's resource id: as one `u64` on a profile -/// with `shaderInt64`, else as two words. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum HandleIds { - U64, - Words, -} - /// Emit handle strategy `s`, defining value `vid`. pub fn emit( cx: &mut EmitCx<'_>, diff --git a/crates/metal2vulkan/src/lower/access/icb.rs b/crates/metal2vulkan/src/lower/access/icb.rs index 44b16a649..48f65f2ad 100644 --- a/crates/metal2vulkan/src/lower/access/icb.rs +++ b/crates/metal2vulkan/src/lower/access/icb.rs @@ -203,7 +203,7 @@ fn address(cx: &mut SelectCx<'_>, v: Value, m: &mut Meter) -> Result, slot: Option, }, - /// `icmp` of Metal addresses, in two words without `shaderInt64` (`words`). + /// `icmp` of Metal addresses. CompareAddresses { pred: IntPredicate, a: Addr, b: Addr, - words: bool, }, /// `ptrtoint` of a static fat pointer to `i`. - ToInt { of: Addr, bits: u8, words: bool }, + ToInt { of: Addr, bits: u8 }, /// A static fat pointer stored as its 8-byte Metal address through a static-root pointer, a /// wide pointer, or an arena's pointer cell. - StorePointer { - to: Box, - value: Addr, - words: bool, - }, + StorePointer { to: Box, value: Addr }, } /// SPIR-V words of one candidate's address: the guest base, the displacement, the sum, and the -/// root select (twice that in two words). +/// root select. const CANDIDATE_WORDS: u32 = 48; impl Addr { - fn words(&self, two: bool) -> u32 { - let per = if two { 2 } else { 1 }; + fn words(&self) -> u32 { match self { Addr::Null => 4, Addr::Static(s) => (s.targets.len() as u32 + u32::from(s.null)) .saturating_add(1) - .saturating_mul(CANDIDATE_WORDS * per), + .saturating_mul(CANDIDATE_WORDS), Addr::Wide(_) => 80, } } @@ -166,10 +157,9 @@ impl PointerValue { /// Metal address carry `Volatile`; the refusal of any other strategy. pub(super) fn volatile(self) -> Result { match self { - PointerValue::StorePointer { to, value, words } => Ok(PointerValue::StorePointer { + PointerValue::StorePointer { to, value } => Ok(PointerValue::StorePointer { to: Box::new((*to).volatile()), value, - words, }), _ => Err(refuse(AccessCause::Volatile)), } @@ -182,12 +172,7 @@ impl PointerValue { pub fn name(&self, slots: &AccessPlan) -> Cow<'static, str> { match self { PointerValue::CompareOffsets { .. } => "access.pointer.compare_offsets".into(), - PointerValue::CompareAddresses { words: false, .. } => { - "access.pointer.compare_addresses".into() - } - PointerValue::CompareAddresses { words: true, .. } => { - "access.pointer.compare_addresses.words".into() - } + PointerValue::CompareAddresses { .. } => "access.pointer.compare_addresses".into(), PointerValue::ToInt { .. } => "access.pointer.ptrtoint".into(), PointerValue::StorePointer { to, .. } => match &**to { Source::Static(a) => a.reach(slots).qualify("access.pointer.store_pointer"), @@ -201,15 +186,13 @@ impl PointerValue { pub fn words(&self) -> u32 { match self { PointerValue::CompareOffsets { .. } => 24, - PointerValue::CompareAddresses { a, b, words, .. } => a - .words(*words) - .saturating_add(b.words(*words)) - .saturating_add(if *words { 48 } else { 8 }), - PointerValue::ToInt { of, words, .. } => of.words(*words).saturating_add(16), - PointerValue::StorePointer { to, value, words } => to - .words() - .saturating_add(value.words(*words)) - .saturating_add(8), + PointerValue::CompareAddresses { a, b, .. } => { + a.words().saturating_add(b.words()).saturating_add(8) + } + PointerValue::ToInt { of, .. } => of.words().saturating_add(16), + PointerValue::StorePointer { to, value } => { + to.words().saturating_add(value.words()).saturating_add(8) + } } } } @@ -415,18 +398,10 @@ fn compare( } } (Kind::Null | Kind::Fat | Kind::Wide, Kind::Null | Kind::Fat | Kind::Wide) => { - let words = !cx.profile.fields().leaf.int64; - let x = address(cx, a, &ka, m)?; - let y = address(cx, b, &kb, m)?; - if words && (matches!(x, Addr::Wide(_)) || matches!(y, Addr::Wide(_))) { - // A wide pointer implies Profile A, which implies `shaderInt64`. - return Err(cx.invariant("a wide pointer on a profile without shaderInt64")); - } PointerValue::CompareAddresses { pred, - a: x, - b: y, - words, + a: address(cx, a, &ka, m)?, + b: address(cx, b, &kb, m)?, } } _ => return Err(refuse(AccessCause::PointerCompare)), @@ -446,19 +421,14 @@ fn static_escape(cx: &SelectCx<'_>, v: Value) -> Result, Error> { }) } -/// The 8-byte leaf of a stored Metal address of AIR pointer type `ty` (a `u64`, or two words -/// without `shaderInt64`). +/// The 8-byte leaf of a stored Metal address of AIR pointer type `ty` (a `u64`). fn address_leaf(cx: &SelectCx<'_>, ty: TypeId, align: Option) -> Result { if cx.memory.layouts.store_size(ty) != Some(8) { return Err(refuse(AccessCause::PointerSize)); } - let held = if cx.profile.fields().leaf.int64 { - Held::Int { - bits: 64, - container: 64, - } - } else { - Held::Wide { bits: 64 } + let held = Held::Int { + bits: 64, + container: 64, }; Ok(Leaf { form: Form { held, lanes: 1 }, @@ -499,11 +469,9 @@ fn store_pointer( } _ => dynamic::store_destination(cx, ptr, leaf)?, }; - let words = !cx.profile.fields().leaf.int64; Ok(PointerValue::StorePointer { to: Box::new(to), value: address(cx, val, &k, m)?, - words, }) } @@ -537,11 +505,9 @@ pub fn select( Some(Type::Int(b @ 1..=64)) => *b, _ => return Err(refuse(AccessCause::PointerInteger)), }; - let words = !cx.profile.fields().leaf.int64; Ok(Some(PointerValue::ToInt { of: address(cx, *v, &k, m)?, bits, - words, })) } InstKind::Store { @@ -682,100 +648,6 @@ fn null_thread_source(cx: &EmitCx<'_>, v: ValueId) -> bool { ) } -/// A 64-bit Metal address: a `u64`, or its two words without `shaderInt64`. -#[derive(Clone, Copy, Debug)] -enum Address { - U64(SValue), - Words(Pair), -} - -fn zero(fb: &mut FunctionBuilder<'_>, words: bool) -> BResult
{ - Ok(if words { - let z = k32(fb, 0)?; - Address::Words(Pair { lo: z, hi: z }) - } else { - Address::U64(k64(fb, 0)?) - }) -} - -fn mismatch(cx: &mut EmitCx<'_>) -> crate::spirv::error::BuildError { - cx.fail("a Metal address in two forms") -} - -fn add( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - a: Address, - b: Address, -) -> BResult
{ - match (a, b) { - (Address::U64(x), Address::U64(y)) => Ok(Address::U64(fb.binary(BinOp::IAdd, x, y)?)), - (Address::Words(x), Address::Words(y)) => Ok(Address::Words(wide::add(fb, x, y)?)), - _ => Err(mismatch(cx)), - } -} - -fn pick( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - c: SValue, - a: Address, - b: Address, -) -> BResult
{ - match (a, b) { - (Address::U64(x), Address::U64(y)) => Ok(Address::U64(fb.select(c, x, y)?)), - (Address::Words(x), Address::Words(y)) => Ok(Address::Words(wide::sel(fb, c, x, y)?)), - _ => Err(mismatch(cx)), - } -} - -/// The displacement `start + zext((m − start) mod 2³²)` the `u32` offset `m` stands for. -fn displacement( - fb: &mut FunctionBuilder<'_>, - m: SValue, - start: i64, - words: bool, -) -> BResult
{ - if !words { - return Ok(Address::U64(psb::displacement(fb, m, start)?)); - } - let z = k32(fb, 0)?; - if start == 0 { - return Ok(Address::Words(Pair { lo: m, hi: z })); - } - // The two's-complement bits of `start` are its value modulo 2³² and 2⁶⁴. - let low = k32(fb, start as u32)?; - let rel = fb.binary(BinOp::ISub, m, low)?; - let high = k32(fb, ((start as u64) >> 32) as u32)?; - Ok(Address::Words(wide::add( - fb, - Pair { lo: low, hi: high }, - Pair { lo: rel, hi: z }, - )?)) -} - -/// Buffer slot `slot`'s Metal address ([`slot_address`]) in the address form. -fn guest_base( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - slot: SlotRef, - words: bool, -) -> BResult
{ - if !words { - return Ok(Address::U64(slot_address(cx, fb, slot)?)); - } - let v = cx.push_field(fb, PushField::SlotGuestBase(slot))?; - let word = wide::split(fb, v)?; - if !biased(cx) { - return Ok(Address::Words(word)); - } - let bias = Pair { - lo: k32(fb, super::SLOT_ADDRESS_BIAS as u32)?, - hi: k32(fb, 0)?, - }; - Ok(Address::Words(wide::add(fb, word, bias)?)) -} - /// Whether buffer slots' `SlotGuestBase` words are their Metal addresses less /// [`SLOT_ADDRESS_BIAS`](super::SLOT_ADDRESS_BIAS), as the runtime pushes them. A replay variant /// reads each slot's address itself from its root entry. @@ -783,8 +655,7 @@ fn biased(cx: &EmitCx<'_>) -> bool { !cx.plan.families.access.replay } -/// Buffer slot `slot`'s `SlotGuestBase` word (a `uvec2`, low word first) as a `u64` (needs -/// `shaderInt64`). +/// Buffer slot `slot`'s `SlotGuestBase` word (a `uvec2`, low word first) as a `u64`. fn slot_word(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, slot: SlotRef) -> BResult { let v = cx.push_field(fb, PushField::SlotGuestBase(slot))?; let u64_ = fb.module().ty(SType::Int { @@ -795,7 +666,7 @@ fn slot_word(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, slot: SlotRef) - } /// Buffer slot `slot`'s Metal address, the bound buffer's `gpuAddress` plus the bind offset, as a -/// `u64` (needs `shaderInt64`): its `SlotGuestBase` word, plus +/// `u64`: its `SlotGuestBase` word, plus /// [`SLOT_ADDRESS_BIAS`](super::SLOT_ADDRESS_BIAS) where the word is biased ([`biased`]), added to /// the low word with the carry into the high word (`psb::add_slot_offset`). Made once, before the /// body ([`make_ahead`]). What a pointer compare, a converted or stored pointer, and an access @@ -846,19 +717,19 @@ pub(super) fn direct_base( cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, slot: SlotRef, -) -> BResult { +) -> BResult { let (lo, hi) = ( SlotMemo::DirectBase(slot, false), SlotMemo::DirectBase(slot, true), ); if let (Some(lo), Some(hi)) = (cx.recall_slot(fb, lo), cx.recall_slot(fb, hi)) { - return Ok(Pair { lo, hi }); + return Ok(psb::Pair { lo, hi }); } if !biased(cx) { return Err(cx.fail("a direct access of a slot whose SlotGuestBase word is not biased")); } let v = cx.push_field(fb, PushField::SlotGuestBase(slot))?; - let base = wide::split(fb, v)?; + let base = psb::split(fb, v)?; cx.remember_slot(fb, lo, base.lo); cx.remember_slot(fb, hi, base.hi); Ok(base) @@ -886,42 +757,32 @@ fn window_start(cx: &mut EmitCx<'_>, slot: usize) -> BResult<(SlotRef, i64)> { Ok((choice.slot, start)) } -/// The Metal address of `a` in the open block. -fn emit_address( - cx: &mut EmitCx<'_>, - fb: &mut FunctionBuilder<'_>, - a: &Addr, - words: bool, -) -> BResult
{ +/// The Metal address of `a` (a `u64`) in the open block. +fn emit_address(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, a: &Addr) -> BResult { match a { - Addr::Null => zero(fb, words), - Addr::Wide(p) => { - if words { - return Err(cx.fail("a wide pointer's address in two words")); - } - // A wide pointer is the address it holds. - Ok(Address::U64(cx.operand(fb, *p)?)) - } + Addr::Null => k64(fb, 0), + // A wide pointer is the address it holds. + Addr::Wide(p) => cx.operand(fb, *p), Addr::Static(s) => { let fat = cx.operand(fb, s.ptr)?; let root = fat_part(fb, fat, 0)?; let m = fat_part(fb, fat, 1)?; let mut acc = if s.null { - Some(displacement(fb, m, s.start.unwrap_or(0), words)?) + Some(psb::displacement(fb, m, s.start.unwrap_or(0))?) } else { None }; for &(slot, r) in &s.targets { let (slot, window) = window_start(cx, slot)?; - let base = guest_base(cx, fb, slot, words)?; - let d = displacement(fb, m, s.start.unwrap_or(window), words)?; - let here = add(cx, fb, base, d)?; + let base = slot_address(cx, fb, slot)?; + let d = psb::displacement(fb, m, s.start.unwrap_or(window))?; + let here = fb.binary(BinOp::IAdd, base, d)?; acc = Some(match acc { None => here, Some(prev) => { let rk = k32(fb, r)?; let is = fb.binary(BinOp::IEqual, root, rk)?; - pick(cx, fb, is, here, prev)? + fb.select(is, here, prev)? } }); } @@ -959,32 +820,21 @@ fn offset_value(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, o: Offset) -> } } -/// Address `a` truncated to `i`, held as its value family holds it: an `i1` as a `bool` (the -/// low bit), up to 32 bits zero-extended in a `u32`, a wider integer masked in a `u64` or, in two -/// words, as `Held::Wide`. -fn truncated(fb: &mut FunctionBuilder<'_>, a: Address, bits: u8) -> BResult { - let low = match a { - Address::U64(x) if bits > 32 => { - if bits == 64 { - return Ok(x); - } - let m = k64(fb, (1u64 << bits) - 1)?; - return fb.binary(BinOp::BitwiseAnd, x, m); +/// Address `x` (a `u64`) truncated to `i`, held as its value family holds it: an `i1` as a +/// `bool` (the low bit), up to 32 bits zero-extended in a `u32`, a wider integer masked in a `u64`. +fn truncated(fb: &mut FunctionBuilder<'_>, x: SValue, bits: u8) -> BResult { + if bits > 32 { + if bits == 64 { + return Ok(x); } - Address::Words(p) if bits > 32 => { - let f = wide::wide_form(bits, 1); - let p = wide::mask_top(fb, f, p)?; - return wide::join(fb, f, p); - } - Address::U64(x) => { - let u32_ = fb.module().ty(SType::Int { - width: 32, - signed: false, - })?; - fb.convert(ConvOp::UConvert, x, u32_)? - } - Address::Words(p) => p.lo, - }; + let m = k64(fb, (1u64 << bits) - 1)?; + return fb.binary(BinOp::BitwiseAnd, x, m); + } + let u32_ = fb.module().ty(SType::Int { + width: 32, + signed: false, + })?; + let low = fb.convert(ConvOp::UConvert, x, u32_)?; match bits { 1 => { let one = k32(fb, 1)?; @@ -1000,14 +850,6 @@ fn truncated(fb: &mut FunctionBuilder<'_>, a: Address, bits: u8) -> BResult, a: Address) -> BResult { - match a { - Address::U64(x) => Ok(x), - Address::Words(p) => wide::join(fb, wide::wide_form(64, 1), p), - } -} - /// Emit pointer-value strategy `s`, defining value `vid`. pub fn emit( cx: &mut EmitCx<'_>, @@ -1039,27 +881,17 @@ pub fn emit( } fb.binary(predicate_op(*pred), x, y)? } - PointerValue::CompareAddresses { pred, a, b, words } => { - let x = emit_address(cx, fb, a, *words)?; - let y = emit_address(cx, fb, b, *words)?; - match (x, y) { - (Address::U64(x), Address::U64(y)) => fb.binary(predicate_op(*pred), x, y)?, - (Address::Words(x), Address::Words(y)) => { - let f = wide::wide_form(64, 1); - let x = wide::join(fb, f, x)?; - let y = wide::join(fb, f, y)?; - wide::int_compare(fb, *pred, f, x, y)? - } - _ => return Err(mismatch(cx)), - } + PointerValue::CompareAddresses { pred, a, b } => { + let x = emit_address(cx, fb, a)?; + let y = emit_address(cx, fb, b)?; + fb.binary(predicate_op(*pred), x, y)? } - PointerValue::ToInt { of, bits, words } => { - let a = emit_address(cx, fb, of, *words)?; + PointerValue::ToInt { of, bits } => { + let a = emit_address(cx, fb, of)?; truncated(fb, a, *bits)? } - PointerValue::StorePointer { to, value, words } => { - let a = emit_address(cx, fb, value, *words)?; - let v = address_value(fb, a)?; + PointerValue::StorePointer { to, value } => { + let v = emit_address(cx, fb, value)?; match &**to { Source::Static(to) => { let p = cx.operand(fb, to.ptr)?; diff --git a/crates/metal2vulkan/src/lower/access/psb.rs b/crates/metal2vulkan/src/lower/access/psb.rs index d9de5faaf..23d6a38dc 100644 --- a/crates/metal2vulkan/src/lower/access/psb.rs +++ b/crates/metal2vulkan/src/lower/access/psb.rs @@ -46,7 +46,6 @@ use super::SLOT_ADDRESS_BIAS; use crate::device::DeviceProfile; -use crate::lower::arith::wide; use crate::memory::leaf::{k32, u32_op, Units, WordMem, WordOps}; use crate::spirv::builder::FunctionBuilder; use crate::spirv::error::BResult; @@ -62,19 +61,39 @@ fn u64_ty(fb: &mut FunctionBuilder<'_>) -> BResult { }) } +/// A `u64` as its two `u32` words, low word first. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Pair { + pub lo: Value, + pub hi: Value, +} + +/// The two words of `uvec2` `x`, low word first. +pub fn split(fb: &mut FunctionBuilder<'_>, x: Value) -> BResult { + Ok(Pair { + lo: fb.composite_extract(x, &[0])?, + hi: fb.composite_extract(x, &[1])?, + }) +} + /// A device address as a `u64`: `base` (its low and high words) plus the `u32` `offset` read as /// unsigned, added to the low word with the carry into the high word, so no 64-bit add takes a /// constant. One `OpIAddCarry`, its two words, one add of the carry, and the words joined. pub(super) fn add_slot_offset( fb: &mut FunctionBuilder<'_>, - base: wide::Pair, + base: Pair, offset: Value, ) -> BResult { let sum = fb.binary(BinOp::IAddCarry, base.lo, offset)?; let lo = fb.composite_extract(sum, &[0])?; let carry = fb.composite_extract(sum, &[1])?; let hi = fb.binary(BinOp::IAdd, base.hi, carry)?; - let words = wide::join(fb, wide::wide_form(64, 1), wide::Pair { lo, hi })?; + let u32_ = fb.module().ty(Type::Int { + width: 32, + signed: false, + })?; + let uvec2 = fb.module().ty(Type::Vector { elem: u32_, len: 2 })?; + let words = fb.composite_construct(uvec2, &[lo, hi])?; let address = u64_ty(fb)?; fb.convert(ConvOp::Bitcast, words, address) } @@ -163,7 +182,7 @@ enum Reach { /// ([`add_slot_offset`]); the base's words are made once where they dominate /// (`pointer::direct_base`). The address holds the binder's alignment /// (`RuntimeFact::AddressAlignment`), the first field. - Direct(u32, wide::Pair), + Direct(u32, Pair), } /// Prepare an access of a static slot at the `u32` displacement `m` from its bind offset, read as @@ -197,7 +216,7 @@ pub fn prepare_at(fb: &mut FunctionBuilder<'_>, address: Value, m: Value) -> BRe /// buffer lies within 2^31 bytes of each bind address in it, the runtime making no buffer longer /// than 2 GiB (`metal2vulkan_runtime::MAX_BUFFER_LENGTH`), so the offset is exact whatever the /// slot's window. Nothing is rounded. The check, where the access takes one, is `emit::prepare`'s. -pub fn prepare_direct(base: wide::Pair, m: Value, held: u32) -> PsbAccess { +pub fn prepare_direct(base: Pair, m: Value, held: u32) -> PsbAccess { PsbAccess { mem: PsbMem { reach: Reach::Direct(held, base), diff --git a/crates/metal2vulkan/src/lower/access/table.rs b/crates/metal2vulkan/src/lower/access/table.rs index 728ddf2e6..46a621fbe 100644 --- a/crates/metal2vulkan/src/lower/access/table.rs +++ b/crates/metal2vulkan/src/lower/access/table.rs @@ -30,8 +30,7 @@ fn shape_type(mb: &mut ModuleBuilder, sh: FieldShape) -> BResult { })?; match sh { FieldShape::U32 => Ok(u32_), - // Only address fields are 64-bit; they are placed only where device addresses (and - // `shaderInt64`) are. + // Only address fields are 64-bit. FieldShape::U64 => mb.ty(Type::Int { width: 64, signed: false, diff --git a/crates/metal2vulkan/src/lower/arith/aggregate.rs b/crates/metal2vulkan/src/lower/arith/aggregate.rs index 32e8c974f..4998a13ab 100644 --- a/crates/metal2vulkan/src/lower/arith/aggregate.rs +++ b/crates/metal2vulkan/src/lower/arith/aggregate.rs @@ -733,17 +733,10 @@ fn emit_build(cx: &mut EmitCx<'_>, fb: &mut FunctionBuilder<'_>, b: &Build) -> B } fb.composite_extract(x, path) } - Build::Const(k) => { - let k = if cx.plan.families.arith.wide { - legal::widen_const(k.clone()) - } else { - k.clone() - }; - match super::materialize(fb, &k)? { - Some(x) => Ok(x), - None => Err(cx.fail("a member constant arith does not materialize")), - } - } + Build::Const(k) => match super::materialize(fb, k)? { + Some(x) => Ok(x), + None => Err(cx.fail("a member constant arith does not materialize")), + }, Build::Zero(d) => zero_value(cx, fb, d), Build::Parts { ty, parts } => { let mut xs = Vec::with_capacity(parts.len()); diff --git a/crates/metal2vulkan/src/lower/arith/chunk.rs b/crates/metal2vulkan/src/lower/arith/chunk.rs index 4acf87af8..da75a2cad 100644 --- a/crates/metal2vulkan/src/lower/arith/chunk.rs +++ b/crates/metal2vulkan/src/lower/arith/chunk.rs @@ -22,12 +22,6 @@ //! moves as its format bits, a 64-bit lane as a word pair), so no 64-bit integer is needed //! for the move itself. //! -//! - **Two-word lanes**: without `shaderInt64` a chunk of 64-bit integer lanes is their wide -//! representation (a `uvec2` for a one-lane chunk, else a struct of the low-word and high-word -//! vectors), a lane-wise operation is the wide lowering's per chunk (`wide::select_in`), a lane -//! move moves both words of the lane, a dynamic index of 64 bits reads its low word (an index of -//! `2^32` or more is out of range), and a bitcast takes the lane's words as they are. -//! //! - **`dot`** of chunked vectors sums each chunk's `OpDot` (a product for a one-lane chunk) in //! `f32` and rounds a narrow result once; **`sincos`** of one takes each chunk's sine and //! cosine, and its cosine is stored as one chunked leaf (`memory::leaf`). @@ -42,7 +36,7 @@ use crate::error::Error; use crate::lower::arith::legal::{self, chunk_lanes, not_lowered, Form, Held}; use crate::lower::arith::libm::Lib; use crate::lower::arith::math::{self, FloatFn}; -use crate::lower::arith::{narrow, operands_of, ops, wide, ArithStrategy}; +use crate::lower::arith::{narrow, operands_of, ops, ArithStrategy}; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; use crate::spirv::builder::FunctionBuilder; @@ -68,9 +62,8 @@ impl Shape { } } - /// Where lane `i` lives: its member path, or, for a lane of two words inside a vector of two - /// or more lanes, the paths of its low and high words. - fn path(self, i: u32) -> LanePath { + /// Where lane `i` lives: its member path (the value itself when empty). + fn path(self, i: u32) -> Vec { let (mut prefix, size, j) = if self.chunked { let c = i / 4; let sizes = chunk_lanes(u32::from(self.lanes)); @@ -78,17 +71,10 @@ impl Shape { } else { (Vec::new(), u8::try_from(self.lanes).unwrap_or(1), i) }; - if size == 1 { - return LanePath::Whole(prefix); + if size > 1 { + prefix.push(j); } - if matches!(self.held, Held::Wide { .. }) { - let mut hi = prefix.clone(); - prefix.extend([0, j]); - hi.extend([1, j]); - return LanePath::Words(prefix, hi); - } - prefix.push(j); - LanePath::Whole(prefix) + prefix } /// The form of one lane. @@ -109,8 +95,7 @@ impl Shape { } } -/// The shape of AIR type `ty` on the profile (64-bit integer lanes as two words without -/// `shaderInt64`), or the refusal of one arith does not hold. +/// The shape of AIR type `ty` on the profile, or the refusal of one arith does not hold. pub(super) fn shape_of(cx: &SelectCx<'_>, ty: AirTypeId) -> Result { if let Some((held, lanes)) = legal::chunked(cx.entry.module.types(), ty) { let held = legal::held_on(cx.profile, held)?; @@ -121,7 +106,7 @@ pub(super) fn shape_of(cx: &SelectCx<'_>, ty: AirTypeId) -> Result chunked: true, }); } - let f = legal::wide_form_on(cx.entry, cx.profile, ty)?; + let f = legal::form_on(cx.entry, cx.profile, ty)?; Ok(Shape { held: f.held, lanes: u16::from(f.lanes), @@ -129,14 +114,6 @@ pub(super) fn shape_of(cx: &SelectCx<'_>, ty: AirTypeId) -> Result }) } -/// Where one lane of a scalar, vector, or chunked value lives ([`Shape::path`]). -enum LanePath { - /// The member at this path (the value itself when empty). - Whole(Vec), - /// A two-word lane: its low word and its high word, each a component of a word vector. - Words(Vec, Vec), -} - /// Whether `ty` is a chunked vector type. fn is_chunked(cx: &SelectCx<'_>, ty: AirTypeId) -> bool { legal::chunked(cx.entry.module.types(), ty).is_some() @@ -183,14 +160,13 @@ fn lanes_of(cx: &SelectCx<'_>, inst: &Inst) -> Option { .map(|(_, n)| n) } -/// The integer form of a dynamic lane index `v` (a held integer, or two words, of which the low -/// one names the lane: an index of `2^32` or more is out of range), or a refusal. +/// The integer form of a dynamic lane index `v` (a held integer), or a refusal. fn index_form(cx: &SelectCx<'_>, v: Value) -> Result { let t = cx .value_ty(v) .ok_or_else(|| cx.invariant("a lane index without a type"))?; - let f = legal::wide_form_on(cx.entry, cx.profile, t)?; - if !(f.is_int() || f.is_wide()) || f.lanes != 1 { + let f = legal::form_on(cx.entry, cx.profile, t)?; + if !f.is_int() || f.lanes != 1 { return Err(not_lowered()); } Ok(f) @@ -325,16 +301,10 @@ pub fn select( // (`dot`) is not lowered per chunk. return Err(not_lowered()); } - // Chunks of two-word lanes are the wide lowering's. - let wide_lanes = wide::involved_chunked(cx, inst); let mut parts: Vec<(u8, ArithStrategy)> = Vec::new(); for k in chunk_lanes(n) { if parts.iter().all(|(s, _)| *s != k) { - let part = if wide_lanes { - wide::select_in(cx, at, inst, Some(k))? - } else { - super::select_in(cx, at, inst, Some(k), m)? - }; + let part = super::select_in(cx, at, inst, Some(k), m)?; parts.push((k, part)); } } @@ -534,39 +504,16 @@ pub enum LaneMove { Shuffle, } -/// Words to read a two-word lane ([`lane`]): two `OpCompositeExtract` of at most 3 indices (7 -/// words each) and the `uvec2` construct (5). -const WIDE_READ: u32 = 2 * 7 + 5; -/// Words to write a two-word lane ([`with_lane`]): its split (two 1-index extracts, 5 words each) -/// and two `OpCompositeInsert` of at most 3 indices (8 each). -const WIDE_WRITE: u32 = 2 * 5 + 2 * 8; -/// A two-word lane's share of building a vector ([`build`]): its split (10 words), its -/// constituent in the low-word and high-word constructs (2), and at most half of a 2-lane -/// chunk's two construct headers, join, and member constituent (`(2 * 3 + 5 + 1) / 2`). -const WIDE_BUILD: u32 = 2 * 5 + 2 + 6; -/// Words per lane of a dynamic index: the lane constant (4), `OpIEqual` (5), `OpSelect` (6). -const PICK: u32 = 4 + 5 + 6; - /// An upper estimate of the SPIR-V words of lane move `m` on shape `s` (dynamic: by a dynamic -/// index), from the emission below. A lane held whole is one extract or insert (the flat bounds); a -/// two-word lane is read, written, and gathered word by word (19, 26, and 18 words, and 15 per lane -/// of a dynamic index), each move with 8 words of slack for a new type. +/// index), from the emission below: a lane is held whole, so a constant move is one extract or +/// insert. pub fn move_words(s: Shape, m: LaneMove, dynamic: bool) -> u32 { let n = s.lanes; - if !matches!(s.held, Held::Wide { .. }) { - return match (m, dynamic) { - (LaneMove::Extract | LaneMove::Insert, false) => 8, - (LaneMove::Extract, true) => lane_words(n, 24), - (LaneMove::Insert, true) => lane_words(n, 40), - (LaneMove::Shuffle, _) => lane_words(n, 16), - }; - } match (m, dynamic) { - (LaneMove::Extract, false) => WIDE_READ + 8, - (LaneMove::Insert, false) => WIDE_WRITE + 8, - (LaneMove::Extract, true) => lane_words(n, WIDE_READ + PICK) + 8, - (LaneMove::Insert, true) => lane_words(n, WIDE_READ + PICK + WIDE_BUILD) + 8, - (LaneMove::Shuffle, _) => lane_words(n, WIDE_READ + WIDE_BUILD) + 8, + (LaneMove::Extract | LaneMove::Insert, false) => 8, + (LaneMove::Extract, true) => lane_words(n, 24), + (LaneMove::Insert, true) => lane_words(n, 40), + (LaneMove::Shuffle, _) => lane_words(n, 16), } } @@ -585,17 +532,13 @@ fn operand_error() -> BuildError { } } -/// Lane `i` of `v` (shape `s`) as a scalar (a two-word lane as its `uvec2`). +/// Lane `i` of `v` (shape `s`) as a scalar. fn lane(fb: &mut FunctionBuilder<'_>, s: Shape, v: SValue, i: u32) -> BResult { - match s.path(i) { - LanePath::Whole(p) if p.is_empty() => Ok(v), - LanePath::Whole(p) => fb.composite_extract(v, &p), - LanePath::Words(lo, hi) => { - let lo = fb.composite_extract(v, &lo)?; - let hi = fb.composite_extract(v, &hi)?; - wide::join(fb, s.lane_form(), wide::Pair { lo, hi }) - } + let p = s.path(i); + if p.is_empty() { + return Ok(v); } + fb.composite_extract(v, &p) } /// `v` (shape `s`) with lane `i` replaced by scalar `x`. @@ -606,15 +549,11 @@ fn with_lane( i: u32, x: SValue, ) -> BResult { - match s.path(i) { - LanePath::Whole(p) if p.is_empty() => Ok(x), - LanePath::Whole(p) => fb.composite_insert(x, v, &p), - LanePath::Words(lo, hi) => { - let w = wide::split(fb, x)?; - let v = fb.composite_insert(w.lo, v, &lo)?; - fb.composite_insert(w.hi, v, &hi) - } + let p = s.path(i); + if p.is_empty() { + return Ok(x); } + fb.composite_insert(x, v, &p) } /// Every lane of `v` (shape `s`) as a scalar. @@ -626,28 +565,14 @@ fn lanes(fb: &mut FunctionBuilder<'_>, s: Shape, v: SValue) -> BResult, held: Held, xs: &[SValue]) -> BResult { let lanes = u8::try_from(xs.len()).map_err(|_| operand_error())?; if lanes == 1 { return xs.first().copied().ok_or_else(operand_error); } - let f = Form { held, lanes }; - if !f.is_wide() { - let t = ops::ty(fb, f)?; - return fb.composite_construct(t, xs); - } - let t = ops::ty(fb, wide::words_form(lanes))?; - let (mut los, mut his) = (Vec::with_capacity(xs.len()), Vec::with_capacity(xs.len())); - for x in xs { - let w = wide::split(fb, *x)?; - los.push(w.lo); - his.push(w.hi); - } - let lo = fb.composite_construct(t, &los)?; - let hi = fb.composite_construct(t, &his)?; - wide::join(fb, f, wide::Pair { lo, hi }) + let t = ops::ty(fb, Form { held, lanes })?; + fb.composite_construct(t, xs) } /// The value of shape `s` with scalar lanes `xs`. @@ -668,16 +593,6 @@ fn build(fb: &mut FunctionBuilder<'_>, s: Shape, xs: &[SValue]) -> BResult, index: Form, i: SValue) -> BResult<(Form, SValue)> { - if index.is_wide() { - Ok((wide::words_form(1), wide::low_word(fb, i)?)) - } else { - Ok((index, i)) - } -} - /// Emit a lane-wise operation per chunk: `parts` holds the operation per chunk size, `wide` /// which operands are chunked. pub fn emit_chunked( @@ -734,7 +649,6 @@ pub fn extract( (Some(i), _) => lane(fb, src, v, i), (None, Some(f)) => { let i = xs.get(1).copied().ok_or_else(operand_error)?; - let (f, i) = index_value(fb, f, i)?; let ls = lanes(fb, src, v)?; pick(fb, f, i, &ls) } @@ -756,7 +670,6 @@ pub fn insert( (Some(i), _) => with_lane(fb, dst, v, i, e), (None, Some(f)) => { let i = xs.get(2).copied().ok_or_else(operand_error)?; - let (f, i) = index_value(fb, f, i)?; let mut ls = lanes(fb, dst, v)?; for (k, l) in ls.iter_mut().enumerate() { let kk = ops::splat(fb, f, k as u64)?; @@ -800,7 +713,6 @@ const FRAGMENT_LANES: usize = 2; fn fragment_shape(s: Shape) -> bool { s.chunked && s.lanes == 64 - && !matches!(s.held, Held::Wide { .. }) && chunk_lanes(u32::from(s.lanes)) .first() .is_some_and(|&k| usize::from(k) >= FRAGMENT_LANES) @@ -877,11 +789,6 @@ fn words_of(fb: &mut FunctionBuilder<'_>, s: Shape, v: SValue) -> BResult { - words.push(fb.composite_extract(x, &[0])?); - words.push(fb.composite_extract(x, &[1])?); - } (64, _) => { let pair = ops::ty( fb, @@ -950,12 +857,7 @@ fn from_words(fb: &mut FunctionBuilder<'_>, s: Shape, ws: &[SValue]) -> BResult< }, )?; let p = fb.composite_construct(pair, &[lo, hi])?; - // A two-word lane is the pair itself. - xs.push(if lane.is_wide() { - p - } else { - fb.convert(ConvOp::Bitcast, p, lt)? - }); + xs.push(fb.convert(ConvOp::Bitcast, p, lt)?); } (32, Held::Float(_)) => { let w = next.next().ok_or_else(operand_error)?; diff --git a/crates/metal2vulkan/src/lower/arith/legal.rs b/crates/metal2vulkan/src/lower/arith/legal.rs index 52ffb2c89..307d67d6d 100644 --- a/crates/metal2vulkan/src/lower/arith/legal.rs +++ b/crates/metal2vulkan/src/lower/arith/legal.rs @@ -1,20 +1,18 @@ //! Value legality: how every non-pointer AIR value is held in SPIR-V. //! -//! The representation depends on the AIR type and one profile bit, `shaderInt64`; constants are -//! selected without a profile and widened where emission's plan holds words ([`widen_const`]). -//! Otherwise the profile only decides whether a representation is available ([`check`]): +//! The representation depends on the AIR type alone; constants are selected without a profile. The +//! profile only decides whether a representation is available ([`check`]): //! //! - `i1` is `bool`; every other integer is held **zero-extended** in an unsigned 32-bit -//! container (`i2`..`i32`) or 64-bit container (`i33`..`i64`), or, without `shaderInt64`, as -//! two `u32` words ([`Held::Wide`], [`widen`], `super::wide`). The bits above the AIR width are +//! container (`i2`..`i32`) or 64-bit container (`i33`..`i64`). The bits above the AIR width are //! zero in every value that is not poison, so an operation that can set them (add, sub, mul, //! shl, signed results) masks its result, and a signed operation sign-extends its operands //! first. An add, sub, mul or shl the AIR marks `nuw` in a container is not masked: its only //! results that would set them are poison (`super::ops::int_binary`; a loop counter's //! increment is one, and a masked latch hides the loop's trip count from the driver). Where a //! value must be defined although its operand is poison, it is masked: `freeze`, the bytes a -//! store writes (`memory::leaf`), a narrow atomic's operand, and a bitcast's packed lanes. The -//! two-word form keeps its masks. `i8`/`i16` therefore never need `Int8`/`Int16`. +//! store writes (`memory::leaf`), a narrow atomic's operand, and a bitcast's packed lanes. +//! `i8`/`i16` therefore never need `Int8`/`Int16`. //! - `float` is `f32` and `double` is `f64` (needs `shaderFloat64`, else refused). `half` and //! `bfloat` are **held widened** in an `f32` that is always exactly a value of the narrow format, //! on every profile ([`super::narrow`]): no profile needs `shaderFloat16`, and a constant @@ -68,13 +66,6 @@ pub enum Held { container: u8, }, Float(FloatFmt), - /// An `i` (33 to 64 bits) held zero-extended as two `u32` words, low word first, on a - /// profile without `shaderInt64` ([`super::wide`]): a scalar is a `uvec2`, a vector of `n` - /// lanes a struct of two `u32` vectors of `n` lanes (the low words, then the high words). Only - /// [`wide_form_on`] produces it; [`form_on`] keeps refusing such a type. - Wide { - bits: u8, - }, } /// A float format and its container. @@ -228,16 +219,11 @@ impl Form { Held::Float(f) => ScalarTy::Float { bits: f.container(), }, - // The element of each of its two words. - Held::Wide { .. } => ScalarTy::Int { bits: 32 }, } } /// The lowered representation. pub fn demote(self) -> DemoteTy { - if let Held::Wide { .. } = self.held { - return wide_demote(self.lanes); - } if self.lanes == 1 { DemoteTy::Scalar(self.scalar()) } else { @@ -257,18 +243,17 @@ impl Form { pub fn bits(self) -> u8 { match self.held { Held::Bool => 1, - Held::Int { bits, .. } | Held::Wide { bits } => bits, + Held::Int { bits, .. } => bits, Held::Float(f) => f.bits(), } } - /// The container width in bits (a wide integer's two words are 64 bits). + /// The container width in bits. pub fn container(self) -> u8 { match self.held { Held::Bool => 1, Held::Int { container, .. } => container, Held::Float(f) => f.container(), - Held::Wide { .. } => 64, } } @@ -284,11 +269,6 @@ impl Form { matches!(self.held, Held::Float { .. }) } - /// An integer held as two words. - pub fn is_wide(self) -> bool { - matches!(self.held, Held::Wide { .. }) - } - /// An integer held in a container wider than its AIR width. pub fn legalized(self) -> bool { matches!(self.held, Held::Int { bits, container } if bits < container) @@ -322,76 +302,6 @@ impl Form { } } -/// The representation of a wide integer of `lanes` lanes: a `uvec2` (low, high) for a scalar, else -/// a struct of the low-word vector and the high-word vector. -pub fn wide_demote(lanes: u8) -> DemoteTy { - let word = ScalarTy::Int { bits: 32 }; - if lanes == 1 { - DemoteTy::Vector { elem: word, len: 2 } - } else { - let v = DemoteTy::Vector { - elem: word, - len: lanes, - }; - DemoteTy::Composite(vec![v.clone(), v].into()) - } -} - -/// `d` with every 64-bit integer scalar or vector replaced by its wide representation. -pub fn widen(d: &DemoteTy) -> DemoteTy { - match d { - DemoteTy::Scalar(ScalarTy::Int { bits: 64 }) => wide_demote(1), - DemoteTy::Vector { - elem: ScalarTy::Int { bits: 64 }, - len, - } => wide_demote(*len), - DemoteTy::Composite(parts) => DemoteTy::Composite(parts.iter().map(widen).collect()), - other => other.clone(), - } -} - -/// Constant `k` with every 64-bit integer scalar or vector in its wide representation. -pub fn widen_const(k: LoweredConst) -> LoweredConst { - let word = ScalarTy::Int { bits: 32 }; - let lo = |b: u64| b & 0xFFFF_FFFF; - let hi = |b: u64| b >> 32; - match k { - LoweredConst::Scalar { - ty: ScalarTy::Int { bits: 64 }, - bits, - } => LoweredConst::Vector { - elem: word, - lanes: vec![lo(bits), hi(bits)].into(), - }, - LoweredConst::Vector { - elem: ScalarTy::Int { bits: 64 }, - lanes, - } => { - let n = u8::try_from(lanes.len()).unwrap_or(u8::MAX); - LoweredConst::Composite { - ty: wide_demote(n), - parts: vec![ - LoweredConst::Vector { - elem: word, - lanes: lanes.iter().map(|b| lo(*b)).collect(), - }, - LoweredConst::Vector { - elem: word, - lanes: lanes.iter().map(|b| hi(*b)).collect(), - }, - ] - .into(), - } - } - LoweredConst::Composite { ty, parts } => LoweredConst::Composite { - ty: widen(&ty), - parts: parts.into_vec().into_iter().map(widen_const).collect(), - }, - LoweredConst::Undef(d) => LoweredConst::Undef(widen(&d)), - other => other, - } -} - impl LoweredConst { /// The lowered representation of the constant. pub fn demote(&self) -> DemoteTy { @@ -428,7 +338,7 @@ pub fn held_of(t: &Type) -> Option { } /// Whether AIR type `ty` is an integer or 2-4-lane integer vector of 33 to 64 bits: a type held -/// in a 64-bit container, or as two words without `shaderInt64`. +/// in a 64-bit container. pub fn is_wide_int(types: &TypeTable, ty: AirTypeId) -> bool { match types.get(ty) { Some(Type::Int(33..=64)) => true, @@ -582,18 +492,12 @@ pub fn bool_lanes(types: &TypeTable, ty: AirTypeId) -> Option { } } -/// Whether profile `p` can hold scalar `s`: 64-bit integers need `shaderInt64`, 64-bit floats -/// `shaderFloat64` (both refused naming the feature). No lowered representation is a 16-bit float -/// (narrow floats are held widened), so one is not this family's. +/// Whether profile `p` can hold scalar `s`: 64-bit floats need `shaderFloat64` (refused naming +/// the feature). No lowered representation is a 16-bit float (narrow floats are held widened), so +/// one is not this family's. pub fn check_scalar(p: &DeviceProfile, s: ScalarTy) -> Result<(), Error> { - let leaf = &p.fields().leaf; match s { - ScalarTy::Int { bits: 64 } if !leaf.int64 => Err(Unsupported::needs( - Feature::Int64Arithmetic, - Capability::Feature(VkFeature::ShaderInt64), - ) - .into()), - ScalarTy::Float { bits: 64 } if !leaf.float64 => Err(Unsupported::needs( + ScalarTy::Float { bits: 64 } if !p.fields().leaf.float64 => Err(Unsupported::needs( Feature::Float64Arithmetic, Capability::Feature(VkFeature::ShaderFloat64), ) @@ -619,19 +523,6 @@ pub fn form_on(e: &Entry, p: &DeviceProfile, ty: AirTypeId) -> Result bool { - !p.fields().leaf.int64 -} - -/// [`form_on`], except that an integer of 33 to 64 bits is [`Held::Wide`] on a profile without -/// `shaderInt64`. Only families that lower the wide form call it; every other family keeps refusing -/// such a type through [`form_on`]. -pub fn wide_form_on(e: &Entry, p: &DeviceProfile, ty: AirTypeId) -> Result { - let f = form_of(e.module.types(), ty)?; - Ok(f.with(held_on(p, f.held)?)) -} - /// Refuse a 64-bit integer (a scalar or 2-4-lane vector of AIR type `ty`) as a stage interface /// value of entry `e`. Metal's compiler rejects `long` and `ulong` as a vertex attribute, a varying /// (flat or not), a color output or input, and a stage builtin ("type 'long' is not valid for @@ -669,20 +560,11 @@ pub fn refuse_bfloat_color(e: &Entry, ty: AirTypeId) -> Result<(), Error> { ))) } -/// How profile `p` holds an element held as `h` profile-independently: an integer of 33 to 64 -/// bits as [`Held::Wide`] without `shaderInt64`, anything else as it is once `p` can hold its -/// scalar ([`check_scalar`]). The element of a chunked vector takes its form here. +/// Element form `h`, once profile `p` can hold its scalar ([`check_scalar`]). The element of a +/// chunked vector takes its form here. pub fn held_on(p: &DeviceProfile, h: Held) -> Result { - match h { - Held::Int { - bits, - container: 64, - } if holds_wide(p) => Ok(Held::Wide { bits }), - _ => { - check_scalar(p, Form { held: h, lanes: 1 }.scalar())?; - Ok(h) - } - } + check_scalar(p, Form { held: h, lanes: 1 }.scalar())?; + Ok(h) } // ---- Constants ---- diff --git a/crates/metal2vulkan/src/lower/arith/mod.rs b/crates/metal2vulkan/src/lower/arith/mod.rs index 95b540f63..e0ba83ef7 100644 --- a/crates/metal2vulkan/src/lower/arith/mod.rs +++ b/crates/metal2vulkan/src/lower/arith/mod.rs @@ -16,11 +16,8 @@ //! [`lowered_type`] is what `select` demotes block-crossing values and phis to and what it requires //! of terminator operands, [`constant`] is which constants lowering materializes, and //! [`spirv_type`] and [`materialize`] are their emission. The representation depends on the AIR -//! type and `shaderInt64` only: `i1` is `bool`, other integers are held zero-extended in a 32- or -//! 64-bit unsigned container (so `i8`/`i16`/`i2`/`i40` need no narrow capability), `i33`..`i64` as -//! two `u32` words without `shaderInt64` ([`wide`]: every operation on them is -//! `ArithStrategy::Wide`, per chunk in a chunked vector; division unrolled without a loop), `float` -//! and `double` are native (`f64` needs `shaderFloat64`), and `half` and `bfloat` are held widened +//! type only: `i1` is `bool`, other integers are held zero-extended in a 32- or 64-bit unsigned +//! container (so `i8`/`i16`/`i2`/`i40` need no narrow capability), `float` and `double` are native (`f64` needs `shaderFloat64`), and `half` and `bfloat` are held widened //! in an `f32` that is always a value of the narrow format ([`narrow`]): each operation rounds its //! `f32` result back to the format, so no profile needs `shaderFloat16`; where the device's 16-bit //! `+ - *`, kept apart, is Metal's `half` arithmetic and the profile has `shaderFloat16`, a `half` @@ -83,7 +80,6 @@ pub mod output_precision; pub mod pack; pub mod srgb; pub mod texel_round; -pub mod wide; #[cfg(test)] mod tests; @@ -122,42 +118,24 @@ use ops::{BitcastPlan, CastKind}; /// lowered value of `ty` has, which is always demotable. A type this family does not lower yet is /// `Unsupported{Lowering(Arith), NotImplemented}`; a type that needs a capability the profile lacks /// is a typed refusal naming it. -/// -/// On a profile without `shaderInt64` every 64-bit integer scalar or vector is held as two words -/// ([`legal::widen`]), each chunk of a chunked vector of them too. pub fn lowered_type(e: &Entry, p: &DeviceProfile, ty: AirTypeId) -> Result { - let mut d = demote_of(e.module.types(), ty)?; - if legal::holds_wide(p) { - d = legal::widen(&d); - } + let d = demote_of(e.module.types(), ty)?; check(p, &d)?; Ok(d) } -/// `v` as a constant lowering materializes, in its profile-independent representation (64-bit -/// integers native). It is `Some` only for constants of a type [`lowered_type`] lowers on some -/// profile; `select` checks the profile. Emission materializes [`constant_in`]. +/// `v` as a constant lowering materializes, in its lowered representation. It is `Some` only for +/// constants of a type [`lowered_type`] lowers on some profile; `select` checks the profile. +/// Emission materializes it. pub fn constant(e: &Entry, v: Value) -> Option { let Value::Const(c) = v else { return None }; legal::lower_const(e, c) } -/// [`constant`] in the representation of the plan's profile: 64-bit integers as two words where -/// the plan holds them so. -pub fn constant_in(e: &Entry, plan: &ArithPlan, v: Value) -> Option { - let k = constant(e, v)?; - Some(if plan.wide { legal::widen_const(k) } else { k }) -} - -/// [`constant`] in lowered representation `d`: the constant itself, or its wide form when `d` is -/// the wide representation of its type; `None` when neither is `d`. +/// [`constant`], when its lowered representation is `d`; `None` otherwise. pub fn constant_as(e: &Entry, v: Value, d: &DemoteTy) -> Option { let k = constant(e, v)?; - if k.demote() == *d { - return Some(k); - } - let w = legal::widen_const(k); - (w.demote() == *d).then_some(w) + (k.demote() == *d).then_some(k) } /// The SPIR-V type of lowered representation `ty`, or `None` for one this family does not @@ -385,9 +363,6 @@ pub enum ArithStrategy { elem: Form, contract: Contraction, }, - /// An operation with a wide integer operand or result on a profile without `shaderInt64`, - /// on the two words of each value ([`wide`]). - Wide(wide::WideOp), /// An `insertvalue` or `extractvalue` whose result is an aggregate that holds a pointer: no /// SPIR-V value ([`aggregate`]). PointerAggregate, @@ -504,7 +479,6 @@ impl FamilyStrategy for ArithStrategy { S::LaneShuffle { fragment: true, .. } => "arith.shuffle.fragment", S::LaneShuffle { .. } => "arith.shuffle.chunked", S::WordBitcast { .. } => "arith.bitcast.chunked", - S::Wide(w) => w.name(), S::PointerAggregate => "arith.aggregate.pointer", S::Handle(_) => "arith.aggregate.handle", S::Forward(_) => "arith.aggregate.forward", @@ -616,7 +590,6 @@ impl FamilyStrategy for ArithStrategy { } => chunk::fragment_shuffle_words(*out), S::LaneShuffle { out, .. } => chunk::move_words(*out, chunk::LaneMove::Shuffle, false), S::WordBitcast { from, to } => chunk::bitcast_words(*from, *to), - S::Wide(w) => w.words(), } } @@ -693,11 +666,6 @@ pub struct ArithPlan { /// The widths whose `SignedZeroInfNanPreserve` execution mode the entry declares: those of /// `preserve` the profile supports. pub modes: BTreeSet, - /// Whether 64-bit integers are held as two words (the profile lacks `shaderInt64`), so emission - /// materializes their constants in that form ([`constant_in`]). - pub wide: bool, - /// The shared division routines the wide divisions call, each defined once by [`declare`]. - pub divides: BTreeSet, /// The value each forwarding `extractvalue` reads ([`aggregate::forwarded`]), and the /// member-wise phi each member extraction reads. pub forwards: BTreeMap, @@ -762,10 +730,7 @@ pub fn routine_words(plan: &ArithPlan) -> impl Iterator, m: &mut Meter) -> Result<(), Error> { - cx.families.arith.wide = legal::holds_wide(cx.profile); cx.families.arith.quantize = narrow::quantize_form(cx.profile); cx.families.arith.native_half = narrow::native_rounding(cx.families.arith.quantize).is_some(); // Under the float controls a `half`'s NaN is the device's conversion's. @@ -814,19 +778,16 @@ pub fn finish(cx: &mut SelectCx<'_>, m: &mut Meter) -> Result<(), Error> { Ok(()) } -/// The arith family's module-scope objects: the shared wide division routines and precise -/// `fmod`'s routine (the `GLSL.std.450` import is the serializer's, and constants are -/// interned where they are used). +/// The arith family's module-scope objects: precise `fmod`'s routine (the `GLSL.std.450` import is +/// the serializer's, and constants are interned where they are used). #[derive(Clone, Debug, Default)] pub struct Declared { - /// The function of each of the plan's [`ArithPlan::divides`]. - pub divides: BTreeMap, /// Precise `fmod`'s routine, when [`ArithPlan::fmod`]. pub fmod: Option, } -/// Declare the arith family's module-scope objects and entry execution modes: one function per -/// shared division routine the plan calls, and one `SignedZeroInfNanPreserve` per width the plan +/// Declare the arith family's module-scope objects and entry execution modes: precise `fmod`'s +/// routine where the plan calls it, and one `SignedZeroInfNanPreserve` per width the plan /// selected. pub fn declare( mb: &mut ModuleBuilder, @@ -837,9 +798,6 @@ pub fn declare( modes.push(ExecMode::SignedZeroInfNanPreserve { width: *w }); } let mut decl = Declared::default(); - for d in &plan.families.arith.divides { - decl.divides.insert(*d, wide::define_divide(mb, *d)?); - } if plan.families.arith.fmod { decl.fmod = Some(libm::define_fmod(mb)?); } @@ -1189,9 +1147,6 @@ pub fn select( if chunk::involved(cx, inst) { return chunk::select(cx, at, inst, m); } - if wide::involved(cx, inst) { - return wide::select(cx, at, inst); - } select_in(cx, at, inst, None, m) } @@ -1250,8 +1205,7 @@ fn select_in( return select_call(cx, at, inst, call, chunk, m); } let mut ops = operands_of(&inst.kind); - // A constant element index is a literal of the instruction, never a materialized value (an - // `i64` index needs no `shaderInt64`). + // A constant element index is a literal of the instruction, never a materialized value. if let InstKind::ExtractElement { idx, .. } | InstKind::InsertElement { idx, .. } = &inst.kind { if matches!(idx, Value::Const(_)) { ops.retain(|v| v != idx); @@ -2616,7 +2570,6 @@ fn arity(s: &ArithStrategy) -> Option { | S::Null(_) | S::Member { .. } => Some(0), S::Chunked { parts, .. } => parts.first().and_then(|(_, p)| arity(p)), - S::Wide(w) => w.arity(), _ => None, } } @@ -2792,16 +2745,6 @@ fn value( } S::IntFn { f, form } => math::int_fn(fb, *f, *form, xs)?, S::IntFnBy { f, k, form } => math::funnel_by(fb, *f, *form, *k, xs)?, - S::Wide(w) => { - let routine = match w.routine() { - Some(d) => match cx.decl.families.arith.divides.get(&d) { - Some(f) => Some(*f), - None => return Err(cx.fail("a wide division whose routine is not declared")), - }, - None => None, - }; - wide::emit(fb, w, xs, routine)? - } S::FloatFn { f, form, contract } => { let lib = lib(cx); math::float_fn(fb, *f, *form, *contract, xs, &lib)? diff --git a/crates/metal2vulkan/src/lower/arith/ops.rs b/crates/metal2vulkan/src/lower/arith/ops.rs index 6b53eb7e3..652999c91 100644 --- a/crates/metal2vulkan/src/lower/arith/ops.rs +++ b/crates/metal2vulkan/src/lower/arith/ops.rs @@ -22,7 +22,7 @@ pub fn ones(bits: u8) -> u64 { } } -/// The SPIR-V element type of `h` (a wide integer's: its words'). +/// The SPIR-V element type of `h`. pub fn elem_ty(fb: &mut FunctionBuilder<'_>, h: Held) -> BResult { fb.module().ty(match h { Held::Bool => Type::Bool, @@ -30,33 +30,14 @@ pub fn elem_ty(fb: &mut FunctionBuilder<'_>, h: Held) -> BResult { width: container, signed: false, }, - Held::Wide { .. } => Type::Int { - width: 32, - signed: false, - }, Held::Float(f) => Type::Float { width: f.container(), }, }) } -/// The SPIR-V type of `f` (a wide integer's: [`super::legal::wide_demote`]). +/// The SPIR-V type of `f`. pub fn ty(fb: &mut FunctionBuilder<'_>, f: Form) -> BResult { - if f.is_wide() { - let words = f.with(Held::Int { - bits: 32, - container: 32, - }); - let w = ty(fb, words)?; - return if f.lanes == 1 { - fb.module().ty(Type::Vector { elem: w, len: 2 }) - } else { - fb.module().ty(Type::Struct { - members: vec![w, w].into(), - layout: None, - }) - }; - } let e = elem_ty(fb, f.held)?; if f.lanes == 1 { Ok(e) @@ -68,11 +49,26 @@ pub fn ty(fb: &mut FunctionBuilder<'_>, f: Form) -> BResult { } } +/// The low word of 64-bit integer `x` (a GEP's index word). +pub fn low_word(fb: &mut FunctionBuilder<'_>, x: Value) -> BResult { + let u = fb.module().ty(Type::Int { + width: 32, + signed: false, + })?; + fb.convert(ConvOp::UConvert, x, u) +} + +/// `u32` value `w` zero-extended to integer form `f` (a 32- or 64-bit container). +pub fn zext_word(fb: &mut FunctionBuilder<'_>, f: Form, w: Value) -> BResult { + if f.container() == 32 { + return Ok(w); + } + let t = ty(fb, f)?; + fb.convert(ConvOp::UConvert, w, t) +} + /// The constant of form `f` with `bits` (in the container) in every lane. pub fn splat(fb: &mut FunctionBuilder<'_>, f: Form, bits: u64) -> BResult { - if f.is_wide() { - return super::wide::splat(fb, f, bits); - } let e = elem_ty(fb, f.held)?; let bits = match f.held { Held::Bool => bits & 1, diff --git a/crates/metal2vulkan/src/lower/arith/tests.rs b/crates/metal2vulkan/src/lower/arith/tests.rs index ce121ca94..6bc6d0df2 100644 --- a/crates/metal2vulkan/src/lower/arith/tests.rs +++ b/crates/metal2vulkan/src/lower/arith/tests.rs @@ -149,15 +149,6 @@ fn const_of(fb: &mut FunctionBuilder<'_>, ty: TypeId, bits: u64) -> BResult, f: Form, buf: GlobalId, at: Value, k: u32) -> BResult { - if f.is_wide() { - // Two words per lane, low first. - let mut ws = Vec::new(); - for j in 0..2 * u32::from(f.lanes) { - let p = word_ptr(fb, buf, at, k + j)?; - ws.push(fb.load(p, MemAccess::default())?); - } - return super::wide::from_words(fb, f, &ws); - } let lane = f.scalar_form(); let et = ops::ty(fb, lane)?; let mut lanes = Vec::new(); @@ -218,14 +209,6 @@ fn store( v: Value, lanes: bool, ) -> BResult<()> { - if f.is_wide() { - let ws = super::wide::to_words(fb, f, v)?; - for (j, w) in ws.into_iter().enumerate() { - let p = word_ptr(fb, buf, at, j as u32)?; - fb.store(p, w, MemAccess::default())?; - } - return Ok(()); - } let lane = f.scalar_form(); let u32_ = u32_ty(fb.module())?; // A narrow vector encodes once, as the memory leaf's store does; with `lanes`, each lane is @@ -378,16 +361,16 @@ fn kernel_defs( Ok(m) } -/// A committed profile with 64-bit integers and floats and 16-bit floats (for L3). +/// A committed profile with 64-bit floats and 16-bit floats (for L3). fn wide_profile() -> DeviceProfile { let all = committed_profiles().expect("profiles"); all.into_iter() .map(|(_, p)| p) .find(|p| { let l = &p.fields().leaf; - l.int64 && l.float64 && l.float16 + l.float64 && l.float16 }) - .expect("a committed profile with int64, float64, and float16") + .expect("a committed profile with float64 and float16") } /// One case: per operand, per lane, the held bits. @@ -4125,6 +4108,7 @@ fn aggregate_leaf_total_is_capped_before_expansion() { mod atan2; mod bicubic; +mod chunk; mod color_write; mod convert_suffix; mod divide; @@ -4136,7 +4120,6 @@ mod pack; mod round_texel; mod specials; mod texel_round; -mod wide; /// `air.convert` from an integer to `bool` is C++'s `x != 0`, lane by lane, at every width and /// whatever the source's sign: the values that differ from the low bit (2, 0x80, the top bit) are diff --git a/crates/metal2vulkan/src/lower/arith/tests/chunk.rs b/crates/metal2vulkan/src/lower/arith/tests/chunk.rs new file mode 100644 index 000000000..294cffdd2 --- /dev/null +++ b/crates/metal2vulkan/src/lower/arith/tests/chunk.rs @@ -0,0 +1,213 @@ +//! Word bounds of the lane moves on chunked vectors (`chunk::move_words`, +//! `chunk::fragment_shuffle_words`, `chunk::bitcast_words`) against what they emit. + +use super::*; + +/// The word bound of each lane move on a chunked vector covers what it emits, for 64-bit and 32-bit +/// lanes: constant and dynamic (32-bit and 64-bit index) extracts and inserts, shuffles, and word +/// bitcasts of 64-bit lanes to 32-bit lanes and back, at 5, 6, and 8 lanes (chunks of 4 and 1, 4 +/// and 2, and two of 4). +#[test] +fn chunked_lane_moves_bound_their_emission() { + use super::super::chunk::{self, Shape}; + use super::super::ArithStrategy as S; + use crate::lower::strategy::FamilyStrategy; + use crate::spirv::serialize::serialize; + let size = |ins: &[Form], out: Form, body: Body<'_>| -> usize { + let m = kernel(ins, out, body).expect("build"); + serialize(m).expect("serialize").words.len() + }; + let check = |what: &str, s: &S, with: usize, without: usize| { + let bound = s.words() as usize; + assert!( + with - without <= bound, + "{what}: {} words above the kernel, bound {bound}", + with - without + ); + }; + for lane in [int(64), int(32)] { + let four = Shape { + held: lane.held, + lanes: 4, + chunked: false, + }; + let v4 = vec(lane, 4); + for n in [5u16, 6, 8] { + let s = Shape { + held: lane.held, + lanes: n, + chunked: true, + }; + let what = |m: &str| format!("{m} {lane:?} x {n}"); + let all: Vec = (0..u32::from(n)).collect(); + // The chunked operand, from the first two (4-lane) operands. + let make = |fb: &mut FunctionBuilder<'_>, x: &[Value]| { + chunk::shuffle(fb, four, four, s, &all, &x[..2]) + }; + // Lane 0 of a chunked value, as the kernel's output. + let first = + |fb: &mut FunctionBuilder<'_>, v: Value| chunk::extract(fb, s, Some(0), None, &[v]); + let unmoved = |ins: &[Form]| { + size(ins, lane, &|fb, x| { + let v = make(fb, x)?; + first(fb, v) + }) + }; + // Constant moves of lane 1, which lives in a 4-lane chunk. + let ins = [v4, v4, lane]; + let kept = size(&ins, lane, &|fb, x| { + make(fb, x)?; + Ok(x[2]) + }); + let with = size(&ins, lane, &|fb, x| { + let v = make(fb, x)?; + chunk::extract(fb, s, Some(1), None, &[v]) + }); + let extract = S::LaneExtract { + src: s, + at: Some(1), + index: None, + }; + check(&what("extract"), &extract, with, kept); + let with = size(&ins, lane, &|fb, x| { + let v = make(fb, x)?; + let r = chunk::insert(fb, s, Some(1), None, &[v, x[2]])?; + first(fb, r) + }); + let insert = S::LaneInsert { + dst: s, + at: Some(1), + index: None, + }; + check(&what("insert"), &insert, with, unmoved(&ins)); + // Dynamic moves. + for index in [int(32), int(64)] { + let ins = [v4, v4, lane, index]; + let kept = size(&ins, lane, &|fb, x| { + make(fb, x)?; + Ok(x[2]) + }); + let with = size(&ins, lane, &|fb, x| { + let v = make(fb, x)?; + chunk::extract(fb, s, None, Some(index), &[v, x[3]]) + }); + let extract = S::LaneExtract { + src: s, + at: None, + index: Some(index), + }; + check(&what("dynamic extract"), &extract, with, kept); + let with = size(&ins, lane, &|fb, x| { + let v = make(fb, x)?; + let r = chunk::insert(fb, s, None, Some(index), &[v, x[2], x[3]])?; + first(fb, r) + }); + let insert = S::LaneInsert { + dst: s, + at: None, + index: Some(index), + }; + check(&what("dynamic insert"), &insert, with, unmoved(&ins)); + } + // A shuffle of every lane from both operands. + let ins = [v4, v4]; + let mask: Box<[u32]> = (0..u32::from(n)) + .map(|i| (i * 5 + 3) % (2 * u32::from(n))) + .collect(); + let with = size(&ins, lane, &|fb, x| { + let v = make(fb, x)?; + let r = chunk::shuffle(fb, s, s, s, &mask, &[v, v])?; + first(fb, r) + }); + let shuffle = S::LaneShuffle { + a: s, + b: s, + out: s, + mask: mask.clone(), + fragment: false, + }; + check(&what("shuffle"), &shuffle, with, unmoved(&ins)); + // Word bitcasts of 64-bit lanes to twice as many 32-bit lanes and back. + if lane.bits() == 64 { + let words = Shape { + held: int(32).held, + lanes: 2 * n, + chunked: true, + }; + let with = size(&ins, lane, &|fb, x| { + let v = make(fb, x)?; + let u = chunk::bitcast(fb, s, words, v)?; + let r = chunk::bitcast(fb, words, s, u)?; + first(fb, r) + }); + let there = S::WordBitcast { from: s, to: words }; + let back = S::WordBitcast { from: words, to: s }; + let bound = (there.words() + back.words()) as usize; + let emitted = with - unmoved(&ins); + assert!( + emitted <= bound, + "{}: {emitted} words above the kernel, bound {bound}", + what("bitcast and back") + ); + } + } + } +} + +/// A shuffle into a simdgroup matrix's fragment (64 lanes held whole) emits no more than its bound, +/// `chunk::fragment_shuffle_words`, for a merge taking lanes 0 and 1 from one operand and the rest +/// from the other, of 32-bit integer and of `float` lanes. +#[test] +fn a_fragment_shuffle_bounds_its_emission() { + use super::super::chunk::{self, Shape}; + use super::super::ArithStrategy as S; + use crate::lower::strategy::FamilyStrategy; + use crate::spirv::serialize::serialize; + let size = |ins: &[Form], out: Form, body: Body<'_>| -> usize { + let m = kernel(ins, out, body).expect("build"); + serialize(m).expect("serialize").words.len() + }; + for lane in [int(32), float(32)] { + let four = Shape { + held: lane.held, + lanes: 4, + chunked: false, + }; + let s = Shape { + held: lane.held, + lanes: 64, + chunked: true, + }; + let v4 = vec(lane, 4); + let ins = [v4, v4]; + let spread: Vec = (0..64).map(|i| i % 8).collect(); + let make = |fb: &mut FunctionBuilder<'_>, x: &[Value]| { + chunk::shuffle(fb, four, four, s, &spread, &x[..2]) + }; + let first = + |fb: &mut FunctionBuilder<'_>, v: Value| chunk::extract(fb, s, Some(0), None, &[v]); + let without = size(&ins, lane, &|fb, x| { + let v = make(fb, x)?; + first(fb, v) + }); + let mask: Box<[u32]> = [0, 1].into_iter().chain(66..128).collect(); + let with = size(&ins, lane, &|fb, x| { + let v = make(fb, x)?; + let r = chunk::shuffle_fragment(fb, s, s, s, &mask, &[v, v])?; + first(fb, r) + }); + let strategy = S::LaneShuffle { + a: s, + b: s, + out: s, + mask, + fragment: true, + }; + let bound = strategy.words() as usize; + assert!( + with - without <= bound, + "{lane:?}: {} words above the kernel, bound {bound}", + with - without + ); + } +} diff --git a/crates/metal2vulkan/src/lower/arith/tests/wide.rs b/crates/metal2vulkan/src/lower/arith/tests/wide.rs deleted file mode 100644 index 5f046a914..000000000 --- a/crates/metal2vulkan/src/lower/arith/tests/wide.rs +++ /dev/null @@ -1,1638 +0,0 @@ -//! Interpreter differential tests of wide integers held as two words. -//! -//! Operands and results cross the kernel boundary as their two words per lane (the parent's -//! `load`/`store` go through `wide::from_words`/`wide::to_words`), so the word composition is -//! checked by every test. Every kernel also passes L3 on `vk12-floor`, which has no -//! `shaderInt64` (a float64 kernel only on the parent's 64-bit profile), built in the profile's -//! `half` rounding form (it has no `shaderFloat16`): the sequences need no 64-bit integer. -//! References are the parent's LLVM and Metal definitions. - -use super::super::wide::{self as w, WideOp}; -use super::*; - -fn wide(bits: u8) -> Form { - Form { - held: Held::Wide { bits }, - lanes: 1, - } -} - -/// The committed profile without `shaderInt64` the sequences are validated on. -fn floor() -> DeviceProfile { - committed_profiles() - .expect("profiles") - .into_iter() - .find(|(n, _)| n == "runtime-floor") - .map(|(_, p)| p) - .expect("runtime-floor") -} - -/// [`check_accept`] after L3 on `vk12-floor` (unless a form needs 64-bit floats), the module there -/// built in the profile's `half` rounding form. -fn check_wide( - what: &str, - ins: &[Form], - out: Form, - body: Body<'_>, - cases: &[Case], - reference: &dyn Fn(&Case) -> Option>, -) { - let f64_used = ins - .iter() - .chain(std::iter::once(&out)) - .any(|f| f.float_fmt() == Some(FloatFmt::F64)); - if !f64_used { - let p = floor(); - let q = crate::lower::arith::narrow::quantize_form(&p); - let m = kernel_defs( - ins, - out, - &|b| { - b.set_quantize_form(q); - Ok(Vec::new()) - }, - &|fb, xs, _| body(fb, xs), - false, - false, - ) - .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - assert_valid(m, &p); - } - check(what, ins, out, body, cases, reference, false); -} - -const WIDE_WIDTHS: [u8; 4] = [33, 40, 63, 64]; - -/// Wide binary operator `op` on form `f`: a division through its routine, defined in the -/// kernel's module as `arith::declare` defines it. -fn wide_bin( - fb: &mut FunctionBuilder<'_>, - op: AirBin, - f: Form, - a: Value, - b: Value, -) -> BResult { - match op { - AirBin::UDiv | AirBin::URem | AirBin::SDiv | AirBin::SRem => { - let r = w::define_divide(fb.module(), w::Divide::of(f))?; - w::divide(fb, op, f, a, b, r) - } - _ => w::binary(fb, op, f, a, b), - } -} - -#[test] -fn wide_operators_match_llvm() { - let mut rng = Rng(0xD95); - for bits in WIDE_WIDTHS { - let vals = int_values(bits, &mut rng, 5); - let mut shifts = vals.clone(); - shifts.extend([0, 1, 5, 31, 32, 33, 47, u64::from(bits) - 1]); - let f = wide(bits); - for op in INT_OPS { - let b: &[u64] = if matches!(op, AirBin::Shl | AirBin::LShr | AirBin::AShr) { - &shifts - } else { - &vals - }; - check_wide( - &format!("{op:?} wide i{bits}"), - &[f, f], - f, - &|fb, x| wide_bin(fb, op, f, x[0], x[1]), - &pairs(&vals, b), - &|c| Some(vec![llvm_int(op, bits, arg(c, 0), arg(c, 1))?]), - ); - } - } -} - -#[test] -fn wide_operators_on_vectors_work_per_lane() { - let f = vec(wide(64), 3); - let big = 0x8000_0000_0000_0000u64; - let cases: Vec = vec![ - vec![vec![u64::MAX, big, 7], vec![3, u64::MAX, 2]], - vec![ - vec![0x1_0000_0000, 0xFFFF_FFFF, big + 5], - vec![0x1_0000_0001, 33, 63], - ], - vec![vec![12345678901234, 1, 0], vec![1000000007, 64 - 1, 5]], - vec![ - vec![big + 12345, u64::MAX - 3, 0x1234_5678_9ABC], - vec![1, 32, 45], - ], - ]; - for op in [ - AirBin::Add, - AirBin::Sub, - AirBin::Mul, - AirBin::UDiv, - AirBin::SRem, - AirBin::Shl, - AirBin::AShr, - ] { - check_wide( - &format!("{op:?} <3 x i64> wide"), - &[f, f], - f, - &|fb, x| wide_bin(fb, op, f, x[0], x[1]), - &cases, - &|c| { - (0..3) - .map(|l| llvm_int(op, 64, c[0][l], c[1][l])) - .collect::>>() - }, - ); - } -} - -/// The divisors of the division tests: 0, 1, the maximum, every power of two and its neighbours -/// (every normalization shift, with the divisor's high word zero or not), and words where Knuth's -/// digit estimate needs one or two corrections (a normalized divisor whose low digit is large, a -/// dividend whose top digits equal the divisor's). -fn division_edges(bits: u8) -> Vec { - let m = mask(bits); - let mut v = vec![0, 1, 2, 3, 5, 7, 10, m, m - 1, m >> 1]; - for k in 0..u32::from(bits) { - let p = 1u64 << k; - v.extend([p, p - 1]); - } - v.extend( - division_hard_words() - .into_iter() - .flat_map(|w| [w, w << 16, w << 32]), - ); - let mut v: Vec = v.into_iter().map(|x| x & m).collect(); - v.sort_unstable(); - v.dedup(); - v -} - -/// Words that exercise the digit corrections and the normalization of the compact division. -fn division_hard_words() -> Vec { - [ - 0x7FFFu64, - 0x8000, - 0xFFFF, - 0x8000_0001, - 0xFFFF_0001, - 0xFFFF_8000, - 0x7FFF_8000, - 0x8000_7FFF, - 0xFFFE_FFFF, - 0x1_FFFF_FFFF, - 0x7FFF_8000_0000_0000, - 0x8000_0000_FFFF_FFFF, - 0xFFFF_FFFF_0000_0001, - 0x0123_4567_89AB_CDEF, - ] - .into_iter() - .collect() -} - -/// The dividends of the division tests: fewer than the divisors (every case is an interpreter -/// invocation), still 0, 1, the maximum, the powers of two around each word and digit boundary, -/// and the hard words. -fn division_dividends(bits: u8) -> Vec { - let m = mask(bits); - let mut v = vec![0, 1, 2, 3, 10, m, m - 1, m >> 1]; - for k in [16u32, 32, 33, 48, u32::from(bits) - 1] { - let p = 1u64 << k; - v.extend([p, p - 1, p + 1]); - } - v.extend(division_hard_words().into_iter().flat_map(|w| [w, w << 32])); - let mut v: Vec = v.into_iter().map(|x| x & m).collect(); - v.sort_unstable(); - v.dedup(); - v -} - -/// Dividend and divisor pairs whose quotient digit estimate is two too large, one for each -/// divisor class (below `2^32` or not, and the leading zeros of its top word, 0 to 31 in the -/// classes that have one): without the second correction of a quotient digit they divide -/// wrongly (found by a model of the sequence over random operands). -const SECOND_CORRECTION: [(u64, u64); 32] = [ - (0x44a_d6a2_6348_b40a, 0x83b2_fc96), - (0x4_7092_9a68_38f9, 0x47b4_6deb), - (0x1_16fc_e100_959f, 0x2f0e_3da4), - (0x53a0_9b7a_d155, 0x151a_7ad8), - (0x2855_6768_36dc_97af, 0xa2c_aeb2), - (0x86a_7d74_5774, 0x483_afaf), - (0x187_05fd_e4db, 0x22d_ffd2), - (0x2087_20f0_6ab6_3bc7, 0x116_77fe), - (0x3be2_4fb9_7c35_2142, 0x82_89ca), - (0x14d_1d32_c8fa, 0x43_91fc), - (0x38_753b_3b1a, 0x20_aa77), - (0xaea_0c49_d010_1ff3, 0x10_74df), - (0x878a_c9d3_586e, 0x8_0f6a), - (0x47d_5b0a_a11b, 0x5_33e7), - (0x75_e312_3009_0b83, 0x2_1f3f), - (0xfaab_611a_5b45_4850, 0x1_3049_fd29_9750), - (0xf6fa_1c66_ab7d_1bb7, 0xa33a_ee6b_aebb), - (0xae6b_aa32_743c_1428, 0x4579_ffdf_dedb), - (0xf4cc_857c_5c9d_a040, 0x218b_7b57_a4da), - (0xf70a_a94d_ed97_d7ef, 0x131a_bbbf_b13b), - (0xf002_67b0_851f_2f1e, 0x82d_da0e_2912), - (0xcf4f_4587_30bd_f3e7, 0x403_e7fc_1967), - (0xe975_f96d_cc4c_7c78, 0x233_5f8b_61c7), - (0xe98f_203b_76a0_eddb, 0x103_4fd0_3252), - (0xba8f_2665_5944_ae5c, 0x80_1afa_f4fa), - (0xcfcb_e30c_130b_abd7, 0x41_28ef_d9e6), - (0xe744_c3ca_9abb_defd, 0x28_d23d_6e77), - (0xfae4_1bf8_0e0a_fb36, 0x10_6edc_2fc2), - (0xcaf4_6482_656d_ef1e, 0x8_004a_a235), - (0xf303_008c_5c66_c891, 0x4_8327_6e76), - (0xd650_48cd_ba4b_8bd7, 0x2_41ef_84f7), - (0xd3ce_0def_5105_de3c, 0x1_05bd_e8d7), -]; - -/// The compact division (Hacker's Delight `divdu` on 32-bit `OpUDiv`) is Rust's `u64` division (the -/// LLVM reference) on every pair of edge values, at 64 bits and at narrower wide widths, quotient -/// and remainder, signed and unsigned; and a zero divisor, undefined in LLVM, traps nowhere (the -/// interpreter traps a division by zero and an out-of-range shift) and divides by one. -#[test] -fn wide_division_matches_u64_division_on_edge_values() { - for bits in [64u8, 40, 33] { - let f = wide(bits); - let dividends = division_dividends(bits); - let (every, fewer) = ( - pairs(÷nds, &division_edges(bits)), - pairs(÷nds, ÷nds), - ); - for op in [AirBin::UDiv, AirBin::URem, AirBin::SDiv, AirBin::SRem] { - // Every divisor against the unsigned 64-bit routine; the sign handling and the - // narrower widths (zero-extended into the same routine) on fewer. - let cases = match (bits, op) { - (64, AirBin::UDiv | AirBin::URem) => &every, - (64, _) | (_, AirBin::UDiv | AirBin::SRem) => &fewer, - _ => continue, - }; - let reference = |c: &Case| { - let (a, b) = (arg(c, 0), arg(c, 1)); - if b == 0 { - // A zero divisor divides by one. - let q = matches!(op, AirBin::UDiv | AirBin::SDiv); - return Some(vec![if q { a } else { 0 }]); - } - Some(vec![llvm_int(op, bits, a, b)?]) - }; - let cases: Vec = if bits == 64 { - let corrections = SECOND_CORRECTION - .iter() - .map(|(a, b)| vec![vec![*a], vec![*b]]); - cases.iter().cloned().chain(corrections).collect() - } else { - cases.clone() - }; - // The interpreter bounds the steps of one run: at most a few thousand cases each. - for (i, part) in cases.chunks(3000).enumerate() { - let what = format!("{op:?} wide i{bits} on edge values, part {i}"); - let body: Body<'_> = &|fb, x| wide_bin(fb, op, f, x[0], x[1]); - if i == 0 { - check_wide(&what, &[f, f], f, body, part, &reference); - } else { - check(&what, &[f, f], f, body, part, &reference, false); - } - } - } - } -} - -/// On vectors each lane divides on its own, whichever of the division's two cases (a divisor below -/// `2^32` or not) its neighbours take. -#[test] -fn wide_division_mixes_its_cases_across_lanes() { - let edges = division_edges(64); - for lanes in [2u8, 4] { - let f = vec(wide(64), lanes); - let n = usize::from(lanes); - // Neighbouring lanes alternate between divisors below `2^32` (zero among them) and - // wider ones, over every dividend. - let (narrow, wider): (Vec, Vec) = edges.iter().partition(|d| *d >> 32 == 0); - let mut cases: Vec = Vec::new(); - for i in 0..edges.len() { - for flip in 0..2 { - let dividend = |l: usize| edges[(i * n + l * 37 + flip) % edges.len()]; - let divisor = |l: usize| { - let from = if (l + flip).is_multiple_of(2) { - &narrow - } else { - &wider - }; - from[(i * n + l) % from.len()] - }; - cases.push(vec![ - (0..n).map(dividend).collect(), - (0..n).map(divisor).collect(), - ]); - } - } - for op in [AirBin::UDiv, AirBin::URem] { - check_wide( - &format!("{op:?} <{lanes} x i64> wide on edge values"), - &[f, f], - f, - &|fb, x| wide_bin(fb, op, f, x[0], x[1]), - &cases, - &|c| { - (0..n) - .map(|l| match c[1][l] { - 0 if op == AirBin::UDiv => Some(c[0][l]), - 0 => Some(0), - b => llvm_int(op, 64, c[0][l], b), - }) - .collect::>>() - }, - ); - } - } -} - -#[test] -fn wide_comparisons_match_llvm() { - let mut rng = Rng(95); - for bits in [40, 64] { - let vals = int_values(bits, &mut rng, 4); - let f = wide(bits); - for pred in IntPredicate::ALL { - check_wide( - &format!("icmp {pred:?} wide i{bits}"), - &[f, f], - boolean(), - &|fb, x| w::int_compare(fb, pred, f, x[0], x[1]), - &pairs(&vals, &vals), - &|c| Some(vec![u64::from(llvm_icmp(pred, bits, arg(c, 0), arg(c, 1)))]), - ); - } - } - // Lane-wise on a vector. - let f = vec(wide(64), 2); - check_wide( - "icmp slt <2 x i64> wide", - &[f, f], - vec(boolean(), 2), - &|fb, x| w::int_compare(fb, IntPredicate::Slt, f, x[0], x[1]), - &[vec![vec![u64::MAX, 5], vec![0, 0x1_0000_0000]]], - &|_| Some(vec![1, 1]), - ); -} - -#[test] -fn integer_casts_to_and_from_wide_match_llvm() { - let mut rng = Rng(0xCA57); - let tr = |x: u64, to: Form| { - if to.is_bool() { - x & 1 - } else { - x & mask(to.bits()) - } - }; - // Truncations. - for (from, to) in [ - (wide(64), int(32)), - (wide(64), int(8)), - (wide(64), boolean()), - (wide(64), wide(40)), - (wide(40), int(16)), - (wide(33), int(32)), - ] { - let vals = int_values(from.bits(), &mut rng, 6); - let cases: Vec = vals.iter().map(|v| vec![vec![*v]]).collect(); - check_wide( - &format!("trunc {from:?} -> {to:?}"), - &[from], - to, - &|fb, x| w::cast(fb, CastKind::Trunc, from, to, x[0]), - &cases, - &|c| Some(vec![tr(arg(c, 0), to)]), - ); - } - // Extensions. - for (from, to) in [ - (int(32), wide(64)), - (int(8), wide(40)), - (int(31), wide(33)), - (boolean(), wide(64)), - (wide(40), wide(64)), - (wide(33), wide(63)), - ] { - let fb_bits = from.bits(); - let vals = if from.is_bool() { - vec![0, 1] - } else { - int_values(fb_bits, &mut rng, 6) - }; - let cases: Vec = vals.iter().map(|v| vec![vec![*v]]).collect(); - for kind in [CastKind::ZExt, CastKind::SExt] { - check_wide( - &format!("{kind:?} {from:?} -> {to:?}"), - &[from], - to, - &|fb, x| w::cast(fb, kind, from, to, x[0]), - &cases, - &|c| { - let x = arg(c, 0); - Some(vec![if kind == CastKind::SExt { - (sext(x, fb_bits) as u64) & mask(to.bits()) - } else { - x - }]) - }, - ); - } - } -} - -/// `x` (an exact integer magnitude below 2^64) rounded to nearest even at `keep` significant -/// bits, as an `f64` (exact: at most 53 bits are kept). -fn round_bits(x: u64, keep: u32) -> f64 { - if x == 0 { - return 0.0; - } - let msb = 63 - x.leading_zeros(); - if msb < keep { - return x as f64; - } - let shift = msb + 1 - keep; - let q = x >> shift; - let rem = x & ((1u64 << shift) - 1); - let half = 1u64 << (shift - 1); - let q = if rem > half || (rem == half && q & 1 == 1) { - q + 1 - } else { - q - }; - (q as f64) * 2f64.powi(shift as i32) -} - -#[test] -fn wide_to_float_rounds_once() { - let mut rng = Rng(0xF10A7); - for bits in [64, 40] { - let mut vals = int_values(bits, &mut rng, 12); - // Ties and near-ties of f32 and bfloat at several magnitudes. - for base in [1u64 << 24, 1 << 40, 1 << 62] { - for d in [0u64, 1, 2, 3, 0x7F, 0x80, 0x81, 0x8000, 0x8001] { - vals.push((base | d) & mask(bits)); - vals.push((base + (base >> 24) + d) & mask(bits)); - } - } - vals.sort_unstable(); - vals.dedup(); - let cases: Vec = vals.iter().map(|v| vec![vec![*v]]).collect(); - let f = wide(bits); - for signed in [false, true] { - for to in [float(32), float(16), bfloat(), float(64)] { - let kind = if signed { - CastKind::SiToFp - } else { - CastKind::UiToFp - }; - check_wide( - &format!("{kind:?} wide i{bits} -> {to:?}"), - &[f], - to, - &|fb, x| w::cast(fb, kind, f, to, x[0]), - &cases, - &|c| { - let x = arg(c, 0); - let (neg, m) = if signed && sext(x, bits) < 0 { - (true, sext(x, bits).unsigned_abs()) - } else { - (false, x) - }; - let keep = match to.float_fmt() { - Some(FloatFmt::F64) => 53, - Some(FloatFmt::F32) => 24, - Some(FloatFmt::BFloat) => 8, - _ => 11, - }; - // A half keeps 11 bits only below 2^16; above, it is infinite. - let v = round_bits(m, keep); - let v = if neg { -v } else { v }; - // A narrow result crosses the kernel as its format bits. - let c = to.const_bits(v); - Some(vec![to.float_fmt().map_or(c, |f| f.narrow_bits(c))]) - }, - ); - } - } - } -} - -/// A wide integer converts to `half` by integer arithmetic on its `f32`, with no `OpQuantizeToF16` -/// even where the module rounds by the device's quantize ([`QuantizeForm::Device`]), on the values -/// `integers_for_half` gives a 64-bit integer, plus `2^32` and `2^39` and their neighbours. -#[test] -fn wide_integers_round_to_half_without_quantize() { - for bits in [64u8, 40] { - let f = wide(bits); - let m = mask(bits); - let mut vals: Vec = super::narrow::integers_for_half(64) - .into_iter() - .map(|v| v & m) - .collect(); - for base in [1i64 << 32, 1 << 39] { - for d in -3i64..=3 { - vals.push((base + d) as u64 & m); - vals.push((-(base + d)) as u64 & m); - } - } - vals.sort_unstable(); - vals.dedup(); - let cases: Vec = vals.iter().map(|v| vec![vec![*v]]).collect(); - for (kind, signed) in [(CastKind::UiToFp, false), (CastKind::SiToFp, true)] { - let what = format!("{kind:?} wide i{bits} -> half"); - let body = - |fb: &mut FunctionBuilder<'_>, x: &[Value]| w::cast(fb, kind, f, float(16), x[0]); - let module = kernel_defs( - &[f], - float(16), - &|b| { - b.set_quantize_form(QuantizeForm::Device); - Ok(Vec::new()) - }, - &|fb, xs, _| body(fb, xs), - false, - false, - ) - .unwrap_or_else(|e| panic!("{what}: build: {e:?}")); - assert!( - !super::super::narrow::quantizes(&module), - "{what}: the module holds OpQuantizeToF16" - ); - check_wide(&what, &[f], float(16), &body, &cases, &|c| { - let x = arg(c, 0); - let v = if signed { - i128::from(sext(x, bits)) - } else { - i128::from(x) - }; - Some(vec![super::narrow::half_of_integer(v)]) - }); - } - } -} - -#[test] -fn float_to_wide_truncates_and_saturates() { - let vals: Vec = f32_values(); - let cases: Vec = vals.iter().map(|v| vec![vec![*v]]).collect(); - for bits in [64, 40] { - let to = wide(bits); - for signed in [false, true] { - // LLVM `fptoui`/`fptosi`: out of range (and NaN) is poison. - let kind = if signed { - CastKind::FpToSi - } else { - CastKind::FpToUi - }; - check_wide( - &format!("{kind:?} f32 -> wide i{bits}"), - &[float(32)], - to, - &|fb, x| w::cast(fb, kind, float(32), to, x[0]), - &cases, - &|c| { - let x = f64::from(f32v(arg(c, 0))).trunc(); - let (lo, hi) = if signed { - ( - -(2f64.powi(i32::from(bits) - 1)), - 2f64.powi(i32::from(bits) - 1), - ) - } else { - (0.0, 2f64.powi(i32::from(bits))) - }; - if !(x >= lo && x < hi) { - return None; - } - Some(vec![(x as i128 as u64) & mask(bits)]) - }, - ); - // `air.convert` saturates: NaN to 0, out of range to the bound. - check_wide( - &format!("convert saturating f32 -> wide i{bits} signed={signed}"), - &[float(32)], - to, - &|fb, x| { - w::convert( - fb, - ConvertKind::ToInt { - signed, - round: None, - }, - float(32), - to, - x[0], - ) - }, - &cases, - &|c| { - let x = f64::from(f32v(arg(c, 0))); - if x.is_nan() { - return Some(vec![0]); - } - let (lo, hi) = if signed { - (-(1i128 << (bits - 1)), (1i128 << (bits - 1)) - 1) - } else { - (0, (1i128 << bits) - 1) - }; - let t = x.trunc(); - let v = if t <= lo as f64 { - lo - } else if t >= hi as f64 { - hi - } else { - t as i128 - }; - Some(vec![(v as u64) & mask(bits)]) - }, - ); - } - } - // A half and a double source (the double on the 64-bit profile only). - let halves: Vec = [0x3C00u64, 0xBC00, 0x7BFF, 0xFBFF, 0x3800, 0x0001] - .iter() - .map(|h| vec![vec![*h]]) - .collect(); - check_wide( - "fptosi half -> wide i64", - &[float(16)], - wide(64), - &|fb, x| w::cast(fb, CastKind::FpToSi, float(16), wide(64), x[0]), - &halves, - &|c| { - let x = f16_to_f64(arg(c, 0) as u16).trunc(); - Some(vec![x as i64 as u64]) - }, - ); - let doubles: Vec = [1e18f64, -1e18, 12345.75, -0.5, 9.2e18, 1.8e19] - .iter() - .map(|d| vec![vec![d.to_bits()]]) - .collect(); - check_wide( - "fptoui f64 -> wide i64", - &[float(64)], - wide(64), - &|fb, x| w::cast(fb, CastKind::FpToUi, float(64), wide(64), x[0]), - &doubles, - &|c| { - let x = f64v(arg(c, 0)).trunc(); - (x >= 0.0 && x < 2f64.powi(64)).then(|| vec![x as u64]) - }, - ); -} - -/// Integer `median3` on wide values (two 32-bit words) answers the middle one of its operands, -/// signed and unsigned, on scalars and 4-lane vectors of 64 and 40 bits: every ordered triple of -/// the width's edges, ties and the extremes among them. -#[test] -fn wide_integer_median3_answers_the_middle_one_at_ties_and_extremes() { - for bits in [64u8, 40] { - let edges = width_edges(bits); - for s in [Sign::Signed, Sign::Unsigned] { - let op = IntFn::Median3(s); - for lanes in [1u8, 4] { - let f = vec(wide(bits), lanes); - check_wide( - &format!("{op:?} wide i{bits} x{lanes}"), - &[f; 3], - f, - &|fb, x| w::int_fn(fb, op, f, x), - &triples(&edges, usize::from(lanes)), - &|c| { - (0..usize::from(lanes)) - .map(|l| int_ref(op, bits, &[c[0][l], c[1][l], c[2][l]])) - .collect::>>() - }, - ); - } - } - } -} - -#[test] -fn wide_integer_functions_match_metal() { - let mut rng = Rng(0x1F); - for bits in [64, 33, 40, 48, 63] { - let f = wide(bits); - let vals = int_values(bits, &mut rng, 3); - let one: Vec = vals.iter().map(|v| vec![vec![*v]]).collect(); - let two = pairs(&vals, &vals); - // Every pair of values with a third drawn across the range (saturating results, large - // funnel amounts), plus the small cube. - let mut three: Vec = Vec::new(); - for (i, a) in vals.iter().enumerate() { - for (j, b) in vals.iter().enumerate() { - let c = vals[(i * 3 + j * 5) % vals.len()]; - three.push(vec![vec![*a], vec![*b], vec![c]]); - } - } - for a in vals.iter().take(4) { - for b in vals.iter().take(4) { - for c in vals.iter().take(4) { - three.push(vec![vec![*a], vec![*b], vec![*c]]); - } - } - } - let mut ops: Vec = vec![ - IntFn::Abs, - IntFn::Popcount, - IntFn::ReverseBits, - IntFn::Clz, - IntFn::Ctz, - ]; - if bits % 16 == 0 { - ops.push(IntFn::Bswap); - } - for s in [Sign::Signed, Sign::Unsigned] { - ops.extend([ - IntFn::AbsDiff(s), - IntFn::Min(s), - IntFn::Max(s), - IntFn::Min3(s), - IntFn::Max3(s), - IntFn::Median3(s), - IntFn::Clamp(s), - IntFn::AddSat(s), - IntFn::SubSat(s), - IntFn::HAdd(s), - IntFn::RHAdd(s), - IntFn::MulHi(s), - IntFn::MadHi(s), - IntFn::MadSat(s), - ]); - } - ops.extend([IntFn::Rotate, IntFn::Fshl, IntFn::Fshr]); - for op in ops { - assert!(w::int_fn_lowered(op, f), "{op:?} i{bits}"); - let cases = match op.arity() { - 1 => &one, - 2 => &two, - _ => &three, - }; - let ins = vec![f; op.arity()]; - check_wide( - &format!("{op:?} wide i{bits}"), - &ins, - f, - &|fb, x| w::int_fn(fb, op, f, x), - cases, - &|c| { - let a: Vec = c.iter().map(|l| l[0]).collect(); - // Clamp with lo > hi is undefined in Metal. - if let IntFn::Clamp(sg) = op { - let v = |x: u64| { - if sg == Sign::Signed { - i128::from(sext(x, bits)) - } else { - i128::from(x) - } - }; - if v(a[1]) > v(a[2]) { - return None; - } - } - Some(vec![int_ref(op, bits, &a)?]) - }, - ); - } - // Bit fields with 32-bit offset and count. - let (x, y) = ( - 0xF0E1_D2C3_B4A5_9687u64 & mask(bits), - 0x0123_4567_89AB_CDEFu64 & mask(bits), - ); - let mut ext = Vec::new(); - let mut ins = Vec::new(); - for (off, cnt) in [ - (0u64, u64::from(bits)), - (bits as u64 - 4, 4), - (4, 30), - (31, 2), - (17, 0), - (33, 5), - ] { - ext.push(vec![vec![x], vec![off], vec![cnt]]); - ins.push(vec![vec![x], vec![y], vec![off], vec![cnt]]); - } - for s in [Sign::Signed, Sign::Unsigned] { - let op = IntFn::ExtractBits(s); - check_wide( - &format!("{op:?} wide i{bits}"), - &[f, int(32), int(32)], - f, - &|fb, v| w::int_fn(fb, op, f, v), - &ext, - &|c| Some(vec![int_ref(op, bits, &[c[0][0], c[1][0], c[2][0]])?]), - ); - } - check_wide( - &format!("InsertBits wide i{bits}"), - &[f, f, int(32), int(32)], - f, - &|fb, v| w::int_fn(fb, IntFn::InsertBits, f, v), - &ins, - &|c| { - Some(vec![int_ref( - IntFn::InsertBits, - bits, - &[c[0][0], c[1][0], c[2][0], c[3][0]], - )?]) - }, - ); - } - // Lane-wise on a vector. - let f = vec(wide(64), 2); - check_wide( - "Popcount <2 x i64> wide", - &[f], - f, - &|fb, v| w::int_fn(fb, IntFn::Popcount, f, v), - &[vec![vec![u64::MAX, 0x8000_0000_0000_0001]]], - &|_| Some(vec![64, 2]), - ); -} - -#[test] -fn wide_bitcasts_and_integer_converts_move_bits() { - let x = 0xC3B4_A596_8778_6958u64; - let y = 0x0123_4567_89AB_CDEFu64; - let lanes = |v: u64, bits: u8, n: u8| -> Vec { - (0..n) - .map(|i| (v >> (u32::from(i) * u32::from(bits))) & mask(bits)) - .collect() - }; - for other in [ - vec(int(32), 2), - vec(float(32), 2), - vec(int(16), 4), - vec(int(8), 4), - ] { - let n = other.lanes; - let b = other.bits(); - if u32::from(b) * u32::from(n) != 64 { - continue; - } - check_wide( - &format!("bitcast wide i64 -> {other:?}"), - &[wide(64)], - other, - &|fb, v| w::bitcast(fb, wide(64), other, v[0]), - &[vec![vec![x]], vec![vec![y]]], - &|c| Some(lanes(arg(c, 0), b, n)), - ); - check_wide( - &format!("bitcast {other:?} -> wide i64"), - &[other], - wide(64), - &|fb, v| w::bitcast(fb, other, wide(64), v[0]), - &[vec![lanes(x, b, n)], vec![lanes(y, b, n)]], - &|c| { - Some(vec![c[0].iter().enumerate().fold(0u64, |acc, (i, l)| { - acc | (l << (i as u32 * u32::from(b))) - })]) - }, - ); - } - // Two wide lanes to four words, and a double. - check_wide( - "bitcast <2 x i64> wide -> <4 x i32>", - &[vec(wide(64), 2)], - vec(int(32), 4), - &|fb, v| w::bitcast(fb, vec(wide(64), 2), vec(int(32), 4), v[0]), - &[vec![vec![x, y]]], - &|_| Some(vec![x & 0xFFFF_FFFF, x >> 32, y & 0xFFFF_FFFF, y >> 32]), - ); - check_wide( - "bitcast f64 -> wide i64", - &[float(64)], - wide(64), - &|fb, v| w::bitcast(fb, float(64), wide(64), v[0]), - &[vec![vec![x]]], - &|_| Some(vec![x]), - ); - // `air.convert` between integers: truncating or extending by the source's sign. - for (from, to, signed) in [ - (wide(64), int(32), true), - (int(32), wide(64), true), - (int(32), wide(64), false), - (int(16), wide(64), true), - (wide(40), wide(64), true), - ] { - let vals = int_values(from.bits(), &mut Rng(3), 4); - let cases: Vec = vals.iter().map(|v| vec![vec![*v]]).collect(); - check_wide( - &format!("convert {from:?} -> {to:?} signed={signed}"), - &[from], - to, - &|fb, v| { - w::convert( - fb, - ConvertKind::Int { - signed, - saturate: None, - }, - from, - to, - v[0], - ) - }, - &cases, - &|c| { - let x = arg(c, 0); - Some(vec![if to.bits() < from.bits() { - x & mask(to.bits()) - } else if signed { - (sext(x, from.bits()) as u64) & mask(to.bits()) - } else { - x - }]) - }, - ); - } -} - -#[test] -fn a_wide_integer_to_bool_convert_is_nonzero() { - // `x != 0`, so a value with only high-word bits is true. - for from in [wide(64), wide(40), vec(wide(64), 2)] { - let top = 1u64 << (from.bits() - 1); - let vals = [ - 0, - 1, - 2, - 1 << 32, - top, - mask(from.bits()), - 0x1_0000_0000 | 2, - 0, - ]; - let cases: Vec = vals - .chunks(usize::from(from.lanes)) - .map(|c| vec![c.to_vec()]) - .collect(); - let to = vec(boolean(), from.lanes); - check_wide( - &format!("convert {from:?} -> bool"), - &[from], - to, - &|fb, v| w::convert(fb, ConvertKind::IntToBool, from, to, v[0]), - &cases, - &|c| Some(c[0].iter().map(|v| u64::from(*v != 0)).collect()), - ); - } -} - -#[test] -fn wide_element_moves_and_selects_work_per_half() { - let f = vec(wide(64), 3); - let v = vec![u64::MAX, 0x1_0000_0002, 0x8000_0000_0000_0003]; - for i in 0..3u32 { - check_wide( - &format!("extract {i}"), - &[f], - wide(64), - &|fb, x| { - w::emit( - fb, - &WideOp::Extract { - vec: f, - at: Some(i), - wide_index: false, - }, - x, - None, - ) - }, - &[vec![v.clone()]], - &|_| Some(vec![v[i as usize]]), - ); - } - // A dynamic index, narrow and wide. - for (index, wide_index) in [(int(32), false), (wide(64), true)] { - check_wide( - &format!("extract dynamic wide_index={wide_index}"), - &[f, index], - wide(64), - &|fb, x| { - w::emit( - fb, - &WideOp::Extract { - vec: f, - at: None, - wide_index, - }, - x, - None, - ) - }, - &[vec![v.clone(), vec![2]], vec![v.clone(), vec![0]]], - &|c| Some(vec![v[c[1][0] as usize]]), - ); - check_wide( - &format!("insert dynamic wide_index={wide_index}"), - &[f, wide(64), index], - f, - &|fb, x| { - w::emit( - fb, - &WideOp::Insert { - vec: f, - at: None, - wide_index, - }, - x, - None, - ) - }, - &[vec![v.clone(), vec![42], vec![1]]], - &|_| Some(vec![v[0], 42, v[2]]), - ); - } - check_wide( - "shuffle", - &[f, f], - vec(wide(64), 2), - &|fb, x| { - w::emit( - fb, - &WideOp::Shuffle { - mask: vec![5, 0].into(), - out: vec(wide(64), 2), - }, - x, - None, - ) - }, - &[vec![v.clone(), vec![7, 8, 9]]], - &|_| Some(vec![9, v[0]]), - ); - // Narrower wide lanes keep their width. - let g = vec(wide(40), 2); - let u = vec![0xFF_FFFF_FFFF, 0x80_0000_0001]; - check_wide( - "shuffle i40", - &[g, g], - vec(wide(40), 4), - &|fb, x| { - w::emit( - fb, - &WideOp::Shuffle { - mask: vec![3, 0, 1, 2].into(), - out: vec(wide(40), 4), - }, - x, - None, - ) - }, - &[vec![u.clone(), vec![7, 0x12_3456_789A]]], - &|_| Some(vec![0x12_3456_789A, u[0], u[1], 7]), - ); - let c2 = vec(boolean(), 3); - check_wide( - "select per lane", - &[c2, f, f], - f, - &|fb, x| w::emit(fb, &WideOp::Select { form: f }, x, None), - &[vec![vec![1, 0, 1], v.clone(), vec![7, 8, 9]]], - &|_| Some(vec![v[0], 8, v[2]]), - ); -} - -/// The per-use word bound of a wide integer function covers what it emits (the kernel around it, -/// which also loads every operand, subtracted), at every wide width and on vectors. -#[test] -fn wide_integer_function_words_bound_their_emission() { - use crate::spirv::serialize::serialize; - let size = |ins: &[Form], out: Form, body: Body<'_>| -> usize { - let m = kernel(ins, out, body).expect("build"); - serialize(m).expect("serialize").words.len() - }; - let mut ops: Vec = vec![ - IntFn::Abs, - IntFn::Popcount, - IntFn::ReverseBits, - IntFn::Clz, - IntFn::Ctz, - IntFn::Bswap, - IntFn::Rotate, - IntFn::Fshl, - IntFn::Fshr, - IntFn::InsertBits, - ]; - for s in [Sign::Signed, Sign::Unsigned] { - ops.extend([ - IntFn::AbsDiff(s), - IntFn::Min3(s), - IntFn::Median3(s), - IntFn::Clamp(s), - IntFn::AddSat(s), - IntFn::SubSat(s), - IntFn::RHAdd(s), - IntFn::MulHi(s), - IntFn::MadHi(s), - IntFn::MadSat(s), - IntFn::ExtractBits(s), - ]); - } - for (bits, lanes) in [(64u8, 1u8), (40, 1), (63, 3), (48, 4)] { - let f = if lanes == 1 { - wide(bits) - } else { - vec(wide(bits), lanes) - }; - for op in &ops { - let op = *op; - if !w::int_fn_lowered(op, f) { - continue; - } - let ins: Vec
= match op { - IntFn::ExtractBits(_) => vec![f, int(32), int(32)], - IntFn::InsertBits => vec![f, f, int(32), int(32)], - _ => vec![f; op.arity()], - }; - let with = size(&ins, f, &|fb, x| w::int_fn(fb, op, f, x)); - let without = size(&ins, f, &|_, x| Ok(x[0])); - let bound = WideOp::IntFn { f: op, form: f }.words() as usize; - assert!( - with - without <= bound, - "{op:?} {f:?}: {} words above the kernel, bound {bound}", - with - without - ); - } - } -} - -/// A wide division's per-use bound covers its call, and its routine's bound (once per module) -/// covers the routine, at every wide width and on vectors: the second division of a form adds only -/// its call. -#[test] -fn wide_division_words_bound_their_emission() { - use crate::spirv::serialize::serialize; - let size = |ins: &[Form], out: Form, body: Body<'_>| -> usize { - let m = kernel(ins, out, body).expect("build"); - serialize(m).expect("serialize").words.len() - }; - let (mut most_call, mut most_routine) = (0, 0); - for (bits, lanes) in [(64u8, 1u8), (40, 1), (33, 1), (63, 3), (64, 4)] { - let f = if lanes == 1 { - wide(bits) - } else { - vec(wide(bits), lanes) - }; - let d = w::Divide::of(f); - for op in [AirBin::UDiv, AirBin::URem, AirBin::SDiv, AirBin::SRem] { - let without = size(&[f, f], f, &|_, x| Ok(x[0])); - let one = size(&[f, f], f, &|fb, x| { - let r = w::define_divide(fb.module(), d)?; - w::divide(fb, op, f, x[0], x[1], r) - }); - let two = size(&[f, f], f, &|fb, x| { - let r = w::define_divide(fb.module(), d)?; - let t = w::divide(fb, op, f, x[0], x[1], r)?; - w::divide(fb, op, f, t, x[1], r) - }); - let call = two - one; - let routine = one - without - call; - let (call_bound, routine_bound) = ( - WideOp::Bin { op, form: f }.words() as usize, - d.words() as usize, - ); - assert!( - call <= call_bound, - "{op:?} {f:?}: a call of {call} words, bound {call_bound}" - ); - assert!( - routine <= routine_bound, - "{op:?} {f:?}: a routine of {routine} words, bound {routine_bound}" - ); - most_call = most_call.max(call); - most_routine = most_routine.max(routine); - } - } - eprintln!("wide division: at most {most_call} words per call, {most_routine} per routine"); -} - -/// The per-use word bound of each wide element move and select covers what it emits: a select of a -/// scalar (one select of the pair) and of a vector (word by word, on a vector or a scalar -/// condition), shuffles, and constant and dynamic (32-bit and two-word index) extracts and inserts. -#[test] -fn wide_element_moves_and_selects_bound_their_emission() { - use crate::spirv::serialize::serialize; - let size = |ins: &[Form], out: Form, body: Body<'_>| -> usize { - let m = kernel(ins, out, body).expect("build"); - serialize(m).expect("serialize").words.len() - }; - let check = |what: &str, op: WideOp, ins: &[Form], out: Form, keep: usize| { - let with = size(ins, out, &|fb, x| w::emit(fb, &op, x, None)); - let without = size(ins, out, &|_, x| Ok(x[keep])); - let bound = op.words() as usize; - assert!( - with - without <= bound, - "{what}: {} words above the kernel, bound {bound}", - with - without - ); - }; - for bits in [64u8, 40] { - let s = wide(bits); - check( - "select", - WideOp::Select { form: s }, - &[boolean(), s, s], - s, - 1, - ); - for lanes in [2u8, 3, 4] { - let v = vec(s, lanes); - let c = vec(boolean(), lanes); - check( - "select per lane", - WideOp::Select { form: v }, - &[c, v, v], - v, - 1, - ); - check( - "select on a scalar", - WideOp::Select { form: v }, - &[boolean(), v, v], - v, - 1, - ); - for out in 2..=4u8 { - let mask: Box<[u32]> = (0..u32::from(out)).map(|i| (i * 3) % 8).collect(); - let mask: Box<[u32]> = mask.iter().map(|m| m % (2 * u32::from(lanes))).collect(); - let o = vec(s, out); - // The kernel's output is `o`: return the result, or a third operand of `o`. - let op = WideOp::Shuffle { mask, out: o }; - let with = size(&[v, v, o], o, &|fb, x| w::emit(fb, &op, &x[..2], None)); - let without = size(&[v, v, o], o, &|_, x| Ok(x[2])); - assert!( - with - without <= op.words() as usize, - "shuffle {lanes} -> {out}: {} words, bound {}", - with - without, - op.words() - ); - } - let at = Some(u32::from(lanes) - 1); - check( - "extract", - WideOp::Extract { - vec: v, - at, - wide_index: false, - }, - &[v, s], - s, - 1, - ); - check( - "insert", - WideOp::Insert { - vec: v, - at, - wide_index: false, - }, - &[v, s], - v, - 0, - ); - for (index, wide_index) in [(int(32), false), (wide(64), true)] { - check( - "dynamic extract", - WideOp::Extract { - vec: v, - at: None, - wide_index, - }, - &[v, index, s], - s, - 2, - ); - check( - "dynamic insert", - WideOp::Insert { - vec: v, - at: None, - wide_index, - }, - &[v, s, index], - v, - 0, - ); - } - } - } -} - -/// The word bound of each lane move on a chunked vector covers what it emits, for two-word lanes -/// (64 and 40 bits) and, where the flat bounds stay, 32-bit lanes: constant and dynamic (32-bit and -/// two-word index) extracts and inserts, shuffles, and word bitcasts to 32-bit lanes and back, at -/// 5, 6, and 8 lanes (chunks of 4 and 1, 4 and 2, and two of 4). -#[test] -fn chunked_lane_moves_bound_their_emission() { - use super::super::chunk::{self, Shape}; - use super::super::ArithStrategy as S; - use crate::lower::strategy::FamilyStrategy; - use crate::spirv::serialize::serialize; - let size = |ins: &[Form], out: Form, body: Body<'_>| -> usize { - let m = kernel(ins, out, body).expect("build"); - serialize(m).expect("serialize").words.len() - }; - let check = |what: &str, s: &S, with: usize, without: usize| { - let bound = s.words() as usize; - assert!( - with - without <= bound, - "{what}: {} words above the kernel, bound {bound}", - with - without - ); - }; - for lane in [wide(64), wide(40), int(32)] { - let four = Shape { - held: lane.held, - lanes: 4, - chunked: false, - }; - let v4 = vec(lane, 4); - for n in [5u16, 6, 8] { - let s = Shape { - held: lane.held, - lanes: n, - chunked: true, - }; - let what = |m: &str| format!("{m} {lane:?} x {n}"); - let all: Vec = (0..u32::from(n)).collect(); - // The chunked operand, from the first two (4-lane) operands. - let make = |fb: &mut FunctionBuilder<'_>, x: &[Value]| { - chunk::shuffle(fb, four, four, s, &all, &x[..2]) - }; - // Lane 0 of a chunked value, as the kernel's output. - let first = - |fb: &mut FunctionBuilder<'_>, v: Value| chunk::extract(fb, s, Some(0), None, &[v]); - let unmoved = |ins: &[Form]| { - size(ins, lane, &|fb, x| { - let v = make(fb, x)?; - first(fb, v) - }) - }; - // Constant moves of lane 1, which lives in a 4-lane chunk. - let ins = [v4, v4, lane]; - let kept = size(&ins, lane, &|fb, x| { - make(fb, x)?; - Ok(x[2]) - }); - let with = size(&ins, lane, &|fb, x| { - let v = make(fb, x)?; - chunk::extract(fb, s, Some(1), None, &[v]) - }); - let extract = S::LaneExtract { - src: s, - at: Some(1), - index: None, - }; - check(&what("extract"), &extract, with, kept); - let with = size(&ins, lane, &|fb, x| { - let v = make(fb, x)?; - let r = chunk::insert(fb, s, Some(1), None, &[v, x[2]])?; - first(fb, r) - }); - let insert = S::LaneInsert { - dst: s, - at: Some(1), - index: None, - }; - check(&what("insert"), &insert, with, unmoved(&ins)); - // Dynamic moves. - for index in [int(32), wide(64)] { - let ins = [v4, v4, lane, index]; - let kept = size(&ins, lane, &|fb, x| { - make(fb, x)?; - Ok(x[2]) - }); - let with = size(&ins, lane, &|fb, x| { - let v = make(fb, x)?; - chunk::extract(fb, s, None, Some(index), &[v, x[3]]) - }); - let extract = S::LaneExtract { - src: s, - at: None, - index: Some(index), - }; - check(&what("dynamic extract"), &extract, with, kept); - let with = size(&ins, lane, &|fb, x| { - let v = make(fb, x)?; - let r = chunk::insert(fb, s, None, Some(index), &[v, x[2], x[3]])?; - first(fb, r) - }); - let insert = S::LaneInsert { - dst: s, - at: None, - index: Some(index), - }; - check(&what("dynamic insert"), &insert, with, unmoved(&ins)); - } - // A shuffle of every lane from both operands. - let ins = [v4, v4]; - let mask: Box<[u32]> = (0..u32::from(n)) - .map(|i| (i * 5 + 3) % (2 * u32::from(n))) - .collect(); - let with = size(&ins, lane, &|fb, x| { - let v = make(fb, x)?; - let r = chunk::shuffle(fb, s, s, s, &mask, &[v, v])?; - first(fb, r) - }); - let shuffle = S::LaneShuffle { - a: s, - b: s, - out: s, - mask: mask.clone(), - fragment: false, - }; - check(&what("shuffle"), &shuffle, with, unmoved(&ins)); - // Word bitcasts of 64-bit lanes to twice as many 32-bit lanes and back. - if lane.bits() == 64 { - let words = Shape { - held: int(32).held, - lanes: 2 * n, - chunked: true, - }; - let with = size(&ins, lane, &|fb, x| { - let v = make(fb, x)?; - let u = chunk::bitcast(fb, s, words, v)?; - let r = chunk::bitcast(fb, words, s, u)?; - first(fb, r) - }); - let there = S::WordBitcast { from: s, to: words }; - let back = S::WordBitcast { from: words, to: s }; - let bound = (there.words() + back.words()) as usize; - let emitted = with - unmoved(&ins); - assert!( - emitted <= bound, - "{}: {emitted} words above the kernel, bound {bound}", - what("bitcast and back") - ); - } - } - } -} - -/// A shuffle into a simdgroup matrix's fragment (64 lanes held whole) emits no more than its bound, -/// `chunk::fragment_shuffle_words`, for a merge taking lanes 0 and 1 from one operand and the rest -/// from the other, of 32-bit integer and of `float` lanes. -#[test] -fn a_fragment_shuffle_bounds_its_emission() { - use super::super::chunk::{self, Shape}; - use super::super::ArithStrategy as S; - use crate::lower::strategy::FamilyStrategy; - use crate::spirv::serialize::serialize; - let size = |ins: &[Form], out: Form, body: Body<'_>| -> usize { - let m = kernel(ins, out, body).expect("build"); - serialize(m).expect("serialize").words.len() - }; - for lane in [int(32), float(32)] { - let four = Shape { - held: lane.held, - lanes: 4, - chunked: false, - }; - let s = Shape { - held: lane.held, - lanes: 64, - chunked: true, - }; - let v4 = vec(lane, 4); - let ins = [v4, v4]; - let spread: Vec = (0..64).map(|i| i % 8).collect(); - let make = |fb: &mut FunctionBuilder<'_>, x: &[Value]| { - chunk::shuffle(fb, four, four, s, &spread, &x[..2]) - }; - let first = - |fb: &mut FunctionBuilder<'_>, v: Value| chunk::extract(fb, s, Some(0), None, &[v]); - let without = size(&ins, lane, &|fb, x| { - let v = make(fb, x)?; - first(fb, v) - }); - let mask: Box<[u32]> = [0, 1].into_iter().chain(66..128).collect(); - let with = size(&ins, lane, &|fb, x| { - let v = make(fb, x)?; - let r = chunk::shuffle_fragment(fb, s, s, s, &mask, &[v, v])?; - first(fb, r) - }); - let strategy = S::LaneShuffle { - a: s, - b: s, - out: s, - mask, - fragment: true, - }; - let bound = strategy.words() as usize; - assert!( - with - without <= bound, - "{lane:?}: {} words above the kernel, bound {bound}", - with - without - ); - } -} - -/// The suffixes a pipeline of OpenCL mode honors, with a wide side: a wide integer to `f32` -/// toward zero, up and down; an `f32` to a wide integer to nearest even, up and down, saturating; -/// and `.sat` between a wide integer and a 32-bit or another wide one (`convert_suffix.rs` holds -/// the native forms'). -#[test] -fn wide_conversions_honor_their_suffixes() { - use super::convert_suffix::{ - clamped, f32_of, integral_of, rounding_floats, rounding_ints, value_of, DIRECTED, INTEGRAL, - }; - let f32f = float(32); - for bits in [40u8, 64] { - let from = wide(bits); - let cases: Vec = rounding_ints(bits).iter().map(|v| vec![vec![*v]]).collect(); - for signed in [true, false] { - for mode in DIRECTED { - check_wide( - &format!("wide i{bits} signed={signed} to f32 {mode:?}"), - &[from], - f32f, - &|fb, x| { - let kind = ConvertKind::ToFloat { - signed, - directed: Some(mode), - }; - w::convert(fb, kind, from, f32f, x[0]) - }, - &cases, - &|c| Some(vec![f32_of(value_of(arg(c, 0), bits, signed), mode)]), - ); - } - } - } - let floats: Vec = rounding_floats().iter().map(|v| vec![vec![*v]]).collect(); - for signed in [true, false] { - for mode in INTEGRAL { - check_wide( - &format!("f32 to wide i64 signed={signed} {mode:?}"), - &[f32f], - wide(64), - &|fb, x| { - let kind = ConvertKind::ToInt { - signed, - round: Some(mode), - }; - w::convert(fb, kind, f32f, wide(64), x[0]) - }, - &floats, - &|c| { - let x = f64::from(f32v(arg(c, 0))); - Some(vec![saturated(integral_of(x, mode), 64, signed)]) - }, - ); - } - } - for (from, to) in [ - (wide(64), int(32)), - (wide(64), int(8)), - (wide(64), wide(64)), - (int(32), wide(64)), - (wide(40), wide(64)), - ] { - let mut vals = rounding_ints(from.bits()); - vals.extend([ - 0x7F, - 0x80, - 0xFF, - 0x100, - 0x7FFF_FFFF, - 0x8000_0000, - 0xFFFF_FFFF, - ]); - let cases: Vec = vals - .iter() - .map(|v| vec![vec![*v & mask(from.bits())]]) - .collect(); - for (signed, dst) in [ - (true, Sign::Signed), - (true, Sign::Unsigned), - (false, Sign::Signed), - (false, Sign::Unsigned), - ] { - check_wide( - &format!("{from:?} signed={signed} to {to:?} {dst:?} sat"), - &[from], - to, - &|fb, v| { - let kind = ConvertKind::Int { - signed, - saturate: Some(dst), - }; - w::convert(fb, kind, from, to, v[0]) - }, - &cases, - &|c| { - let v = value_of(arg(c, 0), from.bits(), signed); - Some(vec![clamped(v, to.bits(), dst == Sign::Signed)]) - }, - ); - } - } -} diff --git a/crates/metal2vulkan/src/lower/arith/wide.rs b/crates/metal2vulkan/src/lower/arith/wide.rs deleted file mode 100644 index 39573fcd0..000000000 --- a/crates/metal2vulkan/src/lower/arith/wide.rs +++ /dev/null @@ -1,2190 +0,0 @@ -//! Wide integers on profiles without `shaderInt64`. -//! -//! On such a profile an `i33`..`i64` value is held as two `u32` words, low word first -//! ([`Held::Wide`]): a scalar is a `uvec2`, and a vector of `n` lanes is a struct of the `n`-lane -//! low-word vector and the `n`-lane high-word vector, so every operation below is lane-wise on -//! ordinary 32-bit vectors. The value is zero-extended from its AIR width like every held integer: -//! the bits of the high word above the width are zero, so an operation that can set them masks its -//! result ([`mask_top`]) and a signed one sign-extends its operands first ([`sext_top`]). -//! -//! Every sequence is exact for every non-poison input and uses only 32-bit integer instructions -//! (no `Int64` capability): add and subtract through `OpIAddCarry`/`OpISubBorrow`, multiply -//! through `OpUMulExtended` and the two cross products, shifts by a dynamic amount through -//! in-range 32-bit shifts and a select on the amount's bit 5, compares from the high words and -//! then the low words, and division and remainder by Hacker's Delight's `divdu` on 32-bit -//! `OpUDiv` (Knuth's algorithm D on 16-bit digits, straight-line: no loop is opened; every -//! divisor is nonzero). The division is one module-scope function per lane count, which every -//! division on that many lanes calls ([`Divide`]; a signed one divides the magnitudes and sets the -//! sign at the call), so a module holds it once, not once per use. A conversion to a float -//! collapses the magnitude to 32 significant bits with a sticky bit before one exactly scaled -//! conversion, so it rounds once (to odd first for `bfloat`, then once to the format); a conversion -//! from a float splits the truncated magnitude at `2^32` exactly. -//! -//! The multiply-high functions and `mad_sat` form the exact 128-bit product from four -//! `OpUMulExtended` (signed: of the sign-extended operands, corrected by subtracting each operand -//! where the other is negative) and take its bits `[N, 2N)` or saturate it; `rotate` and the -//! funnel shifts reduce the amount modulo the width in 32-bit words and shift in range at every -//! width. - -use crate::air::intrinsics::AirIntrinsic; -use crate::air::ir::{ - BinOp as AirBin, Callee, CastOp, Inst, InstId, InstKind, IntPredicate, Value, -}; -use crate::error::Error; -use crate::lower::arith::legal::{self, FloatFmt, Form, Held}; -use crate::lower::arith::math::{self, ConvertKind, IntFn, Sign}; -use crate::lower::arith::narrow; -use crate::lower::arith::ops::{self, CastKind}; -use crate::lower::select::SelectCx; -use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; -use crate::spirv::error::{BResult, BuildError, OperandRule, TypeRule}; -use crate::spirv::ids::{ConstId, DemoteTy, FuncId, Value as SValue}; -use crate::spirv::ir::{BinOp, ConstBits, Constant, ConvOp, GlslOp, Type, UnOp}; - -use super::{check_operands, lanes_of, not_lowered, operands_of, ty_of, ArithStrategy, Fun}; - -// ---- The pair ---- - -/// A wide value as its two words (each a `u32` or a `u32` vector of the value's lanes). -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Pair { - pub lo: SValue, - pub hi: SValue, -} - -/// The `u32` form of `lanes` lanes (one word of each lane). -pub fn words_form(lanes: u8) -> Form { - Form { - held: Held::Int { - bits: 32, - container: 32, - }, - lanes, - } -} - -/// The wide form of `bits` bits and `lanes` lanes. -pub fn wide_form(bits: u8, lanes: u8) -> Form { - Form { - held: Held::Wide { bits }, - lanes, - } -} - -fn arity_error() -> BuildError { - BuildError::Operand { - op: crate::spv::Op::CompositeExtract, - rule: OperandRule::Arity, - } -} - -fn word_const(fb: &mut FunctionBuilder<'_>, lanes: u8, v: u32) -> BResult { - let u = ops::ty(fb, words_form(1))?; - let s = fb.module().constant(Constant::Scalar { - ty: u, - bits: ConstBits(u64::from(v)), - })?; - if lanes == 1 { - return Ok(s); - } - let t = ops::ty(fb, words_form(lanes))?; - fb.module().constant(Constant::Composite { - ty: t, - parts: vec![s; usize::from(lanes)].into(), - }) -} - -/// The word constant `v` in every lane. -fn k(fb: &mut FunctionBuilder<'_>, lanes: u8, v: u32) -> BResult { - let c = word_const(fb, lanes, v)?; - fb.module().const_value(c) -} - -/// The wide constant of form `f` with `bits` (masked to the width) in every lane. -pub fn splat(fb: &mut FunctionBuilder<'_>, f: Form, bits: u64) -> BResult { - let bits = bits & ops::ones(f.bits()); - let lo = word_const(fb, f.lanes, bits as u32)?; - let hi = word_const(fb, f.lanes, (bits >> 32) as u32)?; - let t = ops::ty(fb, f)?; - let c = fb.module().constant(Constant::Composite { - ty: t, - parts: vec![lo, hi].into(), - })?; - fb.module().const_value(c) -} - -/// The pair constant with `bits` in every lane of `lanes` lanes. -fn pk(fb: &mut FunctionBuilder<'_>, lanes: u8, bits: u64) -> BResult { - Ok(Pair { - lo: k(fb, lanes, bits as u32)?, - hi: k(fb, lanes, (bits >> 32) as u32)?, - }) -} - -/// The two words of wide value `x`. -pub fn split(fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult { - Ok(Pair { - lo: fb.composite_extract(x, &[0])?, - hi: fb.composite_extract(x, &[1])?, - }) -} - -/// The wide value of form `f` with words `p`. -pub fn join(fb: &mut FunctionBuilder<'_>, f: Form, p: Pair) -> BResult { - let t = ops::ty(fb, f)?; - fb.composite_construct(t, &[p.lo, p.hi]) -} - -fn bin(fb: &mut FunctionBuilder<'_>, op: BinOp, a: SValue, b: SValue) -> BResult { - fb.binary(op, a, b) -} - -/// `x op c` with a word constant, omitted for a shift by 0. -fn bink(fb: &mut FunctionBuilder<'_>, n: u8, op: BinOp, x: SValue, c: u32) -> BResult { - if c == 0 - && matches!( - op, - BinOp::ShiftLeftLogical | BinOp::ShiftRightLogical | BinOp::ShiftRightArithmetic - ) - { - return Ok(x); - } - let c = k(fb, n, c)?; - bin(fb, op, x, c) -} - -/// The words of `p` with the bits above `f`'s width cleared. -pub fn mask_top(fb: &mut FunctionBuilder<'_>, f: Form, p: Pair) -> BResult { - let bits = f.bits(); - if bits >= 64 { - return Ok(p); - } - let hi = bink( - fb, - f.lanes, - BinOp::BitwiseAnd, - p.hi, - ops::ones(bits - 32) as u32, - )?; - Ok(Pair { lo: p.lo, hi }) -} - -/// The words of `p` (zero-extended from `f`'s width) sign-extended to 64 bits. -pub fn sext_top(fb: &mut FunctionBuilder<'_>, f: Form, p: Pair) -> BResult { - let bits = f.bits(); - if bits >= 64 { - return Ok(p); - } - let sh = u32::from(64 - bits); - let up = bink(fb, f.lanes, BinOp::ShiftLeftLogical, p.hi, sh)?; - let hi = bink(fb, f.lanes, BinOp::ShiftRightArithmetic, up, sh)?; - Ok(Pair { lo: p.lo, hi }) -} - -fn per_word(fb: &mut FunctionBuilder<'_>, op: BinOp, a: Pair, b: Pair) -> BResult { - Ok(Pair { - lo: bin(fb, op, a.lo, b.lo)?, - hi: bin(fb, op, a.hi, b.hi)?, - }) -} - -/// `a + b` modulo `2^64`. -pub fn add(fb: &mut FunctionBuilder<'_>, a: Pair, b: Pair) -> BResult { - let r = bin(fb, BinOp::IAddCarry, a.lo, b.lo)?; - let lo = fb.composite_extract(r, &[0])?; - let c = fb.composite_extract(r, &[1])?; - let hi = bin(fb, BinOp::IAdd, a.hi, b.hi)?; - let hi = bin(fb, BinOp::IAdd, hi, c)?; - Ok(Pair { lo, hi }) -} - -/// `a - b` modulo `2^64`. -pub fn sub(fb: &mut FunctionBuilder<'_>, a: Pair, b: Pair) -> BResult { - let r = bin(fb, BinOp::ISubBorrow, a.lo, b.lo)?; - let lo = fb.composite_extract(r, &[0])?; - let c = fb.composite_extract(r, &[1])?; - let hi = bin(fb, BinOp::ISub, a.hi, b.hi)?; - let hi = bin(fb, BinOp::ISub, hi, c)?; - Ok(Pair { lo, hi }) -} - -/// `-a` modulo `2^64` (`n` lanes). -pub fn neg(fb: &mut FunctionBuilder<'_>, n: u8, a: Pair) -> BResult { - let z = pk(fb, n, 0)?; - sub(fb, z, a) -} - -/// `a * b` modulo `2^64`. -pub fn mul(fb: &mut FunctionBuilder<'_>, a: Pair, b: Pair) -> BResult { - let p = bin(fb, BinOp::UMulExtended, a.lo, b.lo)?; - let lo = fb.composite_extract(p, &[0])?; - let c = fb.composite_extract(p, &[1])?; - let x = bin(fb, BinOp::IMul, a.lo, b.hi)?; - let y = bin(fb, BinOp::IMul, a.hi, b.lo)?; - let hi = bin(fb, BinOp::IAdd, c, x)?; - let hi = bin(fb, BinOp::IAdd, hi, y)?; - Ok(Pair { lo, hi }) -} - -/// `select(c, a, b)` word by word (`c` a `bool` or a `bool` vector of the words' lanes). -pub fn sel(fb: &mut FunctionBuilder<'_>, c: SValue, a: Pair, b: Pair) -> BResult { - Ok(Pair { - lo: fb.select(c, a.lo, b.lo)?, - hi: fb.select(c, a.hi, b.hi)?, - }) -} - -/// A shift of a pair. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Shift { - Left, - Logical, - Arithmetic, -} - -/// `x` shifted by `s mod 64` (`s` a word of `n` lanes). Every 32-bit shift is in range: the -/// words move by `s mod 32`, the bits crossing between them by two shifts (`(x >> 1) >> (31 - -/// s)`), and bit 5 of `s` selects the half-swapped result. An arithmetic shift reads `x`'s high -/// word as signed (sign-extend it first). -fn shift(fb: &mut FunctionBuilder<'_>, n: u8, kind: Shift, x: Pair, s: SValue) -> BResult { - let s = bink(fb, n, BinOp::BitwiseAnd, s, 63)?; - let s5 = bink(fb, n, BinOp::BitwiseAnd, s, 31)?; - let b5 = bink(fb, n, BinOp::BitwiseAnd, s, 32)?; - let z = k(fb, n, 0)?; - let big = bin(fb, BinOp::INotEqual, b5, z)?; - let k31 = k(fb, n, 31)?; - let inv = bin(fb, BinOp::ISub, k31, s5)?; - Ok(match kind { - Shift::Left => { - let lo_s = bin(fb, BinOp::ShiftLeftLogical, x.lo, s5)?; - let c = bink(fb, n, BinOp::ShiftRightLogical, x.lo, 1)?; - let c = bin(fb, BinOp::ShiftRightLogical, c, inv)?; - let hi_s = bin(fb, BinOp::ShiftLeftLogical, x.hi, s5)?; - let hi_s = bin(fb, BinOp::BitwiseOr, hi_s, c)?; - Pair { - lo: fb.select(big, z, lo_s)?, - hi: fb.select(big, lo_s, hi_s)?, - } - } - Shift::Logical | Shift::Arithmetic => { - let op = if kind == Shift::Arithmetic { - BinOp::ShiftRightArithmetic - } else { - BinOp::ShiftRightLogical - }; - let hi_s = bin(fb, op, x.hi, s5)?; - let c = bink(fb, n, BinOp::ShiftLeftLogical, x.hi, 1)?; - let c = bin(fb, BinOp::ShiftLeftLogical, c, inv)?; - let lo_s = bin(fb, BinOp::ShiftRightLogical, x.lo, s5)?; - let lo_s = bin(fb, BinOp::BitwiseOr, lo_s, c)?; - let fill = if kind == Shift::Arithmetic { - bin(fb, BinOp::ShiftRightArithmetic, x.hi, k31)? - } else { - z - }; - Pair { - lo: fb.select(big, hi_s, lo_s)?, - hi: fb.select(big, fill, hi_s)?, - } - } - }) -} - -/// `x << (s mod 64)` (`s` a word of `n` lanes). -pub fn shl(fb: &mut FunctionBuilder<'_>, n: u8, x: Pair, s: SValue) -> BResult { - shift(fb, n, Shift::Left, x, s) -} - -/// `x >> (s mod 64)`, logical (`s` a word of `n` lanes). -pub fn lshr(fb: &mut FunctionBuilder<'_>, n: u8, x: Pair, s: SValue) -> BResult { - shift(fb, n, Shift::Logical, x, s) -} - -/// `x >> s` (logical) for a constant `s` below 64. -fn lshr_const(fb: &mut FunctionBuilder<'_>, n: u8, x: Pair, s: u32) -> BResult { - Ok(match s { - 0 => x, - 1..=31 => { - let lo = bink(fb, n, BinOp::ShiftRightLogical, x.lo, s)?; - let c = bink(fb, n, BinOp::ShiftLeftLogical, x.hi, 32 - s)?; - Pair { - lo: bin(fb, BinOp::BitwiseOr, lo, c)?, - hi: bink(fb, n, BinOp::ShiftRightLogical, x.hi, s)?, - } - } - _ => Pair { - lo: bink(fb, n, BinOp::ShiftRightLogical, x.hi, s - 32)?, - hi: k(fb, n, 0)?, - }, - }) -} - -/// `x << s` for a constant `s` below 64. -fn shl_const(fb: &mut FunctionBuilder<'_>, n: u8, x: Pair, s: u32) -> BResult { - Ok(match s { - 0 => x, - 1..=31 => { - let hi = bink(fb, n, BinOp::ShiftLeftLogical, x.hi, s)?; - let c = bink(fb, n, BinOp::ShiftRightLogical, x.lo, 32 - s)?; - Pair { - lo: bink(fb, n, BinOp::ShiftLeftLogical, x.lo, s)?, - hi: bin(fb, BinOp::BitwiseOr, hi, c)?, - } - } - _ => Pair { - lo: k(fb, n, 0)?, - hi: bink(fb, n, BinOp::ShiftLeftLogical, x.lo, s - 32)?, - }, - }) -} - -/// An unsigned (or, on sign-extended pairs, signed) comparison of two pairs. -fn compare(fb: &mut FunctionBuilder<'_>, pred: IntPredicate, a: Pair, b: Pair) -> BResult { - use IntPredicate as P; - let (a, b, pred) = match pred { - P::Ugt => (b, a, P::Ult), - P::Uge => (b, a, P::Ule), - P::Sgt => (b, a, P::Slt), - P::Sge => (b, a, P::Sle), - p => (a, b, p), - }; - let lo_eq = bin(fb, BinOp::IEqual, a.lo, b.lo)?; - let hi_eq = bin(fb, BinOp::IEqual, a.hi, b.hi)?; - match pred { - P::Eq => bin(fb, BinOp::LogicalAnd, lo_eq, hi_eq), - P::Ne => { - let eq = bin(fb, BinOp::LogicalAnd, lo_eq, hi_eq)?; - fb.unary(UnOp::LogicalNot, eq) - } - P::Ult | P::Ule | P::Slt | P::Sle => { - let hi_op = if matches!(pred, P::Slt | P::Sle) { - BinOp::SLessThan - } else { - BinOp::ULessThan - }; - let lo_op = if matches!(pred, P::Ule | P::Sle) { - BinOp::ULessThanEqual - } else { - BinOp::ULessThan - }; - let hi_lt = bin(fb, hi_op, a.hi, b.hi)?; - let lo_c = bin(fb, lo_op, a.lo, b.lo)?; - let tie = bin(fb, BinOp::LogicalAnd, hi_eq, lo_c)?; - bin(fb, BinOp::LogicalOr, hi_lt, tie) - } - _ => Err(arity_error()), - } -} - -/// Whether sign-extended pair `p` is negative. -fn negative(fb: &mut FunctionBuilder<'_>, n: u8, p: Pair) -> BResult { - let z = k(fb, n, 0)?; - bin(fb, BinOp::SLessThan, p.hi, z) -} - -/// `|p|` of sign-extended pair `p` (as an unsigned pair; `-2^63` stays `2^63`). -fn abs(fb: &mut FunctionBuilder<'_>, n: u8, p: Pair) -> BResult<(Pair, SValue)> { - let neg_p = negative(fb, n, p)?; - let m = neg(fb, n, p)?; - Ok((sel(fb, neg_p, m, p)?, neg_p)) -} - -/// `c ? 1 : 0` in each of `n` lanes. -fn one_if(fb: &mut FunctionBuilder<'_>, n: u8, c: SValue) -> BResult { - let (one, z) = (k(fb, n, 1)?, k(fb, n, 0)?); - fb.select(c, one, z) -} - -/// Quotient and remainder of unsigned `u / v` on two-word lanes, exact for every 64-bit `u` and -/// `v` (Hacker's Delight's `divdu`, straight-line: both of its cases are computed and selected -/// per lane, and no loop is opened). A zero divisor, which LLVM leaves undefined, divides by one -/// (quotient `u`, remainder 0), so no `OpUDiv` below divides by zero. -/// -/// A divisor below `2^32` (`v.hi == 0`) divides the high word by it (`u.hi / v.lo`, the -/// quotient's high word) and then the remainder's two words by it ([`div_words`], the quotient's -/// low word). A wider divisor is normalized by its leading zeros `z` (its top word `top`, top bit -/// set); `(u / 2) / top`, shifted right by `31 - z`, is the quotient or one less (at most one less -/// once a nonzero estimate is lowered by one), and one compare of the remainder `u - q·v` with -/// `v` corrects it. -fn udivrem(fb: &mut FunctionBuilder<'_>, n: u8, u: Pair, v: Pair) -> BResult<(Pair, Pair)> { - let z = k(fb, n, 0)?; - let narrow = bin(fb, BinOp::IEqual, v.hi, z)?; - let one = k(fb, n, 1)?; - let at_least_one = fb.glsl(GlslOp::UMax, &[v.lo, one])?; - let v = Pair { - lo: fb.select(narrow, at_least_one, v.lo)?, - hi: v.hi, - }; - // The top word of the normalized divisor: `m` is the top bit of `v.hi` (of `1` in a narrow - // lane, which keeps every shift below in range), and the bits leaving `v.lo` enter by two - // in-range shifts (`(v.lo >> 1) >> m` is `v.lo >> (32 - z)`). - let h1 = bink(fb, n, BinOp::BitwiseOr, v.hi, 1)?; - let m = fb.glsl(GlslOp::FindUMsb, &[h1])?; - let k31 = k(fb, n, 31)?; - let lz = bin(fb, BinOp::ISub, k31, m)?; - let top = bin(fb, BinOp::ShiftLeftLogical, v.hi, lz)?; - let c = bink(fb, n, BinOp::ShiftRightLogical, v.lo, 1)?; - let c = bin(fb, BinOp::ShiftRightLogical, c, m)?; - let top = bin(fb, BinOp::BitwiseOr, top, c)?; - // The one word the long division divides by, nonzero in every lane. - let d = fb.select(narrow, v.lo, top)?; - let qh = bin(fb, BinOp::UDiv, u.hi, d)?; - let rh = bin(fb, BinOp::UMod, u.hi, d)?; - // `u / 2`, whose high word is below `2^31 <= top`. - let hh = bink(fb, n, BinOp::ShiftRightLogical, u.hi, 1)?; - let hl = bink(fb, n, BinOp::ShiftRightLogical, u.lo, 1)?; - let cross = bink(fb, n, BinOp::ShiftLeftLogical, u.hi, 31)?; - let hl = bin(fb, BinOp::BitwiseOr, hl, cross)?; - let (nh, nl) = (fb.select(narrow, rh, hh)?, fb.select(narrow, u.lo, hl)?); - let dq = div_words(fb, n, nh, nl, d)?; - // Undo the normalization and the halving: `(dq << z) >> 31` is `dq >> m`. - let est = bin(fb, BinOp::ShiftRightLogical, dq, m)?; - let nonzero = bin(fb, BinOp::INotEqual, est, z)?; - let dec = one_if(fb, n, nonzero)?; - let est = bin(fb, BinOp::ISub, est, dec)?; - let q = Pair { - lo: fb.select(narrow, dq, est)?, - hi: fb.select(narrow, qh, z)?, - }; - // `q·v <= u`, so the remainder is exact modulo `2^64`; it reaches `v` only in a wide lane - // whose estimate is one short (whose quotient stays below `2^32`). - let p = mul(fb, q, v)?; - let r = sub(fb, u, p)?; - let short = compare(fb, IntPredicate::Uge, r, v)?; - let inc = one_if(fb, n, short)?; - let q = Pair { - lo: bin(fb, BinOp::IAdd, q.lo, inc)?, - hi: q.hi, - }; - let less = sub(fb, r, v)?; - Ok((q, sel(fb, short, less, r)?)) -} - -/// The quotient word of the two-word dividend `(u1, u0)` by the word `v`, where `0 < v` and -/// `u1 < v` in every lane (Hacker's Delight's `divlu`, Knuth's algorithm D on 16-bit digits): -/// `v` shifted left by its leading zeros `s` (top bit set) and the dividend with it, then two -/// quotient digits ([`digit`]), each from the running remainder, which stays below the shifted -/// divisor and so is exact modulo `2^32`. -fn div_words( - fb: &mut FunctionBuilder<'_>, - n: u8, - u1: SValue, - u0: SValue, - v: SValue, -) -> BResult { - let t = fb.glsl(GlslOp::FindUMsb, &[v])?; - let k31 = k(fb, n, 31)?; - let s = bin(fb, BinOp::ISub, k31, t)?; - let vn = bin(fb, BinOp::ShiftLeftLogical, v, s)?; - let vn1 = bink(fb, n, BinOp::ShiftRightLogical, vn, 16)?; - let vn0 = bink(fb, n, BinOp::BitwiseAnd, vn, 0xFFFF)?; - // `u1 << s` takes the bits leaving `u0` by two in-range shifts (`(u0 >> 1) >> t`). - let hi = bin(fb, BinOp::ShiftLeftLogical, u1, s)?; - let c = bink(fb, n, BinOp::ShiftRightLogical, u0, 1)?; - let c = bin(fb, BinOp::ShiftRightLogical, c, t)?; - let un32 = bin(fb, BinOp::BitwiseOr, hi, c)?; - let un10 = bin(fb, BinOp::ShiftLeftLogical, u0, s)?; - let un1 = bink(fb, n, BinOp::ShiftRightLogical, un10, 16)?; - let un0 = bink(fb, n, BinOp::BitwiseAnd, un10, 0xFFFF)?; - let q1 = digit(fb, n, un32, un1, vn1, vn0)?; - let up = bink(fb, n, BinOp::ShiftLeftLogical, un32, 16)?; - let up = bin(fb, BinOp::IAdd, up, un1)?; - let taken = bin(fb, BinOp::IMul, q1, vn)?; - let un21 = bin(fb, BinOp::ISub, up, taken)?; - let q0 = digit(fb, n, un21, un0, vn1, vn0)?; - let q1 = bink(fb, n, BinOp::ShiftLeftLogical, q1, 16)?; - bin(fb, BinOp::BitwiseOr, q1, q0) -} - -/// One quotient digit (below `2^16`) of `num·2^16 + low` by the normalized `vn1·2^16 + vn0` -/// (`vn1 >= 2^15`), when the quotient is one digit (Knuth's step D3): the estimate `num / vn1`, -/// with remainder `rhat`, is at most two above the digit, and is lowered while it is `2^16` or -/// more or `q·vn0 > rhat·2^16 + low` (both sides below `2^32` whenever the first test fails), -/// the second time only while `rhat + vn1` stays below `2^16`. -fn digit( - fb: &mut FunctionBuilder<'_>, - n: u8, - num: SValue, - low: SValue, - vn1: SValue, - vn0: SValue, -) -> BResult { - let over = |fb: &mut FunctionBuilder<'_>, q: SValue, rhat: SValue| -> BResult { - let big = bink(fb, n, BinOp::UGreaterThanEqual, q, 0x1_0000)?; - let lhs = bin(fb, BinOp::IMul, q, vn0)?; - let rhs = bink(fb, n, BinOp::ShiftLeftLogical, rhat, 16)?; - let rhs = bin(fb, BinOp::IAdd, rhs, low)?; - let gt = bin(fb, BinOp::UGreaterThan, lhs, rhs)?; - bin(fb, BinOp::LogicalOr, big, gt) - }; - let q = bin(fb, BinOp::UDiv, num, vn1)?; - let rhat = bin(fb, BinOp::UMod, num, vn1)?; - let first = over(fb, q, rhat)?; - let dec = one_if(fb, n, first)?; - let q = bin(fb, BinOp::ISub, q, dec)?; - let z = k(fb, n, 0)?; - let add = fb.select(first, vn1, z)?; - let rhat = bin(fb, BinOp::IAdd, rhat, add)?; - // Without a first correction `q` and `rhat` are unchanged and the test fails again. - let small = bink(fb, n, BinOp::ULessThan, rhat, 0x1_0000)?; - let again = over(fb, q, rhat)?; - let second = bin(fb, BinOp::LogicalAnd, small, again)?; - let dec = one_if(fb, n, second)?; - bin(fb, BinOp::ISub, q, dec) -} - -// ---- The shared division routine ---- - -/// The census name of a wide division, whose routine's words it is charged once. -pub const DIVIDE: &str = "arith.wide.divide"; - -/// A module's shared unsigned division routine of wide operands of `lanes` lanes: `fn(a, b) -> {a / -/// b, a % b}` ([`define_divide`]). Every wide `udiv`, `urem`, `sdiv`, and `srem` on that many lanes -/// calls it, whatever its width: the routine divides the two-word values exactly as 64-bit ones, -/// and a width's zero-extended values stay below `2^bits`. -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct Divide { - pub lanes: u8, -} - -impl Divide { - /// The routine of wide operands of form `f`. - pub fn of(f: Form) -> Divide { - Divide { lanes: f.lanes } - } - - /// An upper estimate of the routine's SPIR-V words, counted once per module: about 125 - /// straight-line instructions of 4 to 7 words, and its constants. Measured at most 716 words, - /// at 4 lanes (`wide_division_words_bound_their_emission`). - pub fn words(self) -> u32 { - 768 - } -} - -/// Define `d`'s routine in `mb`: a function of two unsigned two-word values of its lanes, -/// returning the struct of their quotient and remainder (the compact division above). -pub fn define_divide(mb: &mut ModuleBuilder, d: Divide) -> BResult { - let held = legal::wide_demote(d.lanes); - let both = DemoteTy::Composite(vec![held.clone(), held.clone()].into()); - let (Some(t), Some(ret)) = (legal::spirv_type(mb, &held)?, legal::spirv_type(mb, &both)?) - else { - return Err(BuildError::Type(TypeRule::FunctionSignature)); - }; - let mut fb = mb.function(ret)?; - let (a, b) = (fb.param(t)?, fb.param(t)?); - let (x, y) = (split(&mut fb, a)?, split(&mut fb, b)?); - let (q, r) = udivrem(&mut fb, d.lanes, x, y)?; - let f = wide_form(64, d.lanes); - let (q, r) = (join(&mut fb, f, q)?, join(&mut fb, f, r)?); - let v = fb.composite_construct(ret, &[q, r])?; - fb.ret(Some(v))?; - fb.finish() -} - -/// Whether `op` is a division or remainder (a wide one calls [`Divide`]'s routine). -fn is_division(op: AirBin) -> bool { - matches!( - op, - AirBin::UDiv | AirBin::URem | AirBin::SDiv | AirBin::SRem - ) -} - -/// Division or remainder `op` on wide values of form `f`, through `routine`, the form's -/// [`define_divide`]. An unsigned one is the call (its quotient `q <= a` and remainder `r < b`, -/// or `q = a` and `r = 0` for a zero divisor, stay below `2^bits`); a signed one divides the -/// magnitudes and negates the quotient where the operands' signs differ, the remainder where the -/// dividend is negative. -pub fn divide( - fb: &mut FunctionBuilder<'_>, - op: AirBin, - f: Form, - a: SValue, - b: SValue, - routine: FuncId, -) -> BResult { - let call = |fb: &mut FunctionBuilder<'_>, a: SValue, b: SValue, rem: bool| { - let qr = fb.call(routine, &[a, b])?.ok_or_else(missing_routine)?; - fb.composite_extract(qr, &[u32::from(rem)]) - }; - let n = f.lanes; - match op { - AirBin::UDiv | AirBin::URem => call(fb, a, b, op == AirBin::URem), - AirBin::SDiv | AirBin::SRem => { - let (x, y) = (split(fb, a)?, split(fb, b)?); - let (x, y) = (sext_top(fb, f, x)?, sext_top(fb, f, y)?); - let (mx, nx) = abs(fb, n, x)?; - let (my, ny) = abs(fb, n, y)?; - let (mx, my) = (join(fb, f, mx)?, join(fb, f, my)?); - let m = call(fb, mx, my, op == AirBin::SRem)?; - let m = split(fb, m)?; - let flip = if op == AirBin::SDiv { - bin(fb, BinOp::LogicalNotEqual, nx, ny)? - } else { - nx - }; - let nm = neg(fb, n, m)?; - let r = sel(fb, flip, nm, m)?; - let r = mask_top(fb, f, r)?; - join(fb, f, r) - } - _ => Err(arity_error()), - } -} - -/// A division without its routine, or a routine without a result. -fn missing_routine() -> BuildError { - BuildError::Operand { - op: crate::spv::Op::FunctionCall, - rule: OperandRule::Callee, - } -} - -// ---- Operations ---- - -/// An integer binary operator other than a division on wide values of form `f` (a division is -/// [`divide`]). -pub fn binary( - fb: &mut FunctionBuilder<'_>, - op: AirBin, - f: Form, - a: SValue, - b: SValue, -) -> BResult { - let n = f.lanes; - let (x, y) = (split(fb, a)?, split(fb, b)?); - let r = match op { - AirBin::Add => add(fb, x, y)?, - AirBin::Sub => sub(fb, x, y)?, - AirBin::Mul => mul(fb, x, y)?, - AirBin::And => per_word(fb, BinOp::BitwiseAnd, x, y)?, - AirBin::Or => per_word(fb, BinOp::BitwiseOr, x, y)?, - AirBin::Xor => per_word(fb, BinOp::BitwiseXor, x, y)?, - // A shift by the width or more is poison: any amount's low six bits will do. - AirBin::Shl => shl(fb, n, x, y.lo)?, - AirBin::LShr => lshr(fb, n, x, y.lo)?, - AirBin::AShr => { - let x = sext_top(fb, f, x)?; - shift(fb, n, Shift::Arithmetic, x, y.lo)? - } - AirBin::UDiv - | AirBin::URem - | AirBin::SDiv - | AirBin::SRem - | AirBin::FAdd - | AirBin::FSub - | AirBin::FMul - | AirBin::FDiv - | AirBin::FRem => return Err(arity_error()), - }; - let r = mask_top(fb, f, r)?; - join(fb, f, r) -} - -/// `icmp` on wide values of form `f`. -pub fn int_compare( - fb: &mut FunctionBuilder<'_>, - pred: IntPredicate, - f: Form, - a: SValue, - b: SValue, -) -> BResult { - use IntPredicate as P; - let (mut x, mut y) = (split(fb, a)?, split(fb, b)?); - if matches!(pred, P::Sgt | P::Sge | P::Slt | P::Sle) { - x = sext_top(fb, f, x)?; - y = sext_top(fb, f, y)?; - } - compare(fb, pred, x, y) -} - -/// Integer `x` of form `from` (`bool`, a 32-bit container, or wide) as a 64-bit pair, -/// sign-extended when `signed`. -fn to_pair(fb: &mut FunctionBuilder<'_>, from: Form, x: SValue, signed: bool) -> BResult { - let n = from.lanes; - match from.held { - Held::Bool => { - let one = pk(fb, n, if signed { u64::MAX } else { 1 })?; - let z = pk(fb, n, 0)?; - sel(fb, x, one, z) - } - Held::Int { container: 32, .. } => { - if signed { - let lo = ops::sext(fb, from, x)?; - let hi = bink(fb, n, BinOp::ShiftRightArithmetic, lo, 31)?; - Ok(Pair { lo, hi }) - } else { - Ok(Pair { - lo: x, - hi: k(fb, n, 0)?, - }) - } - } - Held::Wide { .. } => { - let p = split(fb, x)?; - if signed { - sext_top(fb, from, p) - } else { - Ok(p) - } - } - Held::Int { .. } | Held::Float(_) => Err(arity_error()), - } -} - -/// Pair `p` (of `to`'s lanes) as a value of integer form `to`: truncated to its width. -fn from_pair(fb: &mut FunctionBuilder<'_>, to: Form, p: Pair) -> BResult { - match to.held { - Held::Bool => { - let one = k(fb, to.lanes, 1)?; - let b = bin(fb, BinOp::BitwiseAnd, p.lo, one)?; - let z = k(fb, to.lanes, 0)?; - bin(fb, BinOp::INotEqual, b, z) - } - Held::Int { container: 32, .. } => ops::mask(fb, to, p.lo), - Held::Wide { .. } => { - let p = mask_top(fb, to, p)?; - join(fb, to, p) - } - Held::Int { .. } | Held::Float(_) => Err(arity_error()), - } -} - -/// The float form of `f`'s container (a narrow float's `f32`). -fn container_float(f: Form) -> Form { - f.with(Held::Float(if f.container() == 64 { - FloatFmt::F64 - } else { - FloatFmt::F32 - })) -} - -/// Float `x` (form `from`) truncated toward zero to a wide integer of form `to` (LLVM -/// `fptoui`/`fptosi`: a value out of range is poison). The truncated magnitude `m` splits as -/// `h * 2^32 + r` with `h = trunc(m * 2^-32)`: the scaling is exact, `h * 2^32` is exact, and -/// `r = m - h * 2^32` is exact (the low bits of `m`'s significand), so both words convert -/// exactly. -fn float_to_pair( - fb: &mut FunctionBuilder<'_>, - from: Form, - to: Form, - x: SValue, - signed: bool, -) -> BResult { - let n = to.lanes; - let cf = container_float(from); - let m = if signed { - fb.glsl(GlslOp::FAbs, &[x])? - } else { - x - }; - let down = ops::fsplat(fb, cf, 2f64.powi(-32))?; - let up = ops::fsplat(fb, cf, 2f64.powi(32))?; - let h = bin(fb, BinOp::FMul, m, down)?; - let h = fb.glsl(GlslOp::Trunc, &[h])?; - let hh = bin(fb, BinOp::FMul, h, up)?; - let r = bin(fb, BinOp::FSub, m, hh)?; - let ut = ops::ty(fb, words_form(n))?; - let hi = fb.convert(ConvOp::ConvertFToU, h, ut)?; - let lo = fb.convert(ConvOp::ConvertFToU, r, ut)?; - let p = Pair { lo, hi }; - if !signed { - return Ok(p); - } - let z = ops::fsplat(fb, cf, 0.0)?; - let is_neg = bin(fb, BinOp::FOrdLessThan, x, z)?; - let np = neg(fb, n, p)?; - sel(fb, is_neg, np, p) -} - -/// Wide `x` (form `from`, read as signed when `signed`) converted to float form `to`, rounding -/// once: to `double` as `hi * 2^32 + lo` (both exact, one rounding add); otherwise the magnitude -/// shifted right by `s` (so it has at most 32 significant bits) with the bits shifted out folded -/// into a sticky lowest bit, converted (to odd for `bfloat`), and scaled back by `2^s` exactly. -/// A magnitude below `2^32` takes `s = 0`, so below `2^24` the `f32` is exact and a `half` -/// rounds it by integer arithmetic ([`narrow::round_integer`]). -fn pair_to_float( - fb: &mut FunctionBuilder<'_>, - from: Form, - to: Form, - x: SValue, - signed: bool, -) -> BResult { - let n = from.lanes; - let p = to_pair(fb, from, x, signed)?; - let (m, is_neg) = if signed { - let (m, s) = abs(fb, n, p)?; - (m, Some(s)) - } else { - (p, None) - }; - let t = ops::ty(fb, to)?; - let r = if to.float_fmt() == Some(FloatFmt::F64) { - let fh = fb.convert(ConvOp::ConvertUToF, m.hi, t)?; - let fl = fb.convert(ConvOp::ConvertUToF, m.lo, t)?; - let up = ops::fsplat(fb, to, 2f64.powi(32))?; - let fh = bin(fb, BinOp::FMul, fh, up)?; - bin(fb, BinOp::FAdd, fh, fl)? - } else { - // s = the high word's bit length (FindUMsb of 0 is -1). - let msb = fb.glsl(GlslOp::FindUMsb, &[m.hi])?; - let s = bink(fb, n, BinOp::IAdd, msb, 1)?; - let t32 = lshr(fb, n, m, s)?; - let back = shl(fb, n, t32, s)?; - let lost = compare(fb, IntPredicate::Ne, back, m)?; - let one = k(fb, n, 1)?; - let z = k(fb, n, 0)?; - let sticky = fb.select(lost, one, z)?; - let m32 = bin(fb, BinOp::BitwiseOr, t32.lo, sticky)?; - let f32f = to.with(Held::Float(FloatFmt::F32)); - let f = if to.float_fmt() == Some(FloatFmt::BFloat) { - narrow::int_to_f32_odd(fb, words_form(n), to, m32)? - } else { - let ft = ops::ty(fb, f32f)?; - fb.convert(ConvOp::ConvertUToF, m32, ft)? - }; - fb.glsl(GlslOp::Ldexp, &[f, s])? - }; - let r = match is_neg { - Some(c) => { - let nr = fb.unary(UnOp::FNegate, r)?; - fb.select(c, nr, r)? - } - None => r, - }; - narrow::round_integer(fb, to, r) -} - -/// A numeric cast with a wide side. -pub fn cast( - fb: &mut FunctionBuilder<'_>, - kind: CastKind, - from: Form, - to: Form, - x: SValue, -) -> BResult { - match kind { - CastKind::Trunc | CastKind::ZExt | CastKind::SExt => { - let p = to_pair(fb, from, x, kind == CastKind::SExt)?; - from_pair(fb, to, p) - } - CastKind::FpToUi | CastKind::FpToSi => { - let p = float_to_pair(fb, from, to, x, kind == CastKind::FpToSi)?; - from_pair(fb, to, p) - } - CastKind::UiToFp | CastKind::SiToFp => { - pair_to_float(fb, from, to, x, kind == CastKind::SiToFp) - } - CastKind::FpResize => Err(arity_error()), - } -} - -/// `air.convert` with a wide side (saturating from a float, and its honored suffixes, as -/// `math::convert`). -pub fn convert( - fb: &mut FunctionBuilder<'_>, - kind: ConvertKind, - from: Form, - to: Form, - x: SValue, -) -> BResult { - match kind { - ConvertKind::Int { signed, saturate } => { - let signed = signed && !from.is_bool(); - let mut p = to_pair(fb, from, x, signed)?; - // `.sat`: the pair (sign-extended to 64 bits where signed) clamped to the - // destination's range, each bound as its 64-bit two's complement. - if let Some(dst) = saturate { - let (lo, hi) = - math::saturation_bounds(signed, from.bits(), dst == Sign::Signed, to.bits()); - let (lt, gt) = if signed { - (IntPredicate::Slt, IntPredicate::Sgt) - } else { - (IntPredicate::Ult, IntPredicate::Ugt) - }; - for (bound, pred) in [(lo, lt), (hi, gt)] { - if let Some(b) = bound { - let c = pk(fb, from.lanes, b as u64)?; - let past = compare(fb, pred, p, c)?; - p = sel(fb, past, c, p)?; - } - } - } - from_pair(fb, to, p) - } - ConvertKind::ToFloat { signed, directed } => { - let r = pair_to_float(fb, from, to, x, signed)?; - match directed { - Some(mode) => { - let back = |fb: &mut FunctionBuilder<'_>, r: SValue| { - let kind = ConvertKind::ToInt { - signed, - round: None, - }; - convert(fb, kind, to, from, r) - }; - let cmp = - |fb: &mut FunctionBuilder<'_>, pred: IntPredicate, a: SValue, b: SValue| { - int_compare(fb, pred, from, a, b) - }; - let d = math::Directed { - mode, - signed, - from, - to, - }; - math::directed_to_float(fb, d, x, r, (&back, &cmp)) - } - None => Ok(r), - } - } - ConvertKind::ToInt { signed, round } => { - // The NaN test reads `x`; the clamp, the bounds and the conversion read its integral - // value. - let xr = math::integral(fb, round, x)?; - let nb = u32::from(to.bits()); - let fw = from.container(); - let kk = if signed { nb - 1 } else { nb }; - // Clamp into [lo, the largest float below 2^k] so the conversion is in range. - let lo = if signed { - let lo = math::pow2_bits(fw, kk); - let (mb, _, top) = math::float_layout(fw); - let lo = if lo >> mb == top as u64 { - math::below_pow2_bits(fw, kk) - } else { - lo - }; - ops::splat(fb, from, lo | (1u64 << (fw - 1)))? - } else { - ops::fsplat(fb, from, 0.0)? - }; - let hi = ops::splat(fb, from, math::below_pow2_bits(fw, kk))?; - let c = fb.glsl(GlslOp::NClamp, &[xr, lo, hi])?; - let n = to.lanes; - let mut p = float_to_pair(fb, from, to, c, signed)?; - let limit = ops::splat(fb, from, math::pow2_bits(fw, kk))?; - let over = bin(fb, BinOp::FOrdGreaterThanEqual, xr, limit)?; - let max = pk(fb, n, ops::ones(kk as u8))?; - p = sel(fb, over, max, p)?; - if signed { - let under = bin(fb, BinOp::FOrdLessThan, xr, lo)?; - let min = pk(fb, n, (!0u64) << (nb - 1))?; - p = sel(fb, under, min, p)?; - let nan = fb.unary(UnOp::IsNan, x)?; - let z = pk(fb, n, 0)?; - p = sel(fb, nan, z, p)?; - } - from_pair(fb, to, p) - } - // A wide value is held zero-extended, so it is zero exactly when both words are. - ConvertKind::IntToBool => { - let p = split(fb, x)?; - let z = pk(fb, from.lanes, 0)?; - compare(fb, IntPredicate::Ne, p, z) - } - // The value as an `f32` (exact), then the saturating conversion. - ConvertKind::Fp8ToInt { fp8, signed } => { - let f = from.with(Held::Float(FloatFmt::F32)); - let v = narrow::fp8_to_f32(fb, fp8, narrow::u32_form(from), f, x)?; - let kind = ConvertKind::ToInt { - signed, - round: None, - }; - convert(fb, kind, f, to, v) - } - ConvertKind::Float | ConvertKind::FromFp8(_) | ConvertKind::ToBool => Err(arity_error()), - } -} - -/// The words of wide value `x` of form `f`, lane by lane, low word first (`2 * lanes` words). -pub fn to_words(fb: &mut FunctionBuilder<'_>, f: Form, x: SValue) -> BResult> { - let p = split(fb, x)?; - if f.lanes == 1 { - return Ok(vec![p.lo, p.hi]); - } - let mut out = Vec::with_capacity(2 * usize::from(f.lanes)); - for i in 0..u32::from(f.lanes) { - out.push(fb.composite_extract(p.lo, &[i])?); - out.push(fb.composite_extract(p.hi, &[i])?); - } - Ok(out) -} - -/// The wide value of form `f` from its words, lane by lane, low word first (a missing high word -/// is zero); the bits above the width are cleared. -pub fn from_words(fb: &mut FunctionBuilder<'_>, f: Form, ws: &[SValue]) -> BResult { - let word = |fb: &mut FunctionBuilder<'_>, i: usize| -> BResult { - match ws.get(i) { - Some(w) => Ok(*w), - None => k(fb, 1, 0), - } - }; - let p = if f.lanes == 1 { - Pair { - lo: word(fb, 0)?, - hi: word(fb, 1)?, - } - } else { - let t = ops::ty(fb, words_form(f.lanes))?; - let mut los = Vec::with_capacity(usize::from(f.lanes)); - let mut his = Vec::with_capacity(usize::from(f.lanes)); - for i in 0..usize::from(f.lanes) { - los.push(word(fb, 2 * i)?); - his.push(word(fb, 2 * i + 1)?); - } - Pair { - lo: fb.composite_construct(t, &los)?, - hi: fb.composite_construct(t, &his)?, - } - }; - let p = mask_top(fb, f, p)?; - join(fb, f, p) -} - -/// A bitcast with a wide side through 32-bit words (both sides 64 bits per wide lane). -pub fn bitcast(fb: &mut FunctionBuilder<'_>, from: Form, to: Form, x: SValue) -> BResult { - let total = u32::from(from.bits()) * u32::from(from.lanes); - let n = u8::try_from(total / 32).map_err(|_| arity_error())?; - let ws = if from.is_wide() { - to_words(fb, from, x)? - } else { - ops::pack_words(fb, from, n, x)? - }; - if to.is_wide() { - from_words(fb, to, &ws) - } else { - ops::unpack_words(fb, to, &ws) - } -} - -/// The low word of wide scalar `x`, or of a 64-bit integer (the index word of a GEP). -pub fn low_word(fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult { - let t = fb.value_ty(x)?; - if matches!(fb.module().types().get(t)?, Type::Vector { .. }) { - return fb.composite_extract(x, &[0]); - } - let u = ops::ty(fb, words_form(1))?; - fb.convert(ConvOp::UConvert, x, u) -} - -/// `u32` value `w` zero-extended to integer form `f` (a 32- or 64-bit container, or wide). -pub fn zext_word(fb: &mut FunctionBuilder<'_>, f: Form, w: SValue) -> BResult { - if f.is_wide() { - let z = k(fb, f.lanes, 0)?; - return join(fb, f, Pair { lo: w, hi: z }); - } - if f.container() == 32 { - return Ok(w); - } - let t = ops::ty(fb, f)?; - fb.convert(ConvOp::UConvert, w, t) -} - -/// A `u32` result `r` (of `f`'s lanes) as a wide value of form `f`. -fn widened(fb: &mut FunctionBuilder<'_>, f: Form, r: SValue) -> BResult { - let z = k(fb, f.lanes, 0)?; - join(fb, f, Pair { lo: r, hi: z }) -} - -/// `u32` operand `v` (a scalar) in every lane of `n`. -fn broadcast(fb: &mut FunctionBuilder<'_>, n: u8, v: SValue) -> BResult { - if n == 1 { - return Ok(v); - } - let t = ops::ty(fb, words_form(n))?; - fb.composite_construct(t, &vec![v; usize::from(n)]) -} - -/// The byte-reversed word `w`. -fn bswap32(fb: &mut FunctionBuilder<'_>, n: u8, w: SValue) -> BResult { - let mut acc: Option = None; - for i in 0..4u32 { - let b = bink(fb, n, BinOp::ShiftRightLogical, w, 8 * i)?; - let b = bink(fb, n, BinOp::BitwiseAnd, b, 0xFF)?; - let b = bink(fb, n, BinOp::ShiftLeftLogical, b, 8 * (3 - i))?; - acc = Some(match acc { - None => b, - Some(a) => bin(fb, BinOp::BitwiseOr, a, b)?, - }); - } - acc.ok_or_else(arity_error) -} - -/// The high 64 bits of the 128-bit product of unsigned pairs `a` and `b`. -fn mul_hi_u(fb: &mut FunctionBuilder<'_>, n: u8, a: Pair, b: Pair) -> BResult { - let mx = |fb: &mut FunctionBuilder<'_>, x, y| -> BResult { - let p = bin(fb, BinOp::UMulExtended, x, y)?; - Ok(Pair { - lo: fb.composite_extract(p, &[0])?, - hi: fb.composite_extract(p, &[1])?, - }) - }; - let z = k(fb, n, 0)?; - let p00 = mx(fb, a.lo, b.lo)?; - let p01 = mx(fb, a.lo, b.hi)?; - let p10 = mx(fb, a.hi, b.lo)?; - let p11 = mx(fb, a.hi, b.hi)?; - // Word 1 of the product: p00.hi + p01.lo + p10.lo, whose carries go to words 2 and 3. - let s1 = add(fb, Pair { lo: p00.hi, hi: z }, Pair { lo: p01.lo, hi: z })?; - let s1 = add(fb, s1, Pair { lo: p10.lo, hi: z })?; - // Words 2 and 3: p11 + p01.hi + p10.hi + the carry of word 1. - let r = add(fb, p11, Pair { lo: p01.hi, hi: z })?; - let r = add(fb, r, Pair { lo: p10.hi, hi: z })?; - add(fb, r, Pair { lo: s1.hi, hi: z }) -} - -/// The high 64 bits of the 128-bit product of pairs `a` and `b`: unsigned, or, when `signed`, of -/// the sign-extended pairs read as two's complement (the unsigned high half less `b` where -/// `a < 0` and less `a` where `b < 0`, modulo `2^64`). -fn mul_high(fb: &mut FunctionBuilder<'_>, n: u8, a: Pair, b: Pair, signed: bool) -> BResult { - let mut hi = mul_hi_u(fb, n, a, b)?; - if signed { - let z = pk(fb, n, 0)?; - let an = negative(fb, n, a)?; - let bn = negative(fb, n, b)?; - let tb = sel(fb, an, b, z)?; - let ta = sel(fb, bn, a, z)?; - hi = sub(fb, hi, tb)?; - hi = sub(fb, hi, ta)?; - } - Ok(hi) -} - -/// The 128-bit product of pairs `a` and `b` as its low and high 64 bits ([`mul_high`]). -fn mul_full( - fb: &mut FunctionBuilder<'_>, - n: u8, - a: Pair, - b: Pair, - signed: bool, -) -> BResult<(Pair, Pair)> { - Ok((mul(fb, a, b)?, mul_high(fb, n, a, b, signed)?)) -} - -/// Bits `[bits, 2 * bits)` of the 128-bit value `(lo, hi)` (unmasked above `bits`). -fn product_high( - fb: &mut FunctionBuilder<'_>, - n: u8, - bits: u8, - lo: Pair, - hi: Pair, -) -> BResult { - if bits >= 64 { - return Ok(hi); - } - let down = lshr_const(fb, n, lo, u32::from(bits))?; - let up = shl_const(fb, n, hi, u32::from(64 - bits))?; - per_word(fb, BinOp::BitwiseOr, down, up) -} - -/// `x mod bits` of pair `x` as a word, for a width of 33 to 64 bits: its low six bits at 64, else -/// `((hi mod bits) * (2^32 mod bits) + lo mod bits) mod bits`, in which no word overflows. -fn amount_mod(fb: &mut FunctionBuilder<'_>, n: u8, bits: u8, x: Pair) -> BResult { - if bits >= 64 { - return bink(fb, n, BinOp::BitwiseAnd, x.lo, 63); - } - let w = u32::from(bits); - let hm = bink(fb, n, BinOp::UMod, x.hi, w)?; - let hm = bink(fb, n, BinOp::IMul, hm, ((1u64 << 32) % u64::from(w)) as u32)?; - let lm = bink(fb, n, BinOp::UMod, x.lo, w)?; - let s = bin(fb, BinOp::IAdd, hm, lm)?; - bink(fb, n, BinOp::UMod, s, w) -} - -/// `a * b + c` saturated to the width of `f` from the exact 128-bit result (`a`, `b`, `c` the -/// operands' pairs, sign-extended when `signed`). -fn mad_sat( - fb: &mut FunctionBuilder<'_>, - f: Form, - signed: bool, - a: Pair, - b: Pair, - c: Pair, -) -> BResult { - let n = f.lanes; - let bits = f.bits(); - let (lo, hi) = mul_full(fb, n, a, b, signed)?; - let lo = add(fb, lo, c)?; - let carry = compare(fb, IntPredicate::Ult, lo, c)?; - let one = pk(fb, n, 1)?; - let z = pk(fb, n, 0)?; - let cp = sel(fb, carry, one, z)?; - let mut hi = add(fb, hi, cp)?; - if !signed { - let max = pk(fb, n, ops::ones(bits))?; - let zero = compare(fb, IntPredicate::Eq, hi, z)?; - let fits = if bits < 64 { - let le = compare(fb, IntPredicate::Ule, lo, max)?; - bin(fb, BinOp::LogicalAnd, zero, le)? - } else { - zero - }; - return sel(fb, fits, lo, max); - } - // A negative addend adds its sign extension, -1, to the high half. - let cn = negative(fb, n, c)?; - let all = pk(fb, n, u64::MAX)?; - let ext = sel(fb, cn, all, z)?; - hi = add(fb, hi, ext)?; - // The result is one 64-bit value when the high half is the low half's sign extension. - let s = bink(fb, n, BinOp::ShiftRightArithmetic, lo.hi, 31)?; - let fits = compare(fb, IntPredicate::Eq, hi, Pair { lo: s, hi: s })?; - let min = pk(fb, n, (!0u64) << (bits - 1))?; - let max = pk(fb, n, ops::ones(bits - 1))?; - let under = compare(fb, IntPredicate::Slt, lo, min)?; - let r = sel(fb, under, min, lo)?; - let over = compare(fb, IntPredicate::Slt, max, r)?; - let r = sel(fb, over, max, r)?; - let neg = negative(fb, n, hi)?; - let sat = sel(fb, neg, min, max)?; - sel(fb, fits, r, sat) -} - -/// Integer function `op` on wide values of form `f` (the implemented set: [`int_fn_lowered`]). -pub fn int_fn( - fb: &mut FunctionBuilder<'_>, - op: IntFn, - f: Form, - args: &[SValue], -) -> BResult { - let n = f.lanes; - let arg = |i: usize| -> BResult { args.get(i).copied().ok_or_else(arity_error) }; - let signed = |s: Sign| s == Sign::Signed; - let a = split(fb, arg(0)?)?; - let ext = |fb: &mut FunctionBuilder<'_>, s: Sign, p: Pair| -> BResult { - if signed(s) { - sext_top(fb, f, p) - } else { - Ok(p) - } - }; - let ext_arg = |fb: &mut FunctionBuilder<'_>, s: Sign, i: usize| -> BResult { - let p = split(fb, arg(i)?)?; - ext(fb, s, p) - }; - let lt = |s: Sign| { - if signed(s) { - IntPredicate::Slt - } else { - IntPredicate::Ult - } - }; - let bits = f.bits(); - let r: Pair = match op { - IntFn::Abs => { - let x = sext_top(fb, f, a)?; - abs(fb, n, x)?.0 - } - IntFn::AbsDiff(s) => { - let (x, y) = (ext(fb, s, a)?, ext_arg(fb, s, 1)?); - let c = compare(fb, lt(s), y, x)?; - let d1 = sub(fb, x, y)?; - let d2 = sub(fb, y, x)?; - sel(fb, c, d1, d2)? - } - IntFn::Min(s) | IntFn::Max(s) | IntFn::Min3(s) | IntFn::Max3(s) => { - let max = matches!(op, IntFn::Max(_) | IntFn::Max3(_)); - let pick = |fb: &mut FunctionBuilder<'_>, x: Pair, y: Pair| -> BResult { - let c = compare(fb, lt(s), x, y)?; - if max { - sel(fb, c, y, x) - } else { - sel(fb, c, x, y) - } - }; - let (x, y) = (ext(fb, s, a)?, ext_arg(fb, s, 1)?); - let mut r = pick(fb, x, y)?; - if matches!(op, IntFn::Min3(_) | IntFn::Max3(_)) { - let z = ext_arg(fb, s, 2)?; - r = pick(fb, r, z)?; - } - r - } - IntFn::Median3(s) => { - let (x, y) = (ext(fb, s, a)?, ext_arg(fb, s, 1)?); - let z = ext_arg(fb, s, 2)?; - let c = compare(fb, lt(s), x, y)?; - let (lo, hi) = (sel(fb, c, x, y)?, sel(fb, c, y, x)?); - let c = compare(fb, lt(s), hi, z)?; - let mid = sel(fb, c, hi, z)?; - let c = compare(fb, lt(s), lo, mid)?; - sel(fb, c, mid, lo)? - } - IntFn::Clamp(s) => { - let x = ext(fb, s, a)?; - let lo = ext_arg(fb, s, 1)?; - let hi = ext_arg(fb, s, 2)?; - let below = compare(fb, lt(s), x, lo)?; - let r = sel(fb, below, lo, x)?; - let above = compare(fb, lt(s), hi, r)?; - sel(fb, above, hi, r)? - } - IntFn::AddSat(s) | IntFn::SubSat(s) => { - let add_op = matches!(op, IntFn::AddSat(_)); - let (x, y) = (ext(fb, s, a)?, ext_arg(fb, s, 1)?); - let r = if add_op { - add(fb, x, y)? - } else { - sub(fb, x, y)? - }; - if !signed(s) { - if add_op { - // Below 64 bits the sum cannot wrap: clamp to the width's maximum. - let max = pk(fb, n, ops::ones(bits))?; - let over = if bits < 64 { - compare(fb, IntPredicate::Ult, max, r)? - } else { - compare(fb, IntPredicate::Ult, r, x)? - }; - sel(fb, over, max, r)? - } else { - let under = compare(fb, IntPredicate::Ult, x, y)?; - let z = pk(fb, n, 0)?; - sel(fb, under, z, r)? - } - } else { - let min = pk(fb, n, (!0u64) << (bits - 1))?; - let max = pk(fb, n, ops::ones(bits - 1))?; - if bits < 64 { - // One bit more than the width: no wrap; clamp to [MIN, MAX]. - let under = compare(fb, IntPredicate::Slt, r, min)?; - let r = sel(fb, under, min, r)?; - let over = compare(fb, IntPredicate::Slt, max, r)?; - sel(fb, over, max, r)? - } else { - // Overflow iff the result's sign differs from what the operands allow. - let xs = bin(fb, BinOp::BitwiseXor, x.hi, r.hi)?; - let t = if add_op { - bin(fb, BinOp::BitwiseXor, y.hi, r.hi)? - } else { - bin(fb, BinOp::BitwiseXor, x.hi, y.hi)? - }; - let both = bin(fb, BinOp::BitwiseAnd, xs, t)?; - let z = k(fb, n, 0)?; - let over = bin(fb, BinOp::SLessThan, both, z)?; - let xn = negative(fb, n, x)?; - let sat = sel(fb, xn, min, max)?; - sel(fb, over, sat, r)? - } - } - } - IntFn::HAdd(s) | IntFn::RHAdd(s) => { - let (x, y) = (ext(fb, s, a)?, ext_arg(fb, s, 1)?); - let one = k(fb, n, 1)?; - let kind = if signed(s) { - Shift::Arithmetic - } else { - Shift::Logical - }; - let hx = shift(fb, n, kind, x, one)?; - let hy = shift(fb, n, kind, y, one)?; - let both = if matches!(op, IntFn::HAdd(_)) { - bin(fb, BinOp::BitwiseAnd, x.lo, y.lo)? - } else { - bin(fb, BinOp::BitwiseOr, x.lo, y.lo)? - }; - let carry = bin(fb, BinOp::BitwiseAnd, both, one)?; - let z = k(fb, n, 0)?; - let r = add(fb, hx, hy)?; - add(fb, r, Pair { lo: carry, hi: z })? - } - IntFn::MulHi(s) | IntFn::MadHi(s) => { - // Bits [N, 2N) of the exact product of the operands (sign-extended when signed). - let (x, y) = (ext(fb, s, a)?, ext_arg(fb, s, 1)?); - let mut h = if bits >= 64 { - mul_high(fb, n, x, y, signed(s))? - } else { - let (lo, hi) = mul_full(fb, n, x, y, signed(s))?; - product_high(fb, n, bits, lo, hi)? - }; - if matches!(op, IntFn::MadHi(_)) { - let c = split(fb, arg(2)?)?; - h = add(fb, h, c)?; - } - h - } - IntFn::MadSat(s) => { - let (x, y) = (ext(fb, s, a)?, ext_arg(fb, s, 1)?); - let c = ext_arg(fb, s, 2)?; - mad_sat(fb, f, signed(s), x, y, c)? - } - IntFn::ExtractBits(s) => { - // (x << (64 - o - c)) >> (64 - c), 0 for a zero count (as `extract_bits64`). - let o = broadcast(fb, n, arg(1)?)?; - let c = broadcast(fb, n, arg(2)?)?; - let z = k(fb, n, 0)?; - let none = bin(fb, BinOp::IEqual, c, z)?; - let k64 = k(fb, n, 64)?; - let up = bin(fb, BinOp::ISub, k64, o)?; - let up = bin(fb, BinOp::ISub, up, c)?; - let down = bin(fb, BinOp::ISub, k64, c)?; - let v = shl(fb, n, a, up)?; - let kind = if signed(s) { - Shift::Arithmetic - } else { - Shift::Logical - }; - let v = shift(fb, n, kind, v, down)?; - let zp = pk(fb, n, 0)?; - sel(fb, none, zp, v)? - } - IntFn::InsertBits => { - let y = split(fb, arg(1)?)?; - let o = broadcast(fb, n, arg(2)?)?; - let c = broadcast(fb, n, arg(3)?)?; - let z = k(fb, n, 0)?; - let none = bin(fb, BinOp::IEqual, c, z)?; - let k64 = k(fb, n, 64)?; - let down = bin(fb, BinOp::ISub, k64, c)?; - let all = pk(fb, n, u64::MAX)?; - let m = lshr(fb, n, all, down)?; - let zp = pk(fb, n, 0)?; - let m = sel(fb, none, zp, m)?; - let m = shl(fb, n, m, o)?; - let keep = Pair { - lo: fb.unary(UnOp::Not, m.lo)?, - hi: fb.unary(UnOp::Not, m.hi)?, - }; - let keep = per_word(fb, BinOp::BitwiseAnd, a, keep)?; - let ins = shl(fb, n, y, o)?; - let ins = per_word(fb, BinOp::BitwiseAnd, ins, m)?; - per_word(fb, BinOp::BitwiseOr, keep, ins)? - } - IntFn::Popcount => { - let cl = fb.unary(UnOp::BitCount, a.lo)?; - let ch = fb.unary(UnOp::BitCount, a.hi)?; - let r = bin(fb, BinOp::IAdd, cl, ch)?; - return widened(fb, f, r); - } - IntFn::ReverseBits => { - let full = Pair { - lo: fb.unary(UnOp::BitReverse, a.hi)?, - hi: fb.unary(UnOp::BitReverse, a.lo)?, - }; - let pad = k(fb, n, u32::from(64 - bits))?; - lshr(fb, n, full, pad)? - } - IntFn::Bswap => { - let full = Pair { - lo: bswap32(fb, n, a.hi)?, - hi: bswap32(fb, n, a.lo)?, - }; - let pad = k(fb, n, u32::from(64 - bits))?; - lshr(fb, n, full, pad)? - } - IntFn::Rotate | IntFn::Fshl | IntFn::Fshr => { - // Every shift is in range: s = amount mod N, and the second shift is by N - 1 - s - // after a shift by one (the bits above N are masked below). - let (y, amount) = match op { - IntFn::Rotate => (a, arg(1)?), - _ => (split(fb, arg(1)?)?, arg(2)?), - }; - let amount = split(fb, amount)?; - let s = amount_mod(fb, n, bits, amount)?; - let n1 = k(fb, n, u32::from(bits) - 1)?; - let rest = bin(fb, BinOp::ISub, n1, s)?; - if op == IntFn::Fshr { - // (y >> s) | ((a << 1) << (N - 1 - s)). - let lo = lshr(fb, n, y, s)?; - let a1 = shl_const(fb, n, a, 1)?; - let hi = shl(fb, n, a1, rest)?; - per_word(fb, BinOp::BitwiseOr, hi, lo)? - } else { - // (a << s) | ((y >> 1) >> (N - 1 - s)). - let hi = shl(fb, n, a, s)?; - let y1 = lshr_const(fb, n, y, 1)?; - let lo = lshr(fb, n, y1, rest)?; - per_word(fb, BinOp::BitwiseOr, hi, lo)? - } - } - IntFn::Clz => { - // 31 - FindUMsb(w) is 32 for a zero word. - let k31 = k(fb, n, 31)?; - let mh = fb.glsl(GlslOp::FindUMsb, &[a.hi])?; - let ch = bin(fb, BinOp::ISub, k31, mh)?; - let ml = fb.glsl(GlslOp::FindUMsb, &[a.lo])?; - let cl = bin(fb, BinOp::ISub, k31, ml)?; - let cl = bink(fb, n, BinOp::IAdd, cl, 32)?; - let z = k(fb, n, 0)?; - let hz = bin(fb, BinOp::IEqual, a.hi, z)?; - let r = fb.select(hz, cl, ch)?; - let r = bink(fb, n, BinOp::ISub, r, u32::from(64 - bits))?; - return widened(fb, f, r); - } - IntFn::Ctz => { - let z = k(fb, n, 0)?; - let ll = fb.glsl(GlslOp::FindILsb, &[a.lo])?; - let lh = fb.glsl(GlslOp::FindILsb, &[a.hi])?; - let lh = bink(fb, n, BinOp::IAdd, lh, 32)?; - let lnz = bin(fb, BinOp::INotEqual, a.lo, z)?; - let r = fb.select(lnz, ll, lh)?; - let zero = compare(fb, IntPredicate::Eq, a, Pair { lo: z, hi: z })?; - let w = k(fb, n, u32::from(bits))?; - let r = fb.select(zero, w, r)?; - return widened(fb, f, r); - } - }; - let r = mask_top(fb, f, r)?; - join(fb, f, r) -} - -/// Whether integer function `op` is lowered on wide values of form `f`: every one, `bswap` on -/// whole 16-bit units (as LLVM defines it). -pub fn int_fn_lowered(op: IntFn, f: Form) -> bool { - match op { - IntFn::Bswap => f.bits().is_multiple_of(16), - _ => true, - } -} - -// ---- Strategy ---- - -/// A lowering of an instruction with a wide operand or result. -#[derive(Clone, Debug, PartialEq, Eq)] -pub enum WideOp { - /// An integer binary operator on wide values of `form`. - Bin { op: AirBin, form: Form }, - /// `icmp` on wide values of `form`. - Compare { pred: IntPredicate, form: Form }, - /// A numeric cast with a wide side. - Cast { - kind: CastKind, - from: Form, - to: Form, - }, - /// `air.convert` with a wide side. - Convert { - kind: ConvertKind, - from: Form, - to: Form, - }, - /// A bitcast with a wide side, through 32-bit words. - Bitcast { from: Form, to: Form }, - /// `select` of wide values of `form`: of the pair on a scalar (its condition is a scalar), - /// word by word on a vector (its condition may be a vector). - Select { form: Form }, - /// `extractelement` from a vector of form `vec` (wide or not): lane `at`, or the lane a - /// dynamic index names (wide when `wide_index`). - Extract { - vec: Form, - at: Option, - wide_index: bool, - }, - /// `insertelement` into a vector of form `vec`, as [`WideOp::Extract`]. - Insert { - vec: Form, - at: Option, - wide_index: bool, - }, - /// `shufflevector` of wide vectors into form `out`: result lane `i` is lane `mask[i]` of the - /// concatenation. - Shuffle { mask: Box<[u32]>, out: Form }, - /// An integer function on wide values of `form`. - IntFn { f: IntFn, form: Form }, -} - -impl WideOp { - /// The census name. - pub fn name(&self) -> &'static str { - match self { - WideOp::Bin { op, .. } if is_division(*op) => DIVIDE, - WideOp::Bin { .. } => "arith.wide.int", - WideOp::Compare { .. } => "arith.wide.compare", - WideOp::Cast { .. } => "arith.wide.cast", - WideOp::Convert { .. } => "arith.wide.convert", - WideOp::Bitcast { .. } => "arith.wide.bitcast", - WideOp::Select { .. } => "arith.wide.select", - WideOp::Extract { .. } | WideOp::Insert { .. } => "arith.wide.element", - WideOp::Shuffle { .. } => "arith.wide.shuffle", - WideOp::IntFn { .. } => "arith.wide.int_fn", - } - } - - /// An upper estimate of the SPIR-V words per use, at most 6 words per instruction. A division's - /// is its call (measured at most 11 words for an unsigned one and 207 for a signed one, - /// `wide_division_words_bound_their_emission`); its routine's are the module's, once - /// ([`Divide::words`]). - pub fn words(&self) -> u32 { - match self { - WideOp::Bin { op, .. } if is_division(*op) => { - if matches!(op, AirBin::SDiv | AirBin::SRem) { - 384 - } else { - 32 - } - } - WideOp::Bin { .. } => 192, - WideOp::Compare { .. } => 96, - // A directed conversion to `f32` adds the conversion back and the step. - WideOp::Convert { - kind: - ConvertKind::ToFloat { - directed: Some(_), .. - }, - .. - } => 2048, - WideOp::Cast { .. } | WideOp::Convert { .. } => { - // The float paths: the collapse to 32 bits (two shifts, a compare) and rounding. - 1024 - } - WideOp::Bitcast { from, to } => { - 64 + 96 * u32::from(from.lanes.max(to.lanes)) + narrow_words(*from, *to) - } - // A scalar's is one `OpSelect` of the pair (6 words); a vector's the operands' splits - // (four 5-word extracts), two selects, and the join (37). - WideOp::Select { form } if form.lanes == 1 => 8, - WideOp::Select { .. } => 40, - WideOp::Extract { .. } | WideOp::Insert { .. } => 64, - // The operands' splits (20 words), two `OpVectorShuffle` of 5 words plus one per - // lane, and the join (5). - WideOp::Shuffle { mask, .. } => 40 + 2 * u32::try_from(mask.len()).unwrap_or(u32::MAX), - // Measured at most 712 words for a signed `mad_sat` and 452 for every other function - // (`wide_integer_function_words_bound_their_emission`). - WideOp::IntFn { f, .. } => match f { - IntFn::MadSat(_) => 1024, - IntFn::Bswap => 512, - _ => 640, - }, - } - } - - /// The module-scope routine the operation calls, if any: a division's. - pub fn routine(&self) -> Option { - match self { - WideOp::Bin { op, form } if is_division(*op) => Some(Divide::of(*form)), - _ => None, - } - } - - /// The operands the operation reads (a prefix of the instruction's; all when `None`). - pub fn arity(&self) -> Option { - match self { - WideOp::Cast { .. } | WideOp::Convert { .. } | WideOp::Bitcast { .. } => Some(1), - WideOp::Extract { at: Some(_), .. } => Some(1), - WideOp::Insert { at: Some(_), .. } => Some(2), - WideOp::IntFn { f, .. } => Some(f.arity()), - _ => None, - } - } -} - -/// The words a bitcast spends moving narrow floats to or from their bits. -fn narrow_words(from: Form, to: Form) -> u32 { - let one = |f: Form| { - if f.is_narrow() { - 192 * u32::from(f.lanes) - } else { - 0 - } - }; - one(from) + one(to) -} - -/// Emit `op` on operand values `xs`; `routine` is the module's function of [`WideOp::routine`] -/// when the operation has one. -pub fn emit( - fb: &mut FunctionBuilder<'_>, - op: &WideOp, - xs: &[SValue], - routine: Option, -) -> BResult { - let a = |i: usize| -> BResult { xs.get(i).copied().ok_or_else(arity_error) }; - match op { - WideOp::Bin { op, form } if is_division(*op) => { - let r = routine.ok_or_else(missing_routine)?; - divide(fb, *op, *form, a(0)?, a(1)?, r) - } - WideOp::Bin { op, form } => binary(fb, *op, *form, a(0)?, a(1)?), - WideOp::Compare { pred, form } => int_compare(fb, *pred, *form, a(0)?, a(1)?), - WideOp::Cast { kind, from, to } => cast(fb, *kind, *from, *to, a(0)?), - WideOp::Convert { kind, from, to } => convert(fb, *kind, *from, *to, a(0)?), - WideOp::Bitcast { from, to } => bitcast(fb, *from, *to, a(0)?), - WideOp::Select { form } if form.lanes == 1 => fb.select(a(0)?, a(1)?, a(2)?), - WideOp::Select { form } => { - let (c, t, f) = (a(0)?, split(fb, a(1)?)?, split(fb, a(2)?)?); - let r = sel(fb, c, t, f)?; - join(fb, *form, r) - } - WideOp::Extract { - vec, - at, - wide_index, - } => { - let v = a(0)?; - let i = match at { - Some(_) => None, - None => Some(index(fb, a(1)?, *wide_index)?), - }; - let lane = |fb: &mut FunctionBuilder<'_>, w: SValue| -> BResult { - match (at, i) { - (Some(at), _) => fb.composite_extract(w, &[*at]), - (None, Some(i)) => fb.vector_extract_dynamic(w, i), - (None, None) => Err(arity_error()), - } - }; - if vec.is_wide() { - let p = split(fb, v)?; - let r = Pair { - lo: lane(fb, p.lo)?, - hi: lane(fb, p.hi)?, - }; - join(fb, vec.scalar_form(), r) - } else { - let y = lane(fb, v)?; - // A store of a narrow lane takes its bits from its vector's. - if let Some(at) = at { - if super::narrow::may_be_narrow(fb, y)? { - fb.note_lane(y, v, *at); - } - } - Ok(y) - } - } - WideOp::Insert { - vec, - at, - wide_index, - } => { - let (v, e) = (a(0)?, a(1)?); - let i = match at { - Some(_) => None, - None => Some(index(fb, a(2)?, *wide_index)?), - }; - let put = |fb: &mut FunctionBuilder<'_>, w: SValue, x: SValue| -> BResult { - match (at, i) { - (Some(at), _) => fb.composite_insert(x, w, &[*at]), - (None, Some(i)) => fb.vector_insert_dynamic(w, x, i), - (None, None) => Err(arity_error()), - } - }; - if vec.is_wide() { - let (p, x) = (split(fb, v)?, split(fb, e)?); - let r = Pair { - lo: put(fb, p.lo, x.lo)?, - hi: put(fb, p.hi, x.hi)?, - }; - join(fb, *vec, r) - } else { - // Narrow lanes' bits follow the insert. - match at { - Some(at) => super::narrow::insert(fb, v, e, *at), - None => put(fb, v, e), - } - } - } - WideOp::Shuffle { mask, out } => { - let (p, q) = (split(fb, a(0)?)?, split(fb, a(1)?)?); - let r = Pair { - lo: fb.vector_shuffle(p.lo, q.lo, mask)?, - hi: fb.vector_shuffle(p.hi, q.hi, mask)?, - }; - join(fb, *out, r) - } - WideOp::IntFn { f, form } => int_fn(fb, *f, *form, xs), - } -} - -/// A dynamic element index: a wide one's low word (an index of 2^32 or more is out of range, -/// poison, whatever lane it names). -fn index(fb: &mut FunctionBuilder<'_>, i: SValue, wide: bool) -> BResult { - if wide { - fb.composite_extract(i, &[0]) - } else { - Ok(i) - } -} - -// ---- Selection ---- - -/// Whether `inst` has a wide integer operand or result on the selection's profile, so this -/// module lowers it (aggregate operations, `freeze`, and `select` of aggregates move the -/// representation as it is and stay with the general strategies). -pub fn involved(cx: &SelectCx<'_>, inst: &Inst) -> bool { - if !legal::holds_wide(cx.profile) { - return false; - } - let types = cx.entry.module.types(); - let wide = |t: Option| t.is_some_and(|t| legal::is_wide_int(types, t)); - match &inst.kind { - InstKind::ExtractValue { .. } | InstKind::InsertValue { .. } | InstKind::Freeze(_) => false, - InstKind::Call(call) => { - wide(Some(inst.ty)) || call.args.iter().any(|v| wide(cx.value_ty(*v))) - } - kind => { - let mut any = wide(Some(inst.ty)); - kind.for_each_value(|v| any |= wide(cx.value_ty(v))); - any - } - } -} - -/// The form of `v`, wide where the profile holds it so; with `chunk`, a chunked vector's form is -/// that of one chunk of `chunk` lanes. -fn form(cx: &SelectCx<'_>, v: Value, chunk: Option) -> Result { - type_form(cx, ty_of(cx, v)?, chunk) -} - -fn result_form(cx: &SelectCx<'_>, inst: &Inst, chunk: Option) -> Result { - type_form(cx, inst.ty, chunk) -} - -fn type_form( - cx: &SelectCx<'_>, - ty: crate::air::ir::TypeId, - chunk: Option, -) -> Result { - if let (Some(k), Some((held, _))) = (chunk, legal::chunked(cx.entry.module.types(), ty)) { - return Ok(Form { - held: legal::held_on(cx.profile, held)?, - lanes: k, - }); - } - legal::wide_form_on(cx.entry, cx.profile, ty) -} - -/// Whether a lane-wise operation `inst` on chunked vectors has a wide integer lane on the -/// selection's profile, so this module lowers each chunk ([`select_in`]). -pub fn involved_chunked(cx: &SelectCx<'_>, inst: &Inst) -> bool { - if !legal::holds_wide(cx.profile) { - return false; - } - let types = cx.entry.module.types(); - let wide = |t: Option| { - t.is_some_and(|t| { - legal::chunked(types, t) - .is_some_and(|(h, _)| matches!(h, Held::Int { container: 64, .. })) - || legal::is_wide_int(types, t) - }) - }; - match &inst.kind { - InstKind::Call(call) => { - wide(Some(inst.ty)) || call.args.iter().any(|v| wide(cx.value_ty(*v))) - } - kind => { - let mut any = wide(Some(inst.ty)); - kind.for_each_value(|v| any |= wide(cx.value_ty(v))); - any - } - } -} - -/// Select the lowering of `inst`, which [`involved`] holds. -pub fn select(cx: &mut SelectCx<'_>, at: InstId, inst: &Inst) -> Result { - select_in(cx, at, inst, None) -} - -/// Select `inst`; with `chunk`, for one chunk of `chunk` lanes of a lane-wise operation on -/// chunked vectors of wide integers (its chunked operands and result take the chunk's form). -pub fn select_in( - cx: &mut SelectCx<'_>, - at: InstId, - inst: &Inst, - chunk: Option, -) -> Result { - if let InstKind::Call(call) = &inst.kind { - return select_call(cx, inst, call, chunk); - } - let mut ops = operands_of(&inst.kind); - if let InstKind::ExtractElement { idx, .. } | InstKind::InsertElement { idx, .. } = &inst.kind { - if matches!(idx, Value::Const(_)) { - ops.retain(|v| v != idx); - } - } - check_operands(cx, &ops)?; - let result = cx.lowered_repr(Value::Inst(at), inst.ty)?; - let op = match &inst.kind { - InstKind::BinOp { op, a, .. } => { - let f = form(cx, *a, chunk)?; - if !f.is_wide() || op.is_float() { - return Err(cx.invariant("a wide binary operator on mismatched operands")); - } - WideOp::Bin { op: *op, form: f } - } - InstKind::ICmp { pred, a, .. } => { - let f = form(cx, *a, chunk)?; - if !f.is_wide() { - return Err(cx.invariant("a wide compare on mismatched operands")); - } - WideOp::Compare { - pred: *pred, - form: f, - } - } - InstKind::Cast { op, v } => select_cast(cx, *op, *v, inst, chunk)?, - InstKind::Select { .. } => { - let f = result_form(cx, inst, chunk)?; - if !f.is_wide() { - return Err(cx.invariant("a wide select of a narrow value")); - } - WideOp::Select { form: f } - } - InstKind::ExtractElement { vec, idx } => { - let vf = form(cx, *vec, chunk)?; - let lanes = u64::from(lanes_of(cx, *vec)?); - match (idx, super::const_int(cx, *idx)) { - (Value::Const(_), Some(i)) if i < lanes => WideOp::Extract { - vec: vf, - at: Some(u32::try_from(i).map_err(|_| not_lowered())?), - wide_index: false, - }, - (Value::Const(_), _) => return Ok(ArithStrategy::Undef(result)), - _ => WideOp::Extract { - vec: vf, - at: None, - wide_index: form(cx, *idx, chunk)?.is_wide(), - }, - } - } - InstKind::InsertElement { vec, idx, .. } => { - let vf = form(cx, *vec, chunk)?; - let lanes = u64::from(lanes_of(cx, *vec)?); - match (idx, super::const_int(cx, *idx)) { - (Value::Const(_), Some(i)) if i < lanes => WideOp::Insert { - vec: vf, - at: Some(u32::try_from(i).map_err(|_| not_lowered())?), - wide_index: false, - }, - (Value::Const(_), _) => return Ok(ArithStrategy::Undef(result)), - _ => WideOp::Insert { - vec: vf, - at: None, - wide_index: form(cx, *idx, chunk)?.is_wide(), - }, - } - } - InstKind::ShuffleVector { a, b, mask } => { - let (fa, fb_) = (form(cx, *a, chunk)?, form(cx, *b, chunk)?); - let out = result_form(cx, inst, chunk)?; - if !fa.is_wide() || !fb_.is_wide() || !out.is_wide() || out.lanes == 1 { - return Err(not_lowered()); - } - let total = u32::from(fa.lanes) + u32::from(fb_.lanes); - let mut comps = Vec::with_capacity(mask.len()); - for m in mask.iter() { - // A poison lane may be any value: take component 0. - let c = m.unwrap_or(0); - if c >= total { - return Err(cx.invariant("a shuffle index beyond its operands")); - } - comps.push(c); - } - WideOp::Shuffle { - mask: comps.into(), - out, - } - } - _ => return Err(not_lowered()), - }; - if let Some(d) = op.routine() { - cx.families.arith.divides.insert(d); - } - Ok(ArithStrategy::Wide(op)) -} - -fn select_cast( - cx: &mut SelectCx<'_>, - op: CastOp, - v: Value, - inst: &Inst, - chunk: Option, -) -> Result { - let from = form(cx, v, chunk)?; - let to = result_form(cx, inst, chunk)?; - let int_like = |f: Form| f.is_bool() || f.is_wide() || (f.is_int() && f.container() == 32); - let kind = match op { - CastOp::Trunc => CastKind::Trunc, - CastOp::ZExt => CastKind::ZExt, - CastOp::SExt => CastKind::SExt, - CastOp::FPToUI => CastKind::FpToUi, - CastOp::FPToSI => CastKind::FpToSi, - CastOp::UIToFP => CastKind::UiToFp, - CastOp::SIToFP => CastKind::SiToFp, - CastOp::Bitcast => return select_bitcast(from, to), - CastOp::FPTrunc | CastOp::FPExt => { - return Err(cx.invariant("a float resize with a wide side")) - } - CastOp::PtrToInt | CastOp::IntToPtr | CastOp::AddrSpaceCast => { - return Err(cx.invariant("a pointer cast routed to arith")) - } - }; - let ok = match kind { - CastKind::Trunc | CastKind::ZExt | CastKind::SExt => int_like(from) && int_like(to), - CastKind::FpToUi | CastKind::FpToSi => from.is_float() && to.is_wide(), - CastKind::UiToFp | CastKind::SiToFp => from.is_wide() && to.is_float(), - CastKind::FpResize => false, - }; - if !ok || from.lanes != to.lanes { - return Err(not_lowered()); - } - Ok(WideOp::Cast { kind, from, to }) -} - -fn select_bitcast(from: Form, to: Form) -> Result { - if from == to { - return Err(not_lowered()); - } - let side = |f: Form| { - if f.is_wide() { - f.bits() == 64 - } else { - !f.is_bool() && ops::word_lanes(f) - } - }; - let total = u32::from(from.bits()) * u32::from(from.lanes); - if !side(from) - || !side(to) - || total != u32::from(to.bits()) * u32::from(to.lanes) - || total % 32 != 0 - { - return Err(not_lowered()); - } - Ok(WideOp::Bitcast { from, to }) -} - -fn select_call( - cx: &mut SelectCx<'_>, - inst: &Inst, - call: &crate::air::ir::Call, - chunk: Option, -) -> Result { - let fun = match &call.callee { - Callee::Air { - op: AirIntrinsic::Convert(c), - .. - } => return select_convert(cx, inst, call, c, chunk), - Callee::Air { - op: AirIntrinsic::Math(m), - .. - } => super::air_math(m.f)?, - Callee::Llvm { op, .. } => super::llvm_math(op)?, - _ => return Err(not_lowered()), - }; - let op = match fun { - Fun::Int(f) => f, - // Unsigned `abs` is the operand itself. - Fun::Copy => { - let x = *call - .args - .first() - .ok_or_else(|| cx.invariant("an intrinsic without operands"))?; - check_operands(cx, &[x])?; - super::lowered_type(cx.entry, cx.profile, inst.ty)?; - return Ok(ArithStrategy::Copy); - } - Fun::Float(_) | Fun::SinCos => return Err(not_lowered()), - }; - let args = call - .args - .get(..op.arity()) - .ok_or_else(|| cx.invariant("too few intrinsic operands"))?; - check_operands(cx, args)?; - super::lowered_type(cx.entry, cx.profile, inst.ty)?; - let first = *args - .first() - .ok_or_else(|| cx.invariant("an intrinsic without operands"))?; - let f = form(cx, first, chunk)?; - if !f.is_wide() || !int_fn_lowered(op, f) { - return Err(not_lowered()); - } - // The bit-field offset and count are `u32` scalars. - let fields: &[usize] = match op { - IntFn::ExtractBits(_) => &[1, 2], - IntFn::InsertBits => &[2, 3], - _ => &[], - }; - for i in fields { - let v = *args - .get(*i) - .ok_or_else(|| cx.invariant("too few intrinsic operands"))?; - let vf = form(cx, v, chunk)?; - if !(vf.is_int() && vf.container() == 32 && vf.lanes == 1) { - return Err(not_lowered()); - } - } - // Every other operand has the first one's form. - for (i, v) in args.iter().enumerate() { - if !fields.contains(&i) && form(cx, *v, chunk)? != f { - return Err(not_lowered()); - } - } - Ok(ArithStrategy::Wide(WideOp::IntFn { f: op, form: f })) -} - -fn select_convert( - cx: &mut SelectCx<'_>, - inst: &Inst, - call: &crate::air::ir::Call, - c: &crate::air::intrinsics::Convert, - chunk: Option, -) -> Result { - use crate::air::intrinsics::NumKind; - let x = *call - .args - .first() - .ok_or_else(|| cx.invariant("air.convert without an operand"))?; - check_operands(cx, &[x])?; - super::lowered_type(cx.entry, cx.profile, inst.ty)?; - let from = form(cx, x, chunk)?; - let to = result_form(cx, inst, chunk)?; - if from.lanes != to.lanes { - return Err(not_lowered()); - } - // An 8-bit float to a wide integer: its value, then the saturating conversion. - if let Some(fmt) = c.src_fp8 { - let carrier = from.is_int() && from.bits() == 8; - if c.dst_kind == NumKind::Float || !carrier || !to.is_wide() { - return Err(not_lowered()); - } - cx.precision - .insert(crate::pipeline::artifact::PrecisionNote::Fp8Value); - return Ok(ArithStrategy::Wide(WideOp::Convert { - kind: ConvertKind::Fp8ToInt { - fp8: narrow::Fp8Layout::of(fmt), - signed: c.dst_kind == NumKind::Signed, - }, - from, - to, - })); - } - // A wide integer to `bool` is C++'s `x != 0`. - if to.is_bool() { - if c.src_kind == NumKind::Float || !from.is_wide() { - return Err(not_lowered()); - } - return Ok(ArithStrategy::Wide(WideOp::Convert { - kind: ConvertKind::IntToBool, - from, - to, - })); - } - let kind = match (c.dst_kind, c.src_kind) { - (NumKind::Float, NumKind::Float) => return Err(not_lowered()), - (NumKind::Float, s) => ConvertKind::ToFloat { - signed: s == NumKind::Signed, - directed: None, - }, - (d, NumKind::Float) => ConvertKind::ToInt { - signed: d == NumKind::Signed, - round: None, - }, - (_, s) => ConvertKind::Int { - signed: s == NumKind::Signed, - saturate: None, - }, - }; - let kind = super::honored(cx.inputs.open_cl_mode, c, kind, from, to); - let int_like = |f: Form| f.is_bool() || f.is_wide() || (f.is_int() && f.container() == 32); - let ok = match kind { - ConvertKind::ToFloat { .. } => from.is_wide() && to.is_float(), - ConvertKind::ToInt { .. } => from.is_float() && to.is_wide(), - ConvertKind::Int { .. } => int_like(from) && int_like(to) && !to.is_bool(), - ConvertKind::Float - | ConvertKind::FromFp8(_) - | ConvertKind::Fp8ToInt { .. } - | ConvertKind::ToBool - | ConvertKind::IntToBool => false, - }; - if !ok { - return Err(not_lowered()); - } - Ok(ArithStrategy::Wide(WideOp::Convert { kind, from, to })) -} diff --git a/crates/metal2vulkan/src/lower/emit.rs b/crates/metal2vulkan/src/lower/emit.rs index 50f77a8a7..ba30dfd0f 100644 --- a/crates/metal2vulkan/src/lower/emit.rs +++ b/crates/metal2vulkan/src/lower/emit.rs @@ -775,8 +775,7 @@ impl<'a> EmitCx<'a> { if let Some(b) = val.and_then(|val| access::handle::absent_param(entry, val)) { return access::handle::absent_param_value(self, fb, b); } - let wide = &self.plan.families.arith; - let Some(k) = val.and_then(|val| arith::constant_in(self.entry, wide, val)) else { + let Some(k) = val.and_then(|val| arith::constant(self.entry, val)) else { // A null buffer pointer constant is the null fat pointer. if let Some(x) = access::pointer::null_operand(self, fb, v)? { return Ok(x); @@ -1568,14 +1567,6 @@ impl CodeEmitter for Emitter<'_> { let miss = k(fb, miss)?; fb.select(fits, low, miss) } - SelectorForm::Words { miss } => { - let low = fb.composite_extract(x, &[0])?; - let high = fb.composite_extract(x, &[1])?; - let zero = k(fb, 0)?; - let fits = fb.binary(BinOp::IEqual, high, zero)?; - let miss = k(fb, miss)?; - fb.select(fits, low, miss) - } } } diff --git a/crates/metal2vulkan/src/lower/fragment/color.rs b/crates/metal2vulkan/src/lower/fragment/color.rs index 9b59b3c2c..f822b8403 100644 --- a/crates/metal2vulkan/src/lower/fragment/color.rs +++ b/crates/metal2vulkan/src/lower/fragment/color.rs @@ -95,7 +95,7 @@ pub(super) fn form(cx: &SelectCx<'_>, ty: AirTypeId) -> Result { let held32 = match form.held { Held::Int { container, .. } => container == 32, Held::Float(f) => f.container() == 32, - Held::Bool | Held::Wide { .. } => false, + Held::Bool => false, }; if !held32 || !(1..=4).contains(&form.lanes) { return Err(not_lowered()); diff --git a/crates/metal2vulkan/src/lower/mesh/mod.rs b/crates/metal2vulkan/src/lower/mesh/mod.rs index 9391d025b..0e38f9dfd 100644 --- a/crates/metal2vulkan/src/lower/mesh/mod.rs +++ b/crates/metal2vulkan/src/lower/mesh/mod.rs @@ -343,13 +343,12 @@ pub fn mesh_stages(p: &DeviceProfile) -> bool { /// Whether profile `p` compiles an object function folded (`LoweringInputs::folded_groups`), so /// that its draws run any object grid Metal runs in pieces within the task stage's limits -/// (`bind::mesh_arguments`): it runs mesh functions natively, and has 64-bit integers (the -/// threadgroup's number), `multiDrawIndirect` (a direct draw's pieces, and `maxDrawIndirectCount` -/// at least 65,535) and `drawIndirectCount` (an indirect draw's). +/// (`bind::mesh_arguments`): it runs mesh functions natively, and has `multiDrawIndirect` (a +/// direct draw's pieces, and `maxDrawIndirectCount` at least 65,535) and `drawIndirectCount` (an +/// indirect draw's). pub fn folds_object_grids(p: &DeviceProfile) -> bool { let features = &p.enabled().features; mesh_stages(p) - && features.contains(&VkFeature::ShaderInt64) && features.contains(&VkFeature::MultiDrawIndirect) && features.contains(&VkFeature::DrawIndirectCount) } diff --git a/crates/metal2vulkan/src/lower/sampler/select.rs b/crates/metal2vulkan/src/lower/sampler/select.rs index c564f8693..dfee7a9fa 100644 --- a/crates/metal2vulkan/src/lower/sampler/select.rs +++ b/crates/metal2vulkan/src/lower/sampler/select.rs @@ -1959,7 +1959,7 @@ fn select_one( ImageRef::Slot(index) if texel_op && !shape.depth && crate::lower::texture::swizzled_storage(cx, image)? => { - if form.is_none_or(|f| f.lanes != 4 || matches!(f.conv, TexelConv::U64Words { .. })) { + if form.is_none_or(|f| f.lanes != 4 || matches!(f.conv, TexelConv::U64Words)) { return Err(Unsupported::not_implemented(Feature::TextureSwizzle).into()); } crate::lower::texture::swizzles(cx, index)?; diff --git a/crates/metal2vulkan/src/lower/select.rs b/crates/metal2vulkan/src/lower/select.rs index 1bb9af908..9ee905691 100644 --- a/crates/metal2vulkan/src/lower/select.rs +++ b/crates/metal2vulkan/src/lower/select.rs @@ -48,7 +48,7 @@ use crate::air::Entry; use crate::budget::{tree_bytes, Growth, Meter}; use crate::device::function_storage; use crate::device::profile::Limits; -use crate::device::requirements::{VkFeature, VkLimit}; +use crate::device::requirements::VkLimit; use crate::device::subgroup::{self, SimdClass, SubgroupRequirement, Tier}; use crate::device::DeviceProfile; use crate::error::{ @@ -86,9 +86,6 @@ pub enum SelectorForm { /// An `i64`: its low word when the high word is 0, else `miss`, a `u32` that is no case /// literal of any switch on the value (literals fit 32 bits, WideSwitchLiteral). Narrow64 { miss: u32 }, - /// An `i33`..`i64` held as two words without `shaderInt64`: the low word when the high word is - /// 0, else `miss`, as [`SelectorForm::Narrow64`] reads the 64-bit container. - Words { miss: u32 }, } /// A slot's selected form with its proven use. @@ -1025,23 +1022,13 @@ pub fn miss_literal(literals: &BTreeSet) -> Option { /// /// Each form assumes the lowered value holds the AIR integer zero-extended, so its bits are the /// case literals': an `i8`/`i16` held at its own width, an `Int(2..=32)` in the 32-bit container, -/// an `Int(33..=64)` in the 64-bit one, or, without `shaderInt64`, as two words (a `uvec2`, low -/// word first). Any other pairing of AIR type and representation is not a form this function knows -/// and is refused until one is added for it. +/// an `Int(33..=64)` in the 64-bit one. Any other pairing of AIR type and representation is not a +/// form this function knows and is refused until one is added for it. pub fn selector_form( air: &Type, lowered: &DemoteTy, - int64: bool, literals: &BTreeSet, ) -> Result { - let words = DemoteTy::Vector { - elem: ScalarTy::Int { bits: 32 }, - len: 2, - }; - if matches!(air, Type::Int(33..=64)) && !int64 && *lowered == words { - let miss = miss_literal(literals).ok_or_else(|| not_lowered(LowerFamily::Arith))?; - return Ok(SelectorForm::Words { miss }); - } let DemoteTy::Scalar(repr) = lowered else { return Err(not_lowered(LowerFamily::Arith)); }; @@ -1054,13 +1041,6 @@ pub fn selector_form( // zero-extended bit patterns: the container is the selector. (Type::Int(2..=32), ScalarTy::Int { bits: 32 }) => Ok(SelectorForm::Direct), (Type::Int(33..=64), ScalarTy::Int { bits: 64 }) => { - if !int64 { - return Err(Unsupported::needs( - Feature::Int64Arithmetic, - Capability::Feature(VkFeature::ShaderInt64), - ) - .into()); - } let miss = miss_literal(literals).ok_or_else(|| not_lowered(LowerFamily::Arith))?; Ok(SelectorForm::Narrow64 { miss }) } @@ -1459,8 +1439,7 @@ fn select_body( .and_then(|t| cx.entry.module.types().get(t)) .ok_or_else(|| invariant("a switch selector without a type"))?; let lits = switch_literals.get(v).cloned().unwrap_or_default(); - let int64 = cx.profile.fields().leaf.int64; - let form = selector_form(air, &lowered, int64, &lits) + let form = selector_form(air, &lowered, &lits) .map_err(|e| located(e, cx, b.raw(), tid))?; let id = values .id(*v) @@ -1942,79 +1921,41 @@ mod tests { fn selector_forms_follow_the_lowered_representation() { let int = |bits| DemoteTy::Scalar(ScalarTy::Int { bits }); let lits: BTreeSet = [0, 1, 5].into_iter().collect(); - let form = - |air: Type, lowered: &DemoteTy, int64| selector_form(&air, lowered, int64, &lits); + let form = |air: Type, lowered: &DemoteTy| selector_form(&air, lowered, &lits); assert_eq!( - form(Type::Int(1), &DemoteTy::Scalar(ScalarTy::Bool), false), + form(Type::Int(1), &DemoteTy::Scalar(ScalarTy::Bool)), Ok(SelectorForm::Bool) ); - assert_eq!( - form(Type::Int(8), &int(8), false), - Ok(SelectorForm::ZeroExtend) - ); - assert_eq!( - form(Type::Int(16), &int(16), false), - Ok(SelectorForm::ZeroExtend) - ); - assert_eq!( - form(Type::Int(32), &int(32), false), - Ok(SelectorForm::Direct) - ); - assert_eq!( - form(Type::Int(64), &int(64), true), - Ok(SelectorForm::Narrow64 { miss: 2 }) - ); - assert_eq!( - form(Type::Int(64), &int(64), false), - Err(Unsupported::needs( - Feature::Int64Arithmetic, - Capability::Feature(VkFeature::ShaderInt64), - ) - .into()) - ); + assert_eq!(form(Type::Int(8), &int(8)), Ok(SelectorForm::ZeroExtend)); + assert_eq!(form(Type::Int(16), &int(16)), Ok(SelectorForm::ZeroExtend)); + assert_eq!(form(Type::Int(32), &int(32)), Ok(SelectorForm::Direct)); // The held forms: narrow widths are zero-extended in their container. for w in [2, 8, 16, 24, 31] { assert_eq!( - form(Type::Int(w), &int(32), false), + form(Type::Int(w), &int(32)), Ok(SelectorForm::Direct), "i{w}" ); } - // Without `shaderInt64` the selector is two words. + // Two words are not a representation of any integer. let words = DemoteTy::Vector { elem: ScalarTy::Int { bits: 32 }, len: 2, }; for w in [33, 40, 63, 64] { assert_eq!( - form(Type::Int(w), &int(64), true), + form(Type::Int(w), &int(64)), Ok(SelectorForm::Narrow64 { miss: 2 }), "i{w}" ); assert_eq!( - form(Type::Int(w), &int(64), false), - Err(Unsupported::needs( - Feature::Int64Arithmetic, - Capability::Feature(VkFeature::ShaderInt64), - ) - .into()), - "i{w}" - ); - assert_eq!( - form(Type::Int(w), &words, false), - Ok(SelectorForm::Words { miss: 2 }), - "i{w}" - ); - // Two words are the representation only without `shaderInt64`. - assert_eq!( - form(Type::Int(w), &words, true), + form(Type::Int(w), &words), Err(not_lowered(LowerFamily::Arith)), "i{w}" ); } - // A two-word representation of a narrower integer is not a selector form. assert_eq!( - form(Type::Int(32), &words, false), + form(Type::Int(32), &words), Err(not_lowered(LowerFamily::Arith)) ); for (air, lowered) in [ @@ -2033,7 +1974,7 @@ mod tests { ), ] { assert_eq!( - form(air, &lowered, true), + form(air, &lowered), Err(not_lowered(LowerFamily::Arith)), "{lowered:?}" ); diff --git a/crates/metal2vulkan/src/lower/simd/group.rs b/crates/metal2vulkan/src/lower/simd/group.rs index f20ccd295..19fbed706 100644 --- a/crates/metal2vulkan/src/lower/simd/group.rs +++ b/crates/metal2vulkan/src/lower/simd/group.rs @@ -97,7 +97,7 @@ pub(super) fn check(g: &GroupPlan) -> Result<(), ()> { let form = match (g.scope, g.op) { (_, G::All | G::Any | G::IsFirst) => f.is_bool() && f.lanes == 1, (GroupScope::Simdgroup, G::Ballot | G::ActiveThreadsMask) => { - (f.is_int() || f.is_wide()) && f.container() == 64 && f.lanes == 1 + f.is_int() && f.container() == 64 && f.lanes == 1 } (GroupScope::Quad, G::Ballot | G::ActiveThreadsMask) => { f.is_int() && f.container() == 32 && f.lanes == 1 @@ -956,7 +956,7 @@ fn simd_op( // Metal's `simd_vote`: bit `i` is Metal lane `i`, zero-extended to the 64-bit result. G::Ballot => { let w = ln.word(fb, v()?)?; - crate::lower::arith::wide::zext_word(fb, g.form, w) + crate::lower::arith::ops::zext_word(fb, g.form, w) } G::IsFirst if ln.cluster => { let act = ln.active(fb)?; @@ -968,7 +968,7 @@ fn simd_op( // Metal's `simd_active_threads_mask`: the ballot of `true`, bit `i` Metal lane `i`. G::ActiveThreadsMask => { let w = ln.active(fb)?; - crate::lower::arith::wide::zext_word(fb, g.form, w) + crate::lower::arith::ops::zext_word(fb, g.form, w) } } } diff --git a/crates/metal2vulkan/src/lower/simd/matrix.rs b/crates/metal2vulkan/src/lower/simd/matrix.rs index 2eec18ce4..e2fabae9d 100644 --- a/crates/metal2vulkan/src/lower/simd/matrix.rs +++ b/crates/metal2vulkan/src/lower/simd/matrix.rs @@ -70,7 +70,7 @@ use crate::lower::access::copy::{self, Delta, Endpoint}; use crate::lower::access::AccessPlan; use crate::lower::arith::legal::{self, FloatFmt, Form, Held, LoweredConst}; use crate::lower::arith::narrow::{self, Fp8Layout}; -use crate::lower::arith::{self, ops, wide}; +use crate::lower::arith::{self, ops}; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; use crate::memory::leaf::{k32, Leaf, Path}; @@ -165,11 +165,11 @@ pub struct Mac { } /// A block descriptor (`stride` or `origin`): a constant `(x, y)`, or a runtime `<2 x i64>` -/// held as a `u64` vector or, without `shaderInt64`, as two words per lane (`wide`). +/// held as a `u64` vector. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Desc { Const([u64; 2]), - Value { id: ValueId, wide: bool }, + Value { id: ValueId }, } /// How a block addresses its cells. @@ -420,26 +420,21 @@ fn descriptor(cx: &SelectCx<'_>, v: Value) -> Result { let ty = cx .value_ty(v) .ok_or_else(|| cx.invariant("a matrix descriptor without a type"))?; - let wide = match legal::wide_form_on(cx.entry, cx.profile, ty)? { - Form { - held: Held::Int { - bits: 64, - container: 64, - }, - lanes: 2, - } => false, - Form { - held: Held::Wide { bits: 64 }, - lanes: 2, - } => true, - _ => return Err(cx.invariant("a matrix descriptor outside its signature")), + let descriptor = Form { + held: Held::Int { + bits: 64, + container: 64, + }, + lanes: 2, }; + if legal::form_on(cx.entry, cx.profile, ty)? != descriptor { + return Err(cx.invariant("a matrix descriptor outside its signature")); + } if matches!(v, Value::Const(_)) { return Err(cx.invariant("a matrix descriptor constant without lanes")); } Ok(Desc::Value { id: value_id(cx, v)?, - wide, }) } @@ -919,14 +914,10 @@ fn component( ) -> BResult { match d { Desc::Const([x, y]) => k32(fb, if j == 0 { x } else { y } as u32), - Desc::Value { id, wide: true } => { - let x = cx.operand(fb, id)?; - fb.composite_extract(x, &[0, j]) - } - Desc::Value { id, wide: false } => { + Desc::Value { id } => { let x = cx.operand(fb, id)?; let l = fb.composite_extract(x, &[j])?; - wide::low_word(fb, l) + ops::low_word(fb, l) } } } diff --git a/crates/metal2vulkan/src/lower/simd/mod.rs b/crates/metal2vulkan/src/lower/simd/mod.rs index 2bc2035c9..fe1bfe9c1 100644 --- a/crates/metal2vulkan/src/lower/simd/mod.rs +++ b/crates/metal2vulkan/src/lower/simd/mod.rs @@ -168,8 +168,7 @@ //! sums, products and prefix sums and products of a simdgroup record //! `PrecisionNote::ReductionOrder`. A `double` needs `shaderSubgroupExtendedTypes`. Metal has no //! simdgroup or quad function that moves or combines 64-bit integers, so a call of one is -//! `InvalidInput` on every profile; a 64-bit mask is not such a value (the ballot's is two words -//! without `shaderInt64`). +//! `InvalidInput` on every profile; a 64-bit mask is not such a value. //! //! **Not subgroup operations.** `air.all`/`air.any` of a `bool` vector are `OpAll`/`OpAny`, and //! `air.is_uniform` (Metal's `uniform` assertion, whose result the frontend feeds to @@ -226,7 +225,7 @@ use crate::error::{ Capability, Error, Feature, InputError, InputErrorKind, Location, LowerFamily, Unsupported, }; use crate::lower::arith; -use crate::lower::arith::legal::{form_on, wide_form_on, Form, Held, LoweredConst}; +use crate::lower::arith::legal::{form_on, Form, Held, LoweredConst}; use crate::lower::emit::EmitCx; use crate::lower::select::{FamilyPlans, Plan, SelectCx}; use crate::lower::strategy::{FamilyStrategy, Strategy}; @@ -1195,13 +1194,7 @@ fn select_group( Location::function(cx.entry.ep.name.clone(), None, Some(at.raw())), ))); } - // A simdgroup's 64-bit ballot or active mask is two words without `shaderInt64`. - let mask = matches!(g.op, GroupOp::Ballot | GroupOp::ActiveThreadsMask); - let form = if mask && g.scope == GroupScope::Simdgroup { - wide_form_on(cx.entry, cx.profile, inst.ty)? - } else { - form_on(cx.entry, cx.profile, inst.ty)? - }; + let form = form_on(cx.entry, cx.profile, inst.ty)?; if form.container() == 64 && moves_values(g.op) && !cx diff --git a/crates/metal2vulkan/src/lower/simd/workgroup.rs b/crates/metal2vulkan/src/lower/simd/workgroup.rs index 41ff27390..e0341a947 100644 --- a/crates/metal2vulkan/src/lower/simd/workgroup.rs +++ b/crates/metal2vulkan/src/lower/simd/workgroup.rs @@ -82,7 +82,7 @@ use crate::air::ir::{BinOp as AirBin, ValueId}; use crate::budget::Meter; use crate::error::{Error, Feature, LowerFamily, Unsupported}; use crate::lower::arith::legal::{Form, Held}; -use crate::lower::arith::{narrow, ops, wide}; +use crate::lower::arith::{narrow, ops}; use crate::lower::emit::EmitCx; use crate::lower::select::SelectCx; use crate::lower::strategy::Strategy; @@ -1429,7 +1429,7 @@ pub(super) fn simd_op( } G::Ballot => { let (w, _) = word(fb, ln, e, base, v()?, false)?; - wide::zext_word(fb, g.form, w) + ops::zext_word(fb, g.form, w) } // The ballot of `true`: in a divergent block the active lanes; else every lane of the // simdgroup below the thread count. @@ -1441,7 +1441,7 @@ pub(super) fn simd_op( } None => present(fb, e, base, SIMD_WIDTH)?, }; - wide::zext_word(fb, g.form, w) + ops::zext_word(fb, g.form, w) } } } diff --git a/crates/metal2vulkan/src/lower/texture/atomic.rs b/crates/metal2vulkan/src/lower/texture/atomic.rs index f979d995c..fef9351ba 100644 --- a/crates/metal2vulkan/src/lower/texture/atomic.rs +++ b/crates/metal2vulkan/src/lower/texture/atomic.rs @@ -136,7 +136,7 @@ pub(super) fn select( // which no form is built for (the module's docs). match texel.0.conv { TexelConv::I32 => {} - TexelConv::U64Words { .. } if matches!(op, AirOp::Min | AirOp::Max) => { + TexelConv::U64Words if matches!(op, AirOp::Min | AirOp::Max) => { return Err(Unsupported::not_implemented(Feature::ImageAtomics).into()); } _ => return Err(refuse()), diff --git a/crates/metal2vulkan/src/lower/texture/emit.rs b/crates/metal2vulkan/src/lower/texture/emit.rs index 2a5e7baaf..63f675376 100644 --- a/crates/metal2vulkan/src/lower/texture/emit.rs +++ b/crates/metal2vulkan/src/lower/texture/emit.rs @@ -266,24 +266,10 @@ fn u64_ty(fb: &mut FunctionBuilder<'_>) -> BResult { /// Metal's `ulong` texel `(R | G << 32, 0, 0, 1)` of `RG32` image texel `x`: the low word in R and /// the high word in G (measured on Apple M3 Max), and Metal's constant lanes past the first, which -/// out of bounds, where R and G are 0, are the same. `wide`: held as the low words `(R, 0, 0, 1)` -/// and the high words `(G, 0, 0, 0)`. -fn join_words(fb: &mut FunctionBuilder<'_>, x: SValue, wide: bool) -> BResult { +/// out of bounds, where R and G are 0, are the same. +fn join_words(fb: &mut FunctionBuilder<'_>, x: SValue) -> BResult { let lo = fb.composite_extract(x, &[0])?; let hi = fb.composite_extract(x, &[1])?; - if wide { - let u = u32_ty(fb)?; - let uvec = vec(fb, u, 4)?; - let zero = u32s(fb, 1, 0)?; - let one = u32s(fb, 1, 1)?; - let low = fb.composite_construct(uvec, &[lo, zero, zero, one])?; - let high = fb.composite_construct(uvec, &[hi, zero, zero, zero])?; - let ty = fb.module().ty(SType::Struct { - members: vec![uvec, uvec].into(), - layout: None, - })?; - return fb.composite_construct(ty, &[low, high]); - } let u64_ = u64_ty(fb)?; let lo = fb.convert(ConvOp::UConvert, lo, u64_)?; let hi = fb.convert(ConvOp::UConvert, hi, u64_)?; @@ -297,23 +283,15 @@ fn join_words(fb: &mut FunctionBuilder<'_>, x: SValue, wide: bool) -> BResult, v: SValue, wide: bool) -> BResult { +/// stores that lane only, its low word in R and its high word in G. +fn split_words(fb: &mut FunctionBuilder<'_>, v: SValue) -> BResult { let u = u32_ty(fb)?; - let (lo, hi) = if wide { - ( - fb.composite_extract(v, &[0, 0])?, - fb.composite_extract(v, &[1, 0])?, - ) - } else { - let u64_ = u64_ty(fb)?; - let x = fb.composite_extract(v, &[0])?; - let lo = fb.convert(ConvOp::UConvert, x, u)?; - let shift = splat(fb, u64_, 1, 32)?; - let hi = fb.binary(BinOp::ShiftRightLogical, x, shift)?; - (lo, fb.convert(ConvOp::UConvert, hi, u)?) - }; + let u64_ = u64_ty(fb)?; + let x = fb.composite_extract(v, &[0])?; + let lo = fb.convert(ConvOp::UConvert, x, u)?; + let shift = splat(fb, u64_, 1, 32)?; + let hi = fb.binary(BinOp::ShiftRightLogical, x, shift)?; + let hi = fb.convert(ConvOp::UConvert, hi, u)?; let zero = u32s(fb, 1, 0)?; let ty = vec(fb, u, 4)?; fb.composite_construct(ty, &[lo, hi, zero, zero]) @@ -963,7 +941,7 @@ pub fn held_texel( let mask = u32s(fb, n, 0xFFFF)?; fb.binary(BinOp::BitwiseAnd, x, mask) } - TexelConv::U64Words { wide } => join_words(fb, x, wide), + TexelConv::U64Words => join_words(fb, x), } } @@ -1103,7 +1081,7 @@ pub fn to_image( fb.binary(BinOp::ShiftRightArithmetic, s, sixteen)? } TexelConv::I16 { .. } => v, - TexelConv::U64Words { wide } => split_words(fb, v, wide)?, + TexelConv::U64Words => split_words(fb, v)?, }; let x = match decl.class { StorageImageClass::Identity => x, @@ -1354,7 +1332,7 @@ fn held_lane( match form.conv { TexelConv::F32 | TexelConv::F16 => Ok((f32_ty(fb)?, u64::from(1.0f32.to_bits()))), TexelConv::I32 | TexelConv::I16 { .. } => Ok((u32_ty(fb)?, 1)), - TexelConv::U64Words { .. } => Err(cx.fail("a swizzled `ulong` texel")), + TexelConv::U64Words => Err(cx.fail("a swizzled `ulong` texel")), } } @@ -2399,7 +2377,7 @@ fn slice_texel(fb: &mut FunctionBuilder<'_>, form: TexelForm, v: SValue) -> BRes let elem = match form.conv { TexelConv::F32 | TexelConv::F16 => f32_ty(fb)?, TexelConv::I32 | TexelConv::I16 { .. } => u32_ty(fb)?, - TexelConv::U64Words { .. } => u64_ty(fb)?, + TexelConv::U64Words => u64_ty(fb)?, }; let ty = vec(fb, elem, 4)?; let zero = |fb: &mut FunctionBuilder<'_>| -> BResult { diff --git a/crates/metal2vulkan/src/lower/texture/mod.rs b/crates/metal2vulkan/src/lower/texture/mod.rs index 0be8108c0..e212971c1 100644 --- a/crates/metal2vulkan/src/lower/texture/mod.rs +++ b/crates/metal2vulkan/src/lower/texture/mod.rs @@ -239,9 +239,8 @@ pub enum TexelConv { /// Metal's `ulong` texel as the two 32-bit words of an `RG32` image texel, the low word in R /// (measured on Apple M3 Max): a read is `(R | G << 32, 0, 0, 1)` (Metal's lanes, the same out /// of bounds, where R and G are 0), and a write stores lane 0's low word in R and its high word - /// in G. Held in `u64`s, or, `wide` on a profile without `shaderInt64`, as the low words' and - /// the high words' `uvec4`s. - U64Words { wide: bool }, + /// in G. Held in `u64`s. + U64Words, } /// The texel an operation reads or writes: its conversion and lane count (4, or 1 for a depth @@ -1209,16 +1208,11 @@ pub(crate) fn texel_conv(elem: Elem, sign: Option) -> Result<(TexelConv, T }) } -/// [`texel_conv`] of a read, write, or atomic on profile `p`, which also takes Metal's `ulong` -/// texel (no sampling takes it), held as `p` holds 64-bit integers. -fn image_texel_conv( - elem: Elem, - sign: Option, - p: &crate::device::profile::DeviceProfile, -) -> Result<(TexelConv, TexelClass), Error> { +/// [`texel_conv`] of a read, write, or atomic, which also takes Metal's `ulong` texel (no sampling +/// takes it). +fn image_texel_conv(elem: Elem, sign: Option) -> Result<(TexelConv, TexelClass), Error> { if (elem, sign) == (Elem::I64, Some(Sign::Unsigned)) { - let wide = crate::lower::arith::legal::holds_wide(p); - return Ok((TexelConv::U64Words { wide }, TexelClass::Uint64)); + return Ok((TexelConv::U64Words, TexelClass::Uint64)); } texel_conv(elem, sign) } @@ -1860,12 +1854,12 @@ fn select_image( ) -> Result { let shape = t.image; let texel = match t.texel { - Some(x) if matches!(t.op, TexOp::Read | TexOp::Write | TexOp::Atomic(_)) => Some( - image_texel_conv(x.ty.elem, x.sign, cx.profile).map(|(c, class)| { + Some(x) if matches!(t.op, TexOp::Read | TexOp::Write | TexOp::Atomic(_)) => { + Some(image_texel_conv(x.ty.elem, x.sign).map(|(c, class)| { let lanes = u8::try_from(x.ty.lanes).unwrap_or(0); (TexelForm { conv: c, lanes }, class) - })?, - ), + })?) + } _ => None, }; observe(cx, image, shape, texel.map(|(_, c)| c))?; @@ -2101,7 +2095,7 @@ fn select_read( // to the decoded texel. So does a packed normalized sampled slot of the // variant, to the texel its class converts: the variant holds no other sampled slot. let storage_swizzle = shape.dim != ImageDim::Buffer && swizzled_storage(cx, image)?; - if storage_swizzle && (texel.lanes != 4 || matches!(texel.conv, TexelConv::U64Words { .. })) { + if storage_swizzle && (texel.lanes != 4 || matches!(texel.conv, TexelConv::U64Words)) { return Err(Unsupported::not_implemented(Feature::TextureSwizzle).into()); } // A `ulong` read's lanes past the first are Metal's constants `(0, 0, 1)` in and out of @@ -2109,7 +2103,7 @@ fn select_read( // the alpha wherever the function reads a lane. let observed = (check == ReadCheck::Shader || level_views || residency) && texel.lanes == 4 - && !matches!(texel.conv, TexelConv::U64Words { .. }) + && !matches!(texel.conv, TexelConv::U64Words) && (storage_swizzle || alpha_read(cx, at)); let alpha = match image { ImageRef::Slot(index) if observed => { @@ -2280,7 +2274,7 @@ fn select_through( if !t.sampler.bordered() { return Ok(()); } - if matches!(texel.conv, TexelConv::U64Words { .. }) { + if matches!(texel.conv, TexelConv::U64Words) { return Err(Unsupported::not_implemented(Feature::Lowering(LowerFamily::Texture)).into()); } match image { @@ -2370,7 +2364,7 @@ fn select_write( // A storage slot bound to a swizzled texture stores each channel from the lane the swizzle // takes it to, under its variant, as plain Metal writes it. A `ulong` texel's is not measured. let swizzle = shape.dim != ImageDim::Buffer && swizzled_storage(cx, image)?; - if swizzle && (texel.lanes != 4 || matches!(texel.conv, TexelConv::U64Words { .. })) { + if swizzle && (texel.lanes != 4 || matches!(texel.conv, TexelConv::U64Words)) { return Err(Unsupported::not_implemented(Feature::TextureSwizzle).into()); } if let (true, ImageRef::Slot(index)) = (swizzle, image) { diff --git a/crates/metal2vulkan/src/memory/handles.rs b/crates/metal2vulkan/src/memory/handles.rs index 171473042..0495986a2 100644 --- a/crates/metal2vulkan/src/memory/handles.rs +++ b/crates/metal2vulkan/src/memory/handles.rs @@ -70,7 +70,6 @@ use crate::error::{ AccessCause, Error, Feature, InternalError, InternalKind, LowerFamily, Unsupported, }; use crate::memory::leaf::k32; -use crate::memory::views::{self, View}; use crate::pipeline::sym::ImageAccess; use crate::pipeline::sym::ResourceSlot; use crate::spirv::builder::{FunctionBuilder, ModuleBuilder}; @@ -374,19 +373,6 @@ fn walk_roots( pub const NEUTRAL_ELEMENT: u32 = 0; /// Bytes of one handle-table entry. pub const TABLE_ENTRY_BYTES: u32 = 16; -/// Words of one handle-table entry: the resource id's low and high words, the element, the flags. -const ENTRY_WORDS: u32 = 4; -/// Word of an entry holding the resource id's low 32 bits. -pub const ENTRY_ID_LO: u32 = 0; -/// Word of an entry holding the resource id's high 32 bits. -pub const ENTRY_ID_HI: u32 = 1; -/// Word of an entry holding the heap element. -pub const ENTRY_ELEMENT: u32 = 2; -/// Word of an entry holding the flags: for a sampler, its -/// [`SamplerWord`](crate::metal::sampler::SamplerWord); for a texture, -/// [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`], [`FLAG_RED_BLUE`], the index of its texel class in -/// [`FLAG_TEXEL_CLASS`], and [`FLAG_STORAGE_UNREADABLE`], every other bit 0. -pub const ENTRY_FLAGS: u32 = 3; /// The flag of a texture entry whose pixel format has no alpha /// (`metal::format::out_of_bounds_alpha_one`): Metal's out-of-bounds read of such a texture /// bound to a slot returns alpha 1 (MSL 4.1 section 2.9.1), which a read through the table takes @@ -1250,24 +1236,13 @@ impl Working { pub struct Table { global: SGlobalId, u32_ty: TypeId, - /// The `u64` type when the table is an entry array `{ Entry entries[]; }`, `Entry { u64 id; - /// u32 element; u32 flags; }` (a profile with `shaderInt64`), whose search compares each id - /// in one instruction; `None` for a word view `{ u32 words[]; }`, which compares an id's two - /// words. - u64_ty: Option, + /// The `u64` type of the entry array `{ Entry entries[]; }`, `Entry { u64 id; u32 element; + /// u32 flags; }`, whose search compares each id in one instruction. + u64_ty: TypeId, } -/// Declare the handle table at binding symbol `sym`: an entry array when `int64` (the profile -/// has `shaderInt64`), else a word storage view. -pub fn declare_table(mb: &mut ModuleBuilder, sym: ResourceSlot, int64: bool) -> BResult { - if !int64 { - let v = views::declare_at(mb, sym)?; - return Ok(Table { - global: v.global, - u32_ty: v.u32_ty, - u64_ty: None, - }); - } +/// Declare the handle table at binding symbol `sym`: an entry array. +pub fn declare_table(mb: &mut ModuleBuilder, sym: ResourceSlot) -> BResult
{ let int = |width| SType::Int { width, signed: false, @@ -1292,32 +1267,10 @@ pub fn declare_table(mb: &mut ModuleBuilder, sym: ResourceSlot, int64: bool) -> Ok(Table { global, u32_ty, - u64_ty: Some(u64_ty), + u64_ty, }) } -/// `a ≤ b` for two 64-bit values held as `(low, high)` word pairs. -fn le64(fb: &mut FunctionBuilder<'_>, a: (SValue, SValue), b: (SValue, SValue)) -> BResult { - let hi_lt = fb.binary(BinOp::ULessThan, a.1, b.1)?; - let hi_eq = fb.binary(BinOp::IEqual, a.1, b.1)?; - let lo_le = fb.binary(BinOp::ULessThanEqual, a.0, b.0)?; - let tie = fb.binary(BinOp::LogicalAnd, hi_eq, lo_le)?; - fb.binary(BinOp::LogicalOr, hi_lt, tie) -} - -/// Word `field` of entry `k` (a `u32`) of the word view `table`. -fn entry_word(fb: &mut FunctionBuilder<'_>, table: View, k: SValue, field: u32) -> BResult { - let stride = k32(fb, ENTRY_WORDS)?; - let at = fb.binary(BinOp::IMul, k, stride)?; - let at = if field == 0 { - at - } else { - let f = k32(fb, field)?; - fb.binary(BinOp::IAdd, at, f)? - }; - views::read_word(fb, table, at) -} - /// Member `member` of entry `k` of the entry array `t` (0 the id, 1 the element, 2 the flags). fn entry_member(fb: &mut FunctionBuilder<'_>, t: Table, k: SValue, member: u32) -> BResult { let base = fb.module().global_value(t.global)?; @@ -1419,12 +1372,13 @@ fn carry( pub enum EntryField { /// The heap element. Element, - /// The flags: a sampler entry's [`SamplerWord`](crate::metal::sampler::SamplerWord). + /// The flags: for a sampler, its [`SamplerWord`](crate::metal::sampler::SamplerWord); for a + /// texture, [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`], [`FLAG_RED_BLUE`], the index of its texel class + /// in [`FLAG_TEXEL_CLASS`], and [`FLAG_STORAGE_UNREADABLE`], every other bit 0. Flags, } -/// An upper estimate of [`entry_field`]'s words: over a word view, the index's scaling and offset, -/// the access chain, and the load; over an entry array, the access chain and the load; with their +/// An upper estimate of [`entry_field`]'s words: the access chain and the load, with their /// constants. pub const ENTRY_FIELD_WORDS: u32 = 32; @@ -1436,34 +1390,18 @@ pub fn entry_field( k: SValue, field: EntryField, ) -> BResult { - let (member, word) = match field { - EntryField::Element => (1, ENTRY_ELEMENT), - EntryField::Flags => (2, ENTRY_FLAGS), + let member = match field { + EntryField::Element => 1, + EntryField::Flags => 2, }; - match t.u64_ty { - Some(_) => entry_member(fb, t, k, member), - None => { - let words = View { - global: t.global, - u32_ty: t.u32_ty, - }; - entry_word(fb, words, k, word) - } - } + entry_member(fb, t, k, member) } /// The index of the last entry of the handle table `t` (its largest id's), from its length /// (`OpArrayLength`): the null entry's, 0, where the table holds no other. pub fn last_entry(fb: &mut FunctionBuilder<'_>, t: Table) -> BResult { let base_ptr = fb.module().global_value(t.global)?; - let len = fb.array_length(base_ptr, 0)?; - let count = match t.u64_ty { - Some(_) => len, - None => { - let two = k32(fb, 2)?; - fb.binary(BinOp::ShiftRightLogical, len, two)? - } - }; + let count = fb.array_length(base_ptr, 0)?; let one = k32(fb, 1)?; fb.binary(BinOp::ISub, count, one) } @@ -1472,10 +1410,10 @@ pub fn last_entry(fb: &mut FunctionBuilder<'_>, t: Table) -> BResult { /// (the module docs' layout): a branch-free binary search of [`SEARCH_STEPS`] steps for the last /// entry whose id is at most the key, then the entry's element if its id is the key, else /// [`NEUTRAL_ELEMENT`]. Entry 0 is the null entry (id 0), so the search always finds an entry, -/// and every entry it reads is below the table's length (`OpArrayLength`). An entry array -/// compares each id as one `u64`; a word view compares its two words. [`Lookup::Flagged`] also -/// moves the found entry's flags it carries into their handle bits (a miss is -/// [`NEUTRAL_ELEMENT`] without them), and [`Lookup::Entry`] yields the found entry's index in place of its element, 0 for a miss. +/// and every entry it reads is below the table's length (`OpArrayLength`). It compares each id as +/// one `u64`. [`Lookup::Flagged`] also moves the found entry's flags it carries into their handle +/// bits (a miss is [`NEUTRAL_ELEMENT`] without them), and [`Lookup::Entry`] yields the found +/// entry's index in place of its element, 0 for a miss. pub fn lookup( fb: &mut FunctionBuilder<'_>, t: Table, @@ -1487,39 +1425,18 @@ pub fn lookup( let len = fb.array_length(base_ptr, 0)?; let one = k32(fb, 1)?; let zero = k32(fb, 0)?; - let words = View { - global: t.global, - u32_ty: t.u32_ty, - }; - // The key, and the id of an entry, in the table's form. - let (key, count) = match t.u64_ty { - Some(u64_ty) => { - let l = fb.convert(ConvOp::UConvert, lo, u64_ty)?; - let h = fb.convert(ConvOp::UConvert, hi, u64_ty)?; - let s = k32(fb, 32)?; - let h = fb.binary(BinOp::ShiftLeftLogical, h, s)?; - (fb.binary(BinOp::BitwiseOr, h, l)?, len) - } - None => { - let two = k32(fb, 2)?; - (lo, fb.binary(BinOp::ShiftRightLogical, len, two)?) - } - }; + // The key as one `u64`. + let l = fb.convert(ConvOp::UConvert, lo, t.u64_ty)?; + let h = fb.convert(ConvOp::UConvert, hi, t.u64_ty)?; + let s = k32(fb, 32)?; + let h = fb.binary(BinOp::ShiftLeftLogical, h, s)?; + let key = fb.binary(BinOp::BitwiseOr, h, l)?; let at_most_key = |fb: &mut FunctionBuilder<'_>, k: SValue| -> BResult { - match t.u64_ty { - Some(_) => { - let id = entry_member(fb, t, k, 0)?; - fb.binary(BinOp::ULessThanEqual, id, key) - } - None => { - let id_lo = entry_word(fb, words, k, ENTRY_ID_LO)?; - let id_hi = entry_word(fb, words, k, ENTRY_ID_HI)?; - le64(fb, (id_lo, id_hi), (lo, hi)) - } - } + let id = entry_member(fb, t, k, 0)?; + fb.binary(BinOp::ULessThanEqual, id, key) }; let mut base = zero; - let mut len = count; + let mut len = len; for _ in 0..SEARCH_STEPS { let half = fb.binary(BinOp::ShiftRightLogical, len, one)?; let mid = fb.binary(BinOp::IAdd, base, half)?; @@ -1527,19 +1444,8 @@ pub fn lookup( base = fb.select(take, mid, base)?; len = fb.binary(BinOp::ISub, len, half)?; } - let hit = match t.u64_ty { - Some(_) => { - let id = entry_member(fb, t, base, 0)?; - fb.binary(BinOp::IEqual, id, key)? - } - None => { - let id_lo = entry_word(fb, words, base, ENTRY_ID_LO)?; - let id_hi = entry_word(fb, words, base, ENTRY_ID_HI)?; - let eq_lo = fb.binary(BinOp::IEqual, id_lo, lo)?; - let eq_hi = fb.binary(BinOp::IEqual, id_hi, hi)?; - fb.binary(BinOp::LogicalAnd, eq_lo, eq_hi)? - } - }; + let id = entry_member(fb, t, base, 0)?; + let hit = fb.binary(BinOp::IEqual, id, key)?; if form == Lookup::Entry { // The null entry, index 0, for a miss. return fb.select(hit, base, zero); @@ -1556,14 +1462,13 @@ pub fn lookup( fb.select(hit, handle, neutral) } -/// An upper estimate of [`define_lookup`]'s words, counted once per module: per search step, over -/// an entry array, the id's access chain and load, the compare, and the step's arithmetic, or, over -/// a word view, two word reads (about 20 words each) and a five-instruction compare; then the +/// An upper estimate of [`define_lookup`]'s words, counted once per module: per search step, the +/// id's access chain and load, the compare, and the step's arithmetic; then the /// entry's id and element, and the function's own instructions and types. The flagged form also /// reads the entry's flags (a word read) and moves each carried field (three instructions and two /// constants); the entry form reads no element. -pub fn lookup_routine_words(int64: bool, form: Lookup) -> u32 { - let step = if int64 { 48 } else { 96 }; +pub fn lookup_routine_words(form: Lookup) -> u32 { + let step = 48; let carried = 48 * form.carried().len() as u32; SEARCH_STEPS * step + 160 + carried } @@ -1584,6 +1489,7 @@ pub fn define_lookup(mb: &mut ModuleBuilder, t: Table, form: Lookup) -> BResult< #[cfg(test)] mod tests { use super::*; + use crate::memory::views; #[test] fn handle_indices_keep_the_classes_apart() { @@ -1755,16 +1661,14 @@ mod tests { /// A kernel that looks up the [`KEYS`] ids (low, high word pairs) at the start of the /// buffer at slot 1 in the handle table at slot 0 by calling [`define_lookup`]'s search in - /// `form`, and writes each element after them. The table is an entry array when `int64`, else - /// a word view. - fn lookup_module(int64: bool, form: Lookup) -> BResult { - search_module(int64, form, |_, _, h| Ok(vec![h])) + /// `form`, and writes each element after them. + fn lookup_module(form: Lookup) -> BResult { + search_module(form, |_, _, h| Ok(vec![h])) } /// [`lookup_module`] writing the words `per_key` makes of each key's handle (`per_key` of the /// function, the table and the handle), each key's words after the keys in turn. fn search_module( - int64: bool, form: Lookup, per_key: impl Fn(&mut FunctionBuilder<'_>, Table, SValue) -> BResult>, ) -> BResult { @@ -1777,7 +1681,7 @@ mod tests { index, }; let mut b = ModuleBuilder::new(); - let t = declare_table(&mut b, sym(0), int64)?; + let t = declare_table(&mut b, sym(0))?; let io = views::declare_at(&mut b, sym(1))?; let search = define_lookup(&mut b, t, form)?; let void = b.ty(Type::Void)?; @@ -1810,34 +1714,32 @@ mod tests { /// The emitted search is the host model: over the CPU interpreter, every key of tables of /// several sizes up to [`TABLE_CAPACITY`] entries (the null id, present ids, absent ids between - /// and beyond them) gets [`reference`]'s element, through an entry array (`u64` ids) and a - /// word view. [`Lookup::Flagged`] also carries a found entry's [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`] + /// and beyond them) gets [`reference`]'s element, through an entry array (`u64` ids). + /// [`Lookup::Flagged`] also carries a found entry's [`FLAG_OUT_OF_BOUNDS_ALPHA_ONE`] /// in [`HANDLE_ALPHA_ONE`] where it carries the alpha, its texel class where it carries that, /// and its [`FLAG_RED_BLUE`] in [`HANDLE_RED_BLUE`] where it carries that, carrying no other /// bit of the entry; and [`Lookup::Entry`] yields the index of the last entry of the key's id, /// 0 for a miss. #[test] fn the_emitted_search_matches_the_host_model() { - for int64 in [true, false] { - let flagged = |alpha, class, red_blue, unreadable| Lookup::Flagged { - alpha, - class, - red_blue, - unreadable, - }; - for form in [ - Lookup::Element, - flagged(true, false, false, false), - flagged(false, true, false, false), - flagged(false, false, true, false), - flagged(false, false, false, true), - flagged(true, true, false, false), - flagged(true, true, true, false), - flagged(true, true, true, true), - Lookup::Entry, - ] { - emitted_search_matches_the_host_model(int64, form); - } + let flagged = |alpha, class, red_blue, unreadable| Lookup::Flagged { + alpha, + class, + red_blue, + unreadable, + }; + for form in [ + Lookup::Element, + flagged(true, false, false, false), + flagged(false, true, false, false), + flagged(false, false, true, false), + flagged(false, false, false, true), + flagged(true, true, false, false), + flagged(true, true, true, false), + flagged(true, true, true, true), + Lookup::Entry, + ] { + emitted_search_matches_the_host_model(form); } } @@ -1918,10 +1820,10 @@ mod tests { .collect() } - fn emitted_search_matches_the_host_model(int64: bool, form: Lookup) { + fn emitted_search_matches_the_host_model(form: Lookup) { use crate::pipeline::sym::{ResourceKind, ResourceSlot, Stage}; use crate::spirv::interp::{run, Buffer, Config, Resources}; - let m = lookup_module(int64, form).expect("module"); + let m = lookup_module(form).expect("module"); let sym = |index| ResourceSlot { stage: Stage::Kernel, kind: ResourceKind::Buffer, @@ -1998,7 +1900,7 @@ mod tests { t.iter().rposition(|(k, _)| k == id).map_or(0, |i| i as u32) } }; - assert_eq!(got, want, "int64 {int64} {form:?} n {n} id {id:#x}"); + assert_eq!(got, want, "{form:?} n {n} id {id:#x}"); } } } diff --git a/crates/metal2vulkan/src/memory/leaf.rs b/crates/metal2vulkan/src/memory/leaf.rs index 7694bf735..a3f522aab 100644 --- a/crates/metal2vulkan/src/memory/leaf.rs +++ b/crates/metal2vulkan/src/memory/leaf.rs @@ -129,10 +129,9 @@ use crate::air::ir::{Type, TypeId as AirTypeId, TypeLayouts}; use crate::air::Entry; use crate::device::DeviceProfile; use crate::error::{AccessCause, Error, Unsupported}; -use crate::lower::arith::legal::{self, wide_form_on}; +use crate::lower::arith::legal::{self, form_on}; use crate::lower::arith::narrow; use crate::lower::arith::ops; -use crate::lower::arith::wide; use crate::lower::arith::{FloatFmt, Form, Held}; use crate::spirv::builder::constructs::{ArmEnd, ArmFn}; use crate::spirv::builder::FunctionBuilder; @@ -346,7 +345,6 @@ pub fn leaf_of( align: u64, proven: u64, ) -> Result { - // A 64-bit integer is two words on a profile without `shaderInt64`, in a chunk too. let form = match legal::chunked(e.module.types(), ty) { Some((held, lanes)) => Form { held: legal::held_on(p, held)?, @@ -355,7 +353,7 @@ pub fn leaf_of( .filter(|l| *l > 4) .ok_or_else(|| not_lowered(AccessCause::AccessType))?, }, - None => wide_form_on(e, p, ty)?, + None => form_on(e, p, ty)?, }; let bytes = layouts .store_size(ty) @@ -363,7 +361,7 @@ pub fn leaf_of( let bytes = u32::try_from(bytes).map_err(|_| not_lowered(AccessCause::AccessType))?; if form.lanes > 1 { let lane_bits = match form.held { - Held::Int { bits, .. } | Held::Wide { bits } => bits, + Held::Int { bits, .. } => bits, Held::Float(f) => f.bits(), Held::Bool => return Err(not_lowered(AccessCause::AccessType)), }; @@ -823,10 +821,6 @@ pub fn value_of(fb: &mut FunctionBuilder<'_>, leaf: &Leaf, words: &[Value]) -> B let ty = chunked_ty(fb, form)?; return fb.composite_construct(ty, &parts); } - if form.is_wide() { - // Two words per lane, low first. - return wide::from_words(fb, form, words); - } if form.lanes > 1 { if let Some(v) = vector_of(fb, form, words)? { return Ok(v); @@ -875,7 +869,6 @@ pub fn value_of(fb: &mut FunctionBuilder<'_>, leaf: &Leaf, words: &[Value]) -> B }; join64(fb, lo, hi, elem) } - Held::Wide { .. } => Err(dangling()), Held::Float(FloatFmt::Half | FloatFmt::BFloat) => { // A narrow float is held widened: its 16 format bits (`from_bits` reads only the // low 16 bits), a `half` widened from its word where the device widens it. @@ -992,12 +985,6 @@ pub fn words_of(fb: &mut FunctionBuilder<'_>, leaf: &Leaf, v: Value) -> BResult< } return Ok(out); } - if form.is_wide() { - // Its words are the value's; an `i33..i63` high word covers fewer bytes. - let mut ws = wide::to_words(fb, form, v)?; - ws.truncate(leaf.words() as usize); - return Ok(ws); - } if form.lanes > 1 { if let Some(ws) = vector_words(fb, leaf, v)? { return Ok(ws); @@ -1034,7 +1021,6 @@ pub fn words_of(fb: &mut FunctionBuilder<'_>, leaf: &Leaf, v: Value) -> BResult< let x = ops::mask(fb, scalar, x)?; put(fb, &mut out, i * lane_bytes, x)?; } - Held::Wide { .. } => return Err(dangling()), Held::Int { .. } | Held::Float(FloatFmt::F64) => { let x = ops::mask(fb, scalar, x)?; let (lo, hi) = split64(fb, x)?; @@ -1150,12 +1136,11 @@ fn vector_words( } /// Whether a vector unit's leaf (8 or 16 bytes) has a register value of the `uvecN`'s bits: -/// 32-bit lanes, or 64-bit ones, filling its bytes, held natively (not chunked, nor as word pairs). +/// 32-bit lanes, or 64-bit ones, filling its bytes, held natively (not chunked). fn vec_bits(leaf: &Leaf) -> bool { let form = leaf.form; let lanes = u32::from(form.lanes); !leaf.chunked() - && !form.is_wide() && match form.held { Held::Int { bits: 32, diff --git a/crates/metal2vulkan/src/pipeline/lower_inputs.rs b/crates/metal2vulkan/src/pipeline/lower_inputs.rs index bdb9a805e..dfa0ac3a7 100644 --- a/crates/metal2vulkan/src/pipeline/lower_inputs.rs +++ b/crates/metal2vulkan/src/pipeline/lower_inputs.rs @@ -88,13 +88,11 @@ pub struct LoweringInputs { /// So everything the function reads of its buffers is in the root table, which the device /// replay's preprocess writes per replayed command from the command's record (`bind::replay`). /// A vertex or fragment function compiles so too, for a replayed draw: its buffers are the - /// command's, in the slot table at its own stage's `RootTableAddress`. It needs device - /// addresses (`bufferDeviceAddress` and `shaderInt64`: `GpuEncodedIndirectCommands` names - /// them otherwise); a tile, object or mesh function, a kernel with a stage-input descriptor, - /// and a vertex function that fetches an attribute in fixed function are - /// `Unsupported{GpuEncodedIndirectCommands, NotImplemented}` under it (a replayed command is a - /// compute dispatch with no stage-in region, or a draw whose buffers no fixed-function input - /// reads: a pulled attribute reads its slot table). + /// command's, in the slot table at its own stage's `RootTableAddress`. A tile, object or mesh + /// function, a kernel with a stage-input descriptor, and a vertex function that fetches an + /// attribute in fixed function are `Unsupported{GpuEncodedIndirectCommands, NotImplemented}` + /// under it (a replayed command is a compute dispatch with no stage-in region, or a draw whose + /// buffers no fixed-function input reads: a pulled attribute reads its slot table). #[cfg_attr(feature = "serde", serde(default))] pub replay_bindings: bool, /// With `replay_bindings`, the vertex function of a draw replay merged into one draw @@ -285,8 +283,7 @@ pub struct LoweringInputs { /// `PushField::IndirectBase`, in its first block, and an invocation of a command outside the /// range (`command - location >= length`, in `u32`) stores its `[[position]]` as `(2, 2, 2, /// 1)`, outside every clip volume, and returns before the body, so its command draws nothing - /// and writes no memory. A direct draw of the state is pushed a range of every command. Refused - /// on a device without device addresses (`Feature::GpuEncodedIndirectCommands`). + /// and writes no memory. A direct draw of the state is pushed a range of every command. /// `Device::compile_render_pipeline` sets it for a `Function` vertex stage of a descriptor that /// sets the flag, whose vertex function then pulls every attribute it reads. Any other function /// compiles as without it. diff --git a/crates/metal2vulkan/src/spirv/builder/ops/arith.rs b/crates/metal2vulkan/src/spirv/builder/ops/arith.rs index e8f01615b..70faae01c 100644 --- a/crates/metal2vulkan/src/spirv/builder/ops/arith.rs +++ b/crates/metal2vulkan/src/spirv/builder/ops/arith.rs @@ -172,7 +172,7 @@ impl FunctionBuilder<'_> { } self.bool_ty(x.n)? } - BinOp::IAddCarry | BinOp::ISubBorrow | BinOp::UMulExtended | BinOp::SMulExtended => { + BinOp::IAddCarry | BinOp::UMulExtended | BinOp::SMulExtended => { // The struct members, and so both operands, share one type; all but // `SMulExtended` require it unsigned. let unsigned = op != BinOp::SMulExtended; diff --git a/crates/metal2vulkan/src/spirv/interp/eval.rs b/crates/metal2vulkan/src/spirv/interp/eval.rs index 8778fcf2d..d35cdad48 100644 --- a/crates/metal2vulkan/src/spirv/interp/eval.rs +++ b/crates/metal2vulkan/src/spirv/interp/eval.rs @@ -817,7 +817,7 @@ fn binary(p: &Prog<'_>, op: BinOp, a: Value, va: &Val, vb: &Val) -> IResult ))) }) } - B::IAddCarry | B::ISubBorrow | B::UMulExtended | B::SMulExtended => { + B::IAddCarry | B::UMulExtended | B::SMulExtended => { let w = p.t.num_of(a)?.width; let (xs, ys) = (va.comps()?, vb.comps()?); let (mut lo, mut hi) = (Vec::new(), Vec::new()); @@ -827,7 +827,6 @@ fn binary(p: &Prog<'_>, op: BinOp, a: Value, va: &Val, vb: &Val) -> IResult let s = u128::from(x) + u128::from(y); (s as u64 & mask(w), u64::from(s >> w != 0)) } - B::ISubBorrow => ((x.wrapping_sub(y)) & mask(w), u64::from(x < y)), B::UMulExtended => { let pr = u128::from(x) * u128::from(y); (pr as u64 & mask(w), (pr >> w) as u64 & mask(w)) diff --git a/crates/metal2vulkan/src/spirv/ir/inst.rs b/crates/metal2vulkan/src/spirv/ir/inst.rs index a5ec95557..8a4c7fb07 100644 --- a/crates/metal2vulkan/src/spirv/ir/inst.rs +++ b/crates/metal2vulkan/src/spirv/ir/inst.rs @@ -97,8 +97,6 @@ pub enum BinOp { FUnordGreaterThanEqual, /// Result: `struct { T, T }` (sum, carry). IAddCarry, - /// Result: `struct { T, T }` (difference, borrow). - ISubBorrow, /// Result: `struct { T, T }` (low, high). UMulExtended, /// Result: `struct { T, T }` (low, high). @@ -184,7 +182,6 @@ impl BinOp { BinOp::FOrdGreaterThanEqual => Op::FOrdGreaterThanEqual, BinOp::FUnordGreaterThanEqual => Op::FUnordGreaterThanEqual, BinOp::IAddCarry => Op::IAddCarry, - BinOp::ISubBorrow => Op::ISubBorrow, BinOp::UMulExtended => Op::UMulExtended, BinOp::SMulExtended => Op::SMulExtended, BinOp::VectorTimesScalar => Op::VectorTimesScalar, diff --git a/crates/metal2vulkan/src/spirv/serialize/tests/families.rs b/crates/metal2vulkan/src/spirv/serialize/tests/families.rs index cc8104dd7..6af8cafcf 100644 --- a/crates/metal2vulkan/src/spirv/serialize/tests/families.rs +++ b/crates/metal2vulkan/src/spirv/serialize/tests/families.rs @@ -253,7 +253,7 @@ fn binary_operations() { } } for (a, b) in [(u, u), (uv, uv)] { - for op in [IAddCarry, ISubBorrow, UMulExtended] { + for op in [IAddCarry, UMulExtended] { f.binary(op, *a, *b) .unwrap_or_else(|e| panic!("{op:?}: {e}")); } diff --git a/crates/metal2vulkan/src/tests/engine_access.rs b/crates/metal2vulkan/src/tests/engine_access.rs index 66404ca9c..fb524c44c 100644 --- a/crates/metal2vulkan/src/tests/engine_access.rs +++ b/crates/metal2vulkan/src/tests/engine_access.rs @@ -42,7 +42,7 @@ use crate::pipeline::testing::{ use crate::spirv::interp::{run, Buffer, Config, InterpError, Resources}; use crate::spirv::ir::{GlobalKind, TypedModule}; -/// Profiles with and without 64-bit integers and 8/16-bit storage. +/// Profiles with and without 8/16-bit storage. const PROFILES: [&str; 3] = ["moltenvk-m3", "runtime-floor", "lavapipe"]; /// Committed profile `stem`. @@ -356,8 +356,8 @@ fn leaf_kernels() -> Vec { k("load_half5_bytes", "<5 x half>", 10, 1), k("load_uchar8", "<8 x i8>", 8, 8), // A 16-byte leaf aligned to 16 is one `uvec4` of the slot's `uvec4` view: one bitcast for - // four 32-bit or two 64-bit lanes (two words each without `shaderInt64`), the vector's - // words for a chunked one; aligned to 4 it moves word by word. + // four 32-bit or two 64-bit lanes, the vector's words for a chunked one; aligned to 4 it + // moves word by word. k("load_float4", "<4 x float>", 16, 16), k("load_long2", "<2 x i64>", 16, 16), k("load_half8", "<8 x half>", 16, 16), diff --git a/crates/metal2vulkan/src/tests/engine_arena.rs b/crates/metal2vulkan/src/tests/engine_arena.rs index 082915e68..4332c9991 100644 --- a/crates/metal2vulkan/src/tests/engine_arena.rs +++ b/crates/metal2vulkan/src/tests/engine_arena.rs @@ -38,7 +38,7 @@ use crate::pipeline::testing::{ use crate::spirv::interp::{run, Buffer, Config, InterpError, Order, Resources, SubgroupSize}; use crate::spirv::ir::TypedModule; -/// Profiles with and without 64-bit integers, 16 and 32 KiB of shared memory. +/// Profiles with 16 and 32 KiB of shared memory. const PROFILES: [&str; 3] = ["moltenvk-m3", "runtime-floor", "lavapipe"]; const DATALAYOUT: &str = "e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f32:32:32-f64:64:64-v16:16:16-v24:32:32-v32:32:32-v48:64:64-v64:64:64-v96:128:128-v128:128:128-v192:256:256-v256:256:256-v512:512:512-v1024:1024:1024-n8:16:32"; diff --git a/crates/metal2vulkan/src/tests/engine_arith.rs b/crates/metal2vulkan/src/tests/engine_arith.rs index c21724006..9077f1e7c 100644 --- a/crates/metal2vulkan/src/tests/engine_arith.rs +++ b/crates/metal2vulkan/src/tests/engine_arith.rs @@ -1,9 +1,9 @@ //! The arith family end to end: owned kernels go through the whole new pipeline (decode → //! specialize → analyze → select → emit → verify → serialize → link) on committed profiles and pass //! L3, and their typed modules compute the Metal/LLVM result on the CPU SPIR-V interpreter. -//! Profiles without `shaderInt64` hold 64-bit integers as two words, a switch on one included, and -//! profiles without `shaderFloat64` refuse `double` with the typed capability; `half` and `bfloat` -//! are held widened on every profile. +//! 64-bit integers, a switch on one included, are `u64`s on every profile; profiles without +//! `shaderFloat64` refuse `double` with the typed capability; `half` and `bfloat` are held widened +//! on every profile. //! //! Each kernel stores one word to buffer 0 (the skeleton's static-root store). Canonicalization //! folds integer arithmetic on constants but never float arithmetic, so each kernel makes its @@ -327,8 +327,7 @@ fn kernels() -> Vec { ), 13, )); - // Without `shaderInt64` the selector is two words; a nonzero high word matches no (32-bit) case - // literal. + // A selector whose high word is nonzero matches no (32-bit) case literal. v.push(k( "switch_on_an_i40", format!( @@ -385,8 +384,7 @@ fn kernels() -> Vec { needs: &[], note: None, }); - // Without `shaderInt64` 64-bit integers are two words; division is the exact word division - // (`udivrem`), with no loop. + // 64-bit division and remainder, signed and unsigned, of scalars and vectors. v.push(k( "i64_division_as_words", format!( @@ -420,10 +418,9 @@ fn kernels() -> Vec { ), 0x00BC_614D, )); - // Chunked vectors of 64-bit integers are chunks of two-word lanes without `shaderInt64`: - // lane-wise operations per chunk, constant and `i64` dynamic lane moves, a shuffle into a - // five-lane vector (its last chunk one lane), a lane-wise intrinsic, a word bitcast, and a - // truncation. + // Chunked vectors of 64-bit integers: lane-wise operations per chunk, constant and `i64` dynamic + // lane moves, a shuffle into a five-lane vector (its last chunk one lane), a lane-wise + // intrinsic, a word bitcast, and a truncation. v.push(k( "chunked_i64_lanes", format!( @@ -793,8 +790,8 @@ fn kernels() -> Vec { note: None, }); // An 8-bit float to an integer is its value under the saturating rule (448 to `char` is 127, - // -1.0 to `uint` is 0, 57344 and -2.0 to 64 bits, held as two words where the profile lacks - // `shaderInt64`), and records `Fp8Value`; a widening to a float does not. + // -1.0 to `uint` is 0, 57344 and -2.0 to 64 bits), and records `Fp8Value`; a widening to a float + // does not. for (name, call, bits, wide, want) in [ ( "fp8_e4m3fn_to_char_saturates", diff --git a/crates/metal2vulkan/src/tests/engine_atomics.rs b/crates/metal2vulkan/src/tests/engine_atomics.rs index bcd156505..1c85c38c6 100644 --- a/crates/metal2vulkan/src/tests/engine_atomics.rs +++ b/crates/metal2vulkan/src/tests/engine_atomics.rs @@ -40,7 +40,7 @@ use crate::pipeline::testing::{ use crate::spirv::interp::{run, Buffer, Config, InterpError, Order, Resources}; use crate::spirv::ir::TypedModule; -/// Profiles with and without 64-bit integers. +/// Profiles with and without 64-bit atomics. const PROFILES: [&str; 4] = [ "moltenvk-m3", "runtime-floor", @@ -537,11 +537,6 @@ fn int64_atomics_refuse_by_the_profiles_features() { let Error::Unsupported(u) = e else { panic!("{stem} {space}: {e:?}"); }; - // Without Int64 the `zext` is held as two words, so the refusal is the atomic's own: a - // 64-bit atomic needs its int64-atomic feature, which such a profile lacks. - if !prof.fields().leaf.int64 { - assert!(!have, "{stem} {space}"); - } let want = if have { Unsupported::not_implemented(Feature::Lowering(LowerFamily::Access)) } else { diff --git a/crates/metal2vulkan/src/tests/engine_bit_manipulation.rs b/crates/metal2vulkan/src/tests/engine_bit_manipulation.rs index c19d2a06d..33e250e45 100644 --- a/crates/metal2vulkan/src/tests/engine_bit_manipulation.rs +++ b/crates/metal2vulkan/src/tests/engine_bit_manipulation.rs @@ -28,9 +28,7 @@ const STEM: &str = "kernel_bit_manipulation"; /// The committed `moltenvk-m3` profile: 64-bit operands in 64-bit containers. fn m3() -> DeviceProfile { - let p = profile("moltenvk-m3").expect("profile"); - assert!(p.fields().leaf.int64); - p + profile("moltenvk-m3").expect("profile") } fn mask(n: u32) -> u64 { diff --git a/crates/metal2vulkan/src/tests/engine_copy.rs b/crates/metal2vulkan/src/tests/engine_copy.rs index 39d4b2b42..9310ca730 100644 --- a/crates/metal2vulkan/src/tests/engine_copy.rs +++ b/crates/metal2vulkan/src/tests/engine_copy.rs @@ -11,7 +11,7 @@ //! the direction the offsets require; a `volatile` `memcpy` lowers as a plain one; a dynamic //! `memmove` between two slots compares their Metal addresses. //! - `i64` lengths (Metal's `size_t`), loaded or scaled from a `uint` count, are exact on every -//! profile, with `shaderInt64` and without it (the length is two words there); one of 2³² or more +//! profile; one of 2³² or more //! counts as `u32::MAX` bytes and every access it makes at a device address is contained (the //! CPU interpreter's step limit stops the run; no execution bound does; a bound buffer's view is //! the device's robust buffer access, which the interpreter does not model). The Metal-compiled @@ -25,8 +25,6 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicU64, Ordering}; use crate::device::profile::DeviceProfile; -use crate::device::requirements::VkFeature; -use crate::error::{Capability, Error, Feature, Unsupported}; use crate::lower::select::Plan; use crate::pipeline::interface::PushLoc; use crate::pipeline::sym::{PushField, ResourceKind, ResourceSlot, SpecKey, Stage}; @@ -590,35 +588,22 @@ declare void @llvm.memmove.p1.p1.i32(ptr addrspace(1), ptr addrspace(1), i32, i1 /// A dynamic `memmove` between two buffer slots (possibly one buffer bound twice, with no /// comparable offsets) compares the endpoints' Metal addresses (each slot's `SlotGuestBase`), never -/// a guessed direction: it passes L3 where the profile has `shaderInt64` for those `u64` addresses -/// and is refused naming it elsewhere (`engine_pointer_memory` executes it). +/// a guessed direction: it passes L3 on every profile (`engine_pointer_memory` executes it). #[test] fn a_dynamic_move_between_slots_compares_metal_addresses() { let Some(bc) = assemble("aliased", ALIASED_MOVE) else { return; }; for (what, prof) in profiles() { - if prof.fields().leaf.int64 { - l3(&bc, "aliased", &prof, &what); - let (plan, _) = typed_module(&bc, "aliased", &prof).expect("module"); - assert!( - plan.push - .fields - .iter() - .any(|f| matches!(f.field, PushField::SlotGuestBase(_))), - "{what}" - ); - continue; - } - let e = compile(&bc, "aliased", &prof).expect_err("refused"); - let Error::Unsupported(u) = e else { - panic!("{what}: {e:?}"); - }; - let want = Unsupported::needs( - Feature::PointerCompare, - Capability::Feature(VkFeature::ShaderInt64), + l3(&bc, "aliased", &prof, &what); + let (plan, _) = typed_module(&bc, "aliased", &prof).expect("module"); + assert!( + plan.push + .fields + .iter() + .any(|f| matches!(f.field, PushField::SlotGuestBase(_))), + "{what}" ); - assert_eq!((u.feature, u.needs), (want.feature, want.needs), "{what}"); } } diff --git a/crates/metal2vulkan/src/tests/engine_gep_index.rs b/crates/metal2vulkan/src/tests/engine_gep_index.rs index b7333700a..8093eea06 100644 --- a/crates/metal2vulkan/src/tests/engine_gep_index.rs +++ b/crates/metal2vulkan/src/tests/engine_gep_index.rs @@ -591,7 +591,6 @@ fn an_i64_index_that_is_not_an_extension_is_a_64_bit_value() { }; for stem in PROFILES { let p = profile_with(stem); - assert!(p.fields().leaf.int64, "{stem}"); let a = compile(&bc, name, &p).unwrap_or_else(|e| panic!("{name} {stem}: {e}")); assert!( !a.strategies.entries.contains_key("arith.index_extension"), diff --git a/crates/metal2vulkan/src/tests/engine_index_words.rs b/crates/metal2vulkan/src/tests/engine_index_words.rs index 4771e39fd..48635c4e4 100644 --- a/crates/metal2vulkan/src/tests/engine_index_words.rs +++ b/crates/metal2vulkan/src/tests/engine_index_words.rs @@ -308,12 +308,6 @@ fn index_arithmetic_with_other_uses_or_operators_keeps_64_bits() { !a.strategies.entries.contains_key("arith.index_word"), "{name} {stem}" ); - let words = a - .strategies - .entries - .keys() - .any(|n| n.starts_with("arith.wide")); - assert!(!words, "{name} {stem}"); link_and_validate(&a, &p).unwrap_or_else(|e| panic!("{name} {stem}: L3: {e}")); } } diff --git a/crates/metal2vulkan/src/tests/engine_integer_median3.rs b/crates/metal2vulkan/src/tests/engine_integer_median3.rs index 26dcf5b6b..ab324881b 100644 --- a/crates/metal2vulkan/src/tests/engine_integer_median3.rs +++ b/crates/metal2vulkan/src/tests/engine_integer_median3.rs @@ -29,9 +29,7 @@ const WORDS: usize = 32; /// The committed `moltenvk-m3` profile: 64-bit operands in 64-bit containers. fn m3() -> DeviceProfile { - let p = profile("moltenvk-m3").expect("profile"); - assert!(p.fields().leaf.int64); - p + profile("moltenvk-m3").expect("profile") } /// splitmix64's output for `x`. diff --git a/crates/metal2vulkan/src/tests/engine_simd.rs b/crates/metal2vulkan/src/tests/engine_simd.rs index 018b8c68b..c056a0c7c 100644 --- a/crates/metal2vulkan/src/tests/engine_simd.rs +++ b/crates/metal2vulkan/src/tests/engine_simd.rs @@ -511,12 +511,6 @@ fn simd_kernels_compile_or_refuse_with_the_tier() { emulated += 1; } } - Err(Error::Unsupported(u)) => match u.feature { - // A value the profile cannot hold (the ballot's 64-bit result) is refused - // while selecting, before the tier. - Feature::Int64Arithmetic => {} - _ => panic!("{stem} {kernel}: {u:?}"), - }, Err(e) => panic!("{stem} {kernel}: {e}"), } } @@ -978,8 +972,8 @@ fn compute_derivatives_with_a_simd_operation_are_refused() { /// Metal has no simdgroup or quad function of 64-bit integers but the ballot (its `metal_simdgroup` /// and `metal_quadgroup` headers enable them for 8- to 32-bit integers, `half`, `float`, and -/// `double` only), so a call of one is invalid input on every committed profile, never -/// `Int64Arithmetic` or a subgroup capability. +/// `double` only), so a call of one is invalid input on every committed profile, never a subgroup +/// capability. #[test] fn sixty_four_bit_group_operations_are_not_metal() { let text = std::fs::read_to_string(engine_dir().join("store_const.ll")).expect("read"); diff --git a/crates/metal2vulkan/src/tests/engine_stage_io.rs b/crates/metal2vulkan/src/tests/engine_stage_io.rs index e40b5cfcc..a2bd82bb0 100644 --- a/crates/metal2vulkan/src/tests/engine_stage_io.rs +++ b/crates/metal2vulkan/src/tests/engine_stage_io.rs @@ -683,8 +683,7 @@ fn a_gated_off_attribute_in_use_reads_zero() { /// Metal rejects `long`/`ulong` as a vertex attribute, a varying, a stage builtin, a color output, /// and a color input ("type 'long' is not valid for attribute"), so a 64-bit integer there is -/// invalid input on every committed profile, never `Int64Arithmetic` (which `shaderInt64` would not -/// fix). Each case edits one fixture entry's value to `i64`. +/// invalid input on every committed profile. Each case edits one fixture entry's value to `i64`. #[test] fn sixty_four_bit_interface_values_are_not_metal() { use crate::air::error::AbiError; diff --git a/crates/metal2vulkan/tests/api_signatures.tsv b/crates/metal2vulkan/tests/api_signatures.tsv index c61cd1371..cfca2c6a4 100644 --- a/crates/metal2vulkan/tests/api_signatures.tsv +++ b/crates/metal2vulkan/tests/api_signatures.tsv @@ -9628,7 +9628,6 @@ variant metal2vulkan::error::Feature::IndependentBlending IndependentBlending variant metal2vulkan::error::Feature::IndirectRenderState IndirectRenderState variant metal2vulkan::error::Feature::InlineAsm InlineAsm variant metal2vulkan::error::Feature::Instruction Instruction { code: u32 } -variant metal2vulkan::error::Feature::Int64Arithmetic Int64Arithmetic variant metal2vulkan::error::Feature::Int64Atomics Int64Atomics variant metal2vulkan::error::Feature::InterfaceComponents InterfaceComponents variant metal2vulkan::error::Feature::IntersectionFunctionTable IntersectionFunctionTable @@ -9644,7 +9643,6 @@ variant metal2vulkan::error::Feature::ModuleRecord ModuleRecord { code: u32 } variant metal2vulkan::error::Feature::PartialThreadgroups PartialThreadgroups variant metal2vulkan::error::Feature::PixelCoverageAtSampleRate PixelCoverageAtSampleRate variant metal2vulkan::error::Feature::PixelSamplerCompare PixelSamplerCompare -variant metal2vulkan::error::Feature::PointerCompare PointerCompare variant metal2vulkan::error::Feature::PostDepthCoverage PostDepthCoverage variant metal2vulkan::error::Feature::PrimitiveId PrimitiveId variant metal2vulkan::error::Feature::PrivateMemory PrivateMemory diff --git a/docs/API.md b/docs/API.md index 8ef08ceb6..9bce89bd1 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1151,8 +1151,8 @@ measured on the M3 Max) draws nothing: an object function's wrapper launches not grid. An object grid runs at any count Metal runs, past the task stage's limits too, on a device with -device addresses, `shaderInt64`, `multiDrawIndirect` and `drawIndirectCount` (every committed -profile with the extension): the object function is compiled folded, its object stage reading the +`multiDrawIndirect` and `drawIndirectCount` (every committed profile with the extension): the +object function is compiled folded, its object stage reading the threadgroups Metal runs and its grid from a 32-byte region record at its `PushField::ReplayRegionAddress`, so a draw runs its grid in pieces within the task limits. Metal's threads per grid wrap to 32 bits along each axis, as its builtins report them. The lowering takes diff --git a/docs/REFUSALS.md b/docs/REFUSALS.md index 172e3e1c0..6169225aa 100644 --- a/docs/REFUSALS.md +++ b/docs/REFUSALS.md @@ -26,7 +26,7 @@ Columns: | Kind | Variants | With a site | Reach system | Reach app | Reach rare | Reach none | Unassessed | |---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 117 | 113 | 6 | 25 | 65 | 21 | 0 | +| Translator and front-end refusals | 115 | 111 | 6 | 25 | 63 | 21 | 0 | | Translation caps | 14 | 14 | 0 | 0 | 7 | 7 | 0 | | Rate maps the compile layer does not compile | 5 | 5 | 0 | 0 | 4 | 1 | 0 | | The translation deadline | 1 | 1 | 0 | 0 | 0 | 1 | 0 | @@ -39,7 +39,7 @@ Columns: | Kind | `metal-measured` | `metal-documented` | `metal-takes` | `device` | `ours` | `unknown` | `delegated` | `-` | |---|---|---|---|---|---|---|---|---| -| Translator and front-end refusals | 0 | 0 | 3 | 43 | 67 | 0 | 0 | 4 | +| Translator and front-end refusals | 0 | 0 | 3 | 41 | 67 | 0 | 0 | 4 | | Translation caps | 0 | 0 | 0 | 0 | 14 | 0 | 0 | 0 | | Rate maps the compile layer does not compile | 0 | 0 | 0 | 0 | 5 | 0 | 0 | 0 | | The translation deadline | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | @@ -78,7 +78,6 @@ Columns: | `ArgumentBufferTextures` | Argument buffers holding textures or samplers (handle domain) | devices without a capability the site computes (`gaps`); devices without a capability the site computes (`missing`); every device (not implemented) | `ours` | 12: `crates/metal2vulkan/src/bind/heap.rs (member_storage_format, 4 sites)`, `crates/metal2vulkan/src/bind/heap.rs (member_texel_view, 2 sites)` (+5) | `app`: argument buffers holding textures and samplers (bindless) | | `ArgumentBufferObjects` | Argument-buffer members that are pipeline states, ICBs, function tables, or acceleration structures | every device (not implemented) | `ours` | 4: `crates/metal2vulkan/src/lower/access/icb.rs (select)`, `crates/metal2vulkan/src/lower/access/object.rs (select)` (+2) | `rare`: pipeline states and ICBs in argument buffers | | `DereferenceLoadedPointer` | Dereferencing a pointer loaded from memory or made from an integer | every device (no Vulkan mechanism) | `device` | 2: `crates/metal2vulkan/src/lower/access/local.rs (access_ptr)`, `crates/metal2vulkan/src/lower/access/local.rs (threadgroup_constant_refusal)` | `app`: pointers loaded from argument buffers | -| `PointerCompare` | Comparing pointers with different roots | devices without VkFeature::ShaderInt64 | `device` | via a helper: 1: `crates/metal2vulkan/src/lower/access/copy.rs (addressed)` | `rare`: comparing pointers of different roots | | `HandleAsPointer` | A resource handle used as a byte pointer, or conflicting handle provenance | every device (no Vulkan mechanism); every device (not implemented) | `ours` | 6: `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)`, `crates/metal2vulkan/src/lower/access/handle.rs (element, 2 sites)` (+3) | `rare`: resource handles used as byte pointers | | `ConstantGlobalEscaping` | A constant global whose address escapes | every device (not implemented) | `ours` | 2: `crates/metal2vulkan/src/memory/plan.rs (blob_nodes)`, `crates/metal2vulkan/src/memory/plan.rs (serialize)` | `rare`: a constant global whose address escapes | | `ThreadgroupMemorySize` | Threadgroup memory above the device limit | devices short of a device limit the site names; every device (no Vulkan mechanism) | `device` | 2: `crates/metal2vulkan/src/memory/arena.rs (check)`, `crates/metal2vulkan/src/memory/plan.rs (too_large)` | `rare`: threadgroup memory past a smaller device's limit | @@ -87,7 +86,6 @@ Columns: | `Int64Atomics` | 64-bit atomics | devices short of a Vulkan feature the site names | `device` | 1: `crates/metal2vulkan/src/lower/access/atomic.rs (select)` | `rare`: 64-bit atomics | | `ImageAtomics` | Image atomics beyond 32-bit integers | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/texture/atomic.rs (select)` | `rare`: texture atomics beyond 32-bit integers | | `DescriptorCount` | Too many descriptors of one kind in a stage or pipeline | devices short of a device limit the site names | `device` | 2: `crates/metal2vulkan/src/lower/select.rs (finish)`, `crates/metal2vulkan/src/pipeline/link.rs (limit_error)` | `app`: many textures or buffers in one stage on a smaller device | -| `Int64Arithmetic` | 64-bit integer arithmetic | devices without VkFeature::ShaderInt64 | `device` | 2: `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)`, `crates/metal2vulkan/src/lower/select.rs (selector_form)` | `rare`: 64-bit integers on a device without shaderInt64 | | `Float64Arithmetic` | 64-bit float arithmetic | devices without VkFeature::ShaderFloat64 | `device` | 2: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`, `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)` | `rare`: doubles (MSL has none outside Apple's own code) | | `Format` | A pixel or vertex format not supported for the required use | devices without VkFeature::ShaderStorageImageExtendedFormats; devices without a capability the site computes (`alternatives`); devices without a capability the site computes (`missing`); devices without a capability the site computes (`routes`); devices without a format's usage; every device (no Vulkan mechanism); every device (not implemented) | `ours` | 47: `crates/metal2vulkan/src/lower/access/tile.rs (storage_format)`, `crates/metal2vulkan/src/lower/fragment/color.rs (select_param, 5 sites)` (+25) | `system`: pixel formats a device lacks for a use (CoreVideo's 4:2:x and 10-bit formats among them) | | `DivergentImplicitLod` | Divergent implicit-LOD sampling or LOD query through a multi-candidate handle | every device (not implemented) | `ours` | 1: `crates/metal2vulkan/src/lower/sampler/select.rs (tangled)` | `app`: implicit-LOD sampling through a dynamically chosen texture | @@ -410,7 +408,6 @@ Each refusal's sites, with the function that builds it. - `feature::ArgumentBufferTextures`: `crates/metal2vulkan/src/bind/heap.rs (member_storage_format, 4 sites)`; `crates/metal2vulkan/src/bind/heap.rs (member_texel_view, 2 sites)`; `crates/metal2vulkan/src/lower/access/handle.rs (select)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_one)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_sampling)`; `crates/metal2vulkan/src/lower/texture/atomic.rs (select)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_heap, 2 sites)` - `feature::ArgumentBufferObjects`: `crates/metal2vulkan/src/lower/access/icb.rs (select)`; `crates/metal2vulkan/src/lower/access/object.rs (select)`; `crates/metal2vulkan/src/memory/provenance.rs (access)`; `crates/metal2vulkan/src/memory/provenance.rs (classify)` - `feature::DereferenceLoadedPointer`: `crates/metal2vulkan/src/lower/access/local.rs (access_ptr)`; `crates/metal2vulkan/src/lower/access/local.rs (threadgroup_constant_refusal)` -- `feature::PointerCompare`: `crates/metal2vulkan/src/lower/access/copy.rs (addressed)` - `feature::HandleAsPointer`: `crates/metal2vulkan/src/lower/access/handle.rs (domain_kind)`; `crates/metal2vulkan/src/lower/access/handle.rs (element, 2 sites)`; `crates/metal2vulkan/src/memory/plan.rs (reprs)`; `crates/metal2vulkan/src/memory/provenance.rs (classify)`; `crates/metal2vulkan/src/memory/provenance.rs (seed)` - `feature::ConstantGlobalEscaping`: `crates/metal2vulkan/src/memory/plan.rs (blob_nodes)`; `crates/metal2vulkan/src/memory/plan.rs (serialize)` - `feature::ThreadgroupMemorySize`: `crates/metal2vulkan/src/memory/arena.rs (check)`; `crates/metal2vulkan/src/memory/plan.rs (too_large)` @@ -419,7 +416,6 @@ Each refusal's sites, with the function that builds it. - `feature::Int64Atomics`: `crates/metal2vulkan/src/lower/access/atomic.rs (select)` - `feature::ImageAtomics`: `crates/metal2vulkan/src/lower/texture/atomic.rs (select)` - `feature::DescriptorCount`: `crates/metal2vulkan/src/lower/select.rs (finish)`; `crates/metal2vulkan/src/pipeline/link.rs (limit_error)` -- `feature::Int64Arithmetic`: `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)`; `crates/metal2vulkan/src/lower/select.rs (selector_form)` - `feature::Float64Arithmetic`: `crates/metal2vulkan/src/device/metal.rs (unsupported_features)`; `crates/metal2vulkan/src/lower/arith/legal.rs (check_scalar)` - `feature::Format`: `crates/metal2vulkan/src/lower/access/tile.rs (storage_format)`; `crates/metal2vulkan/src/lower/fragment/color.rs (select_param, 5 sites)`; `crates/metal2vulkan/src/lower/sampler/select.rs (select_extended)`; `crates/metal2vulkan/src/lower/stage_io/extended_color.rs (plan, 2 sites)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (entry)`; `crates/metal2vulkan/src/lower/stage_io/plan.rs (zeroed_output)`; `crates/metal2vulkan/src/lower/stage_io/word_color.rs (plan)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_image)`; `crates/metal2vulkan/src/lower/texture/mod.rs (select_read)`; `crates/metal2vulkan/src/lower/texture/slot.rs (atomic_format, 2 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (declare_slot)`; `crates/metal2vulkan/src/lower/texture/slot.rs (storage_format, 6 sites)`; `crates/metal2vulkan/src/lower/texture/slot.rs (ulong_format, 3 sites)`; `crates/metal2vulkan/src/lower/texture/words.rs (not_built)`; `crates/metal2vulkan/src/metal/format/mod.rs (candidates)`; `crates/metal2vulkan/src/metal/format/mod.rs (held_storage_choice, 3 sites)`; `crates/metal2vulkan/src/metal/format/mod.rs (storage_choice)`; `crates/metal2vulkan/src/metal/format/mod.rs (vk_format, 2 sites)`; `crates/metal2vulkan/src/metal/vertex.rs (fetch_as, 2 sites)`; `crates/metal2vulkan/src/pipeline/color_writes.rs (rotated_blend_in_shader)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (extended_write_mask, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (graphics_state, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (reads_alpha_to_coverage, 2 sites)`; `crates/metal2vulkan/src/pipeline/link/graphics.rs (textured_fetches)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (alpha_in_red_blend)`; `crates/metal2vulkan/src/pipeline/rotated_blend.rs (rotated_blend)` - `feature::DivergentImplicitLod`: `crates/metal2vulkan/src/lower/sampler/select.rs (tangled)` diff --git a/scripts/refusal-surface/reach.tsv b/scripts/refusal-surface/reach.tsv index d1c1b7b49..7b5637016 100644 --- a/scripts/refusal-surface/reach.tsv +++ b/scripts/refusal-surface/reach.tsv @@ -28,7 +28,6 @@ feature SimdgroupMatrix16x16x16 rare 16x16x16 simdgroup matrix products (Metal: feature ArgumentBufferTextures app argument buffers holding textures and samplers (bindless) feature ArgumentBufferObjects rare pipeline states and ICBs in argument buffers feature DereferenceLoadedPointer app pointers loaded from argument buffers -feature PointerCompare rare comparing pointers of different roots feature HandleAsPointer rare resource handles used as byte pointers feature ConstantGlobalEscaping rare a constant global whose address escapes feature ThreadgroupMemorySize rare threadgroup memory past a smaller device's limit @@ -37,7 +36,6 @@ feature CoherentMemory rare coherent(device) accesses feature Int64Atomics rare 64-bit atomics feature ImageAtomics rare texture atomics beyond 32-bit integers feature DescriptorCount app many textures or buffers in one stage on a smaller device -feature Int64Arithmetic rare 64-bit integers on a device without shaderInt64 feature Float64Arithmetic rare doubles (MSL has none outside Apple's own code) feature Format system pixel formats a device lacks for a use (CoreVideo's 4:2:x and 10-bit formats among them) feature DivergentImplicitLod app implicit-LOD sampling through a dynamically chosen texture