diff --git a/crates/metal2vulkan-air/src/bitcode/function.rs b/crates/metal2vulkan-air/src/bitcode/function.rs index e2390e3d1..0f4a46229 100644 --- a/crates/metal2vulkan-air/src/bitcode/function.rs +++ b/crates/metal2vulkan-air/src/bitcode/function.rs @@ -81,8 +81,8 @@ use crate::intrinsics::{self, Bound, DeclClass}; use crate::ir::{ AddrSpace, Align, Arena, Atomic, AtomicRmwOp, Block, BlockId, Body, Call, CallAttrs, Callee, CastOp, Const, ConstId, ConstTable, FastMath, FloatPredicate, FuncId, Function, Inst, InstId, - InstKind, IntFlags, IntPredicate, LoopHints, Md, MdId, Ordering, RangeMd, Sym, Symbols, - SyncScope, TailKind, Type, TypeId, TypeTable, Unroll, Value, + InstKind, IntFlags, IntPredicate, LoopHints, Md, MdId, Ordering, ParamAttrs, RangeMd, Sym, + Symbols, SyncScope, TailKind, Type, TypeId, TypeTable, Unroll, Value, }; const B: u32 = FUNCTION_BLOCK; @@ -1536,7 +1536,7 @@ impl FnDecoder { return self.drop_call(s, cx, m); } let mut enums = SiteEnums::default(); - let attrs = match list { + let mut attrs = match list { None => None, Some(list) => { let bc_params = cx.bc_types.params(fn_bc).unwrap_or(&[]); @@ -1559,6 +1559,15 @@ impl FnDecoder { })) } }; + if let Target::Intrinsic(_, class) = &target { + // An older LLVM's memory intrinsic takes its alignment as an operand; the current + // form states it as the pointers' `align` attribute, which lowering reads. + let upgraded = intrinsics::upgrade_legacy_memory(*class, &mut args, cx.consts) + .map_err(|e| InputError::new(InputErrorKind::Intrinsic(e), s.location()))?; + if let Some(legacy) = upgraded { + attrs = upgrade_legacy_attrs(attrs, &mut enums, legacy, m)?; + } + } let callee = match target { Target::Callee(c) => c, Target::Intrinsic(f, class) => match intrinsics::bind(class, &args, cx.consts) { @@ -1740,6 +1749,46 @@ impl FnDecoder { } } +/// `attrs` and `enums` of a legacy memory intrinsic's call, upgraded as LLVM's reader does: the +/// removed alignment operand's attributes go with it, the later positions move down, and the +/// leading pointer operands' `align` is the alignment the operand stated (replacing their own, +/// none for an alignment of 0). +pub(super) fn upgrade_legacy_attrs( + attrs: Option>, + enums: &mut SiteEnums, + legacy: intrinsics::LegacyAlignment, + m: &mut Meter, +) -> Result>, Error> { + if enums.params.len() > legacy.removed { + enums.params.remove(legacy.removed); + } + let CallAttrs { func, ret, params } = match attrs { + Some(a) => *a, + None if legacy.align.is_none() => return Ok(None), + None => { + m.charge(std::mem::size_of::())?; + CallAttrs::default() + } + }; + let mut params = params.into_vec(); + if params.len() > legacy.removed { + params.remove(legacy.removed); + } + if legacy.align.is_some() { + let missing = legacy.pointers.saturating_sub(params.len()); + m.reserve(&mut params, missing)?; + params.resize(params.len().max(legacy.pointers), ParamAttrs::default()); + } + for p in params.iter_mut().take(legacy.pointers) { + p.align = legacy.align; + } + Ok(Some(Box::new(CallAttrs { + func, + ret, + params: params.into_boxed_slice(), + }))) +} + /// What a call's callee operand names, before its arguments are read. enum Target { /// A direct or indirect call. diff --git a/crates/metal2vulkan-air/src/bitcode/function_tests.rs b/crates/metal2vulkan-air/src/bitcode/function_tests.rs index 2c316257a..b8a6d77b1 100644 --- a/crates/metal2vulkan-air/src/bitcode/function_tests.rs +++ b/crates/metal2vulkan-air/src/bitcode/function_tests.rs @@ -12,10 +12,11 @@ use super::ModuleTables; use crate::bitstream::writer::Writer; use crate::error::BitcodeError; use crate::error::{Error, Feature}; +use crate::intrinsics::LlvmIntrinsic; use crate::ir::print::print; use crate::ir::{ - BlockId, Callee, Const, FuncId, InstId, InstKind, IntFlags, IntPredicate, Md, MdId, Type, - Unroll, Value, + Align, BlockId, Callee, Const, FuncId, InstId, InstKind, IntFlags, IntPredicate, Md, MdId, + Type, Unroll, Value, }; const STRTAB: &[u8] = b"kair.x"; @@ -1305,3 +1306,206 @@ fn legacy_metadata_records_read_as_their_modern_twins() { refused(decode_err(legacy_module(&[(8, vec![6, 0])], 5)), 8); refused(decode_err(module_with(&[(9, vec![0, 2])], &[])), 9); } + +/// How a legacy memory intrinsic's alignment operand is written in [`legacy_copy_module`]. +#[derive(Clone, Copy)] +enum LegacyAlign { + /// An `i32` constant. + Constant(u64), + /// The kernel's second parameter. + Parameter, +} + +/// `@k(ptr addrspace(1) %p [, i32 %a])` calling `llvm.memcpy.p1i8.p1i8.i64` as an LLVM before the +/// alignment moved to the pointers' attributes declared it, `void (ptr, ptr, i64, i32, i1)`: +/// `memcpy(%p, %p, 400, , false)`. Types: 0 `i64`, 1 `i32`, 2 `i1`, 3 `void`, 4 `ptr +/// addrspace(1)`, 5 the declaration's, 6 the kernel's. Values: `@k` 0, the declaration 1, `%p` +/// 2, `%a` 3 where there is one, then the local constants. +fn legacy_copy_module(align: LegacyAlign) -> Vec { + const NAMES: &[u8] = b"kllvm.memcpy.p1i8.p1i8.i64"; + let parameter = matches!(align, LegacyAlign::Parameter); + let first_const = if parameter { 4 } else { 3 }; + stream(2, 0, NAMES, |w| { + block( + w, + codes::TYPE_BLOCK, + &[ + (1, vec![7]), + (7, vec![64]), + (7, vec![32]), + (7, vec![1]), + (2, vec![]), + (25, vec![1]), + (21, vec![0, 3, 4, 4, 0, 1, 2]), + ( + 21, + vec![0, 3, 4, 1][..if parameter { 4 } else { 3 }].to_vec(), + ), + ], + ); + w.unabbrev(8, &[0, 1, 6, 0, 0, 0, 0, 0, 0]); + w.unabbrev(8, &[1, 25, 5, 0, 1, 0, 0, 0, 0]); + // Local constants: `i64 400`, then the alignment where it is one, then `i1 false`. + let mut consts = vec![(1, vec![0]), (4, vec![800])]; + let mut at = first_const; + let align_at = match align { + LegacyAlign::Constant(bytes) => { + consts.extend([(1, vec![1]), (4, vec![bytes * 2])]); + at += 1; + at + } + LegacyAlign::Parameter => 3, + }; + consts.extend([(1, vec![2]), (4, vec![0])]); + let (len, no) = (first_const, at + 1); + let next = no + 1; + w.enter(u64::from(codes::FUNCTION_BLOCK), 4); + w.unabbrev(1, &[1]); + block(w, codes::CONSTANTS_BLOCK, &consts); + w.unabbrev( + 34, + &[ + 0, + 1 << 15, + 5, + rel(next, 1), + rel(next, 2), + rel(next, 2), + rel(next, len), + rel(next, align_at), + rel(next, no), + ], + ); + w.unabbrev(10, &[]); + w.end(); + }) +} + +/// A memory intrinsic declared with an alignment operand decodes to the current form: the +/// operand is gone, and its value is the `align` of the destination and the source, as LLVM's +/// reader upgrades it. Metal's compilers before the move wrote this form, and lowering reads +/// the alignment from the attribute only. +#[test] +fn a_legacy_memory_intrinsic_states_its_alignment_on_its_pointers() { + let t = decode(&legacy_copy_module(LegacyAlign::Constant(16))).unwrap(); + // The upgraded call verifies against the legacy declaration. + verify_module_level(&t).unwrap(); + let body = body_of_named(&t, b"k"); + let call = body + .insts + .values() + .find_map(|i| match &i.kind { + InstKind::Call(c) => Some(c), + _ => None, + }) + .unwrap(); + assert!(matches!( + call.callee, + Callee::Llvm { + op: LlvmIntrinsic::Memcpy { + volatile: false, + .. + }, + .. + } + )); + assert_eq!(call.args.len(), 4); + let sixteen = Align::from_bytes(16); + let params = &call.attrs.as_ref().unwrap().params; + assert_eq!( + params.iter().map(|p| p.align).collect::>(), + [sixteen, sixteen] + ); + // An alignment of 0 states none. + let none = decode(&legacy_copy_module(LegacyAlign::Constant(0))).unwrap(); + verify_module_level(&none).unwrap(); + let call = body_of_named(&none, b"k") + .insts + .values() + .find_map(|i| match &i.kind { + InstKind::Call(c) => Some(c.clone()), + _ => None, + }) + .unwrap(); + assert_eq!(call.args.len(), 4); + assert!(call.attrs.is_none()); +} + +/// An alignment that is not a constant power of two is refused, not dropped. +#[test] +fn a_legacy_memory_intrinsic_s_alignment_must_be_a_constant_power_of_two() { + for bad in [LegacyAlign::Parameter, LegacyAlign::Constant(24)] { + let e = decode(&legacy_copy_module(bad)).map(|_| ()).unwrap_err(); + assert!(format!("{e:?}").contains("ImmediateNotConstant"), "{e:?}"); + } +} + +/// An upgraded call's attributes move as LLVM's reader moves them: the removed alignment +/// operand's (position 3) go with it, the volatile flag's (position 4) become position 3's, and +/// the pointers' `align` is the operand's, replacing their own; an alignment of 0 removes it. +#[test] +fn a_legacy_memory_intrinsic_s_attributes_move_with_its_operands() { + use super::enum_attrs::{EnumAttrs, SiteEnums}; + use super::function::upgrade_legacy_attrs; + use crate::intrinsics::LegacyAlignment; + use crate::ir::{CallAttrs, ParamAttrs}; + let param = |align: Option, deref: Option| ParamAttrs { + align: align.and_then(Align::from_bytes), + dereferenceable: deref, + ..ParamAttrs::default() + }; + let kinds = |kind: u32| { + let mut e = EnumAttrs::default(); + e.insert(kind); + e + }; + let attrs = || { + Some(Box::new(CallAttrs { + params: vec![ + param(Some(4), Some(400)), + param(Some(4), None), + param(None, None), + param(None, Some(3)), + param(None, Some(4)), + ] + .into_boxed_slice(), + ..CallAttrs::default() + })) + }; + let enums = || SiteEnums { + params: vec![kinds(1), kinds(2), kinds(3), kinds(4), kinds(5)], + ..SiteEnums::default() + }; + let mut m = super::tests::meter(); + let legacy = |bytes: u64| LegacyAlignment { + align: Align::from_bytes(bytes), + removed: 3, + pointers: 2, + }; + let mut e = enums(); + let got = upgrade_legacy_attrs(attrs(), &mut e, legacy(16), &mut m) + .unwrap() + .unwrap(); + assert_eq!( + got.params.to_vec(), + [ + param(Some(16), Some(400)), + param(Some(16), None), + param(None, None), + param(None, Some(4)), + ] + ); + assert_eq!(e.params, [kinds(1), kinds(2), kinds(3), kinds(5)]); + // An alignment of 0 removes the pointers' own. + let mut e = enums(); + let got = upgrade_legacy_attrs(attrs(), &mut e, legacy(0), &mut m) + .unwrap() + .unwrap(); + assert_eq!(got.params[0], param(None, Some(400))); + assert_eq!(got.params[1], param(None, None)); + // No attributes and no alignment: none. + let mut e = SiteEnums::default(); + assert!(upgrade_legacy_attrs(None, &mut e, legacy(0), &mut m) + .unwrap() + .is_none()); +} diff --git a/crates/metal2vulkan-air/src/intrinsics/llvm.rs b/crates/metal2vulkan-air/src/intrinsics/llvm.rs index 209c9886b..0bdf22eee 100644 --- a/crates/metal2vulkan-air/src/intrinsics/llvm.rs +++ b/crates/metal2vulkan-air/src/intrinsics/llvm.rs @@ -683,6 +683,25 @@ impl LlvmIntrinsic { }) } + /// The signature of the declaration an older LLVM wrote for a memory intrinsic, which has an + /// `i32` alignment before the volatile flag; `None` for any other operation. + pub(super) fn legacy_signature(&self) -> Option { + let sig = self.signature()?; + let (ret, params) = (sig.ret, sig.params()); + match self { + LlvmIntrinsic::Memset { .. } + | LlvmIntrinsic::Memcpy { .. } + | LlvmIntrinsic::Memmove { .. } => { + let (head, flag) = params.split_at(params.len().checked_sub(1)?); + let mut legacy = head.to_vec(); + legacy.push(Operand::Imm(ImmKind::I32)); + legacy.extend_from_slice(flag); + Some(Signature::new(ret, &legacy)) + } + _ => None, + } + } + /// Read the call's immediates into the variant. pub(super) fn bind(self, imm: &Immediates<'_>) -> Result { Ok(match self { diff --git a/crates/metal2vulkan-air/src/intrinsics/mod.rs b/crates/metal2vulkan-air/src/intrinsics/mod.rs index 2114f9281..dd8625ec4 100644 --- a/crates/metal2vulkan-air/src/intrinsics/mod.rs +++ b/crates/metal2vulkan-air/src/intrinsics/mod.rs @@ -474,7 +474,14 @@ pub fn classify(name: &[u8], sym: Sym, fn_ty: TypeId, types: &TypeTable) -> Opti match llvm::parse(rest, sym, types, fn_ty) { Ok(llvm::Parsed::Dropped(d)) => DeclClass::Drop(d), Ok(llvm::Parsed::Kept(op)) => match op.signature() { - Some(sig) if !sig.matches(types, fn_ty) => DeclClass::Mismatch, + Some(sig) + if !sig.matches(types, fn_ty) + && !op + .legacy_signature() + .is_some_and(|legacy| legacy.matches(types, fn_ty)) => + { + DeclClass::Mismatch + } _ => DeclClass::Llvm(op), }, Err(llvm::Fail::Unknown) => DeclClass::Unknown, @@ -558,3 +565,56 @@ pub fn bind( DeclClass::Drop(_) | DeclClass::Unknown => Ok(Bound::Unknown), } } + +/// What upgrading a legacy memory intrinsic's call removed: the alignment it stated, and the +/// operand position it held. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct LegacyAlignment { + /// The alignment; `None` for an alignment of 0, which states none. + pub align: Option, + /// The position of the removed operand (3), whose attributes go with it. + pub removed: usize, + /// The pointer operands it applies to: the destination, and the source of a copy. + pub pointers: usize, +} + +/// Upgrade a call of a memory intrinsic declared with an `i32` alignment before the volatile flag +/// (`llvm.memcpy.p0i8.p0i8.i64(i8*, i8*, i64, i32, i1)`) to the current form, as LLVM's reader +/// upgrades it (`UpgradeIntrinsicCall`): the alignment operand is removed from `args` and returned, +/// and the caller removes that position's attributes and sets the pointer operands' `align` to it +/// (`setDestAlignment`, `setSourceAlignment`: replacing any the call states, and removing it for +/// an alignment of 0). `Ok(None)` for any other call. An alignment that is not a constant is +/// [`IntrinsicError::ImmediateNotConstant`], and so is a malformed one (not a power of two, or +/// above 2^32), which LLVM's verifier refuses: the error names an immediate the call cannot have. +pub(crate) fn upgrade_legacy_memory( + class: DeclClass, + args: &mut Vec, + consts: &ConstTable, +) -> Result, IntrinsicError> { + let DeclClass::Llvm(op) = class else { + return Ok(None); + }; + let Some(legacy) = op + .legacy_signature() + .filter(|legacy| legacy.params().len() == args.len()) + else { + return Ok(None); + }; + let removed = args.len().saturating_sub(2); + let align = match Immediates::new(legacy, args, consts).get(removed)? { + 0 => None, + bytes => { + Some(crate::ir::Align::from_bytes(bytes).ok_or(IntrinsicError::ImmediateNotConstant)?) + } + }; + args.remove(removed); + let pointers = match op { + LlvmIntrinsic::Memset { .. } => 1, + _ => 2, + }; + Ok(Some(LegacyAlignment { + align, + removed, + pointers, + })) +} diff --git a/crates/metal2vulkan-air/src/intrinsics/tests.rs b/crates/metal2vulkan-air/src/intrinsics/tests.rs index e96fae7ff..663b68199 100644 --- a/crates/metal2vulkan-air/src/intrinsics/tests.rs +++ b/crates/metal2vulkan-air/src/intrinsics/tests.rs @@ -898,6 +898,45 @@ fn llvm_bases_decode_against_their_declarations() { "{name}" ); } + // The declaration an older LLVM wrote: an `i32` alignment before the volatile flag. + let align = Operand::Imm(ImmKind::I32); + assert_eq!( + llvm( + "llvm.memcpy.p0i8.p1i8.i64", + void, + &[p0, p1, i64s, align, flag] + ), + DeclClass::Llvm(LlvmIntrinsic::Memcpy { + dst: AddrSpace::Thread, + src: AddrSpace::Device, + len: Elem::I64, + volatile: false, + }) + ); + assert!(matches!( + llvm( + "llvm.memmove.p1i8.p1i8.i32", + void, + &[p1, p1, i32s, align, flag] + ), + DeclClass::Llvm(LlvmIntrinsic::Memmove { .. }) + )); + assert!(matches!( + llvm( + "llvm.memset.p0i8.i64", + void, + &[p0, Operand::Num(NumTy::scalar(Elem::I8)), i64s, align, flag] + ), + DeclClass::Llvm(LlvmIntrinsic::Memset { .. }) + )); + assert_eq!( + llvm( + "llvm.memcpy.p0i8.p1i8.i64", + void, + &[p0, p1, i64s, flag, flag] + ), + DeclClass::Mismatch + ); let i8s = Operand::Num(NumTy::scalar(Elem::I8)); assert!(matches!( llvm("llvm.memset.p1.i32", void, &[p1, i8s, i32s, flag]), diff --git a/crates/metal2vulkan-air/src/ir/verify.rs b/crates/metal2vulkan-air/src/ir/verify.rs index 155dc119b..56eaed858 100644 --- a/crates/metal2vulkan-air/src/ir/verify.rs +++ b/crates/metal2vulkan-air/src/ir/verify.rs @@ -38,6 +38,7 @@ use crate::budget::Meter; use crate::error::Error; use crate::error::{DiagName, InputError, InputErrorKind, Location, VerifyError}; use crate::graph::{Cfg, DomTree}; +use crate::intrinsics::LlvmIntrinsic; /// A verified AIR module. Immutable: passes consume it with [`Module::into_parts`] and build a /// new one through [`Module::new`]. @@ -916,6 +917,34 @@ impl<'a> Verifier<'a> { let Some((ret, params, vararg)) = fn_sig(types, fn_ty) else { return operand(false); }; + // A memory intrinsic declared with an alignment operand (an older LLVM's form, + // its `i32` alignment before the `i1` volatile flag) is called without it: decode + // moved its value to the pointers' `align`. + let upgraded: Vec; + let legacy = |params: &[TypeId]| match params { + [.., align, flag] if params.len() == 5 => { + self.ty(*align) == Some(&Type::Int(32)) && self.is_i1(*flag) + } + _ => false, + }; + let params = match call.callee { + Callee::Llvm { + op: + LlvmIntrinsic::Memset { .. } + | LlvmIntrinsic::Memcpy { .. } + | LlvmIntrinsic::Memmove { .. }, + .. + } if !vararg && call.args.len() + 1 == params.len() && legacy(params) => { + upgraded = params + .iter() + .enumerate() + .filter(|&(i, _)| i + 2 != params.len()) + .map(|(_, &p)| p) + .collect(); + &upgraded[..] + } + _ => params, + }; let arity_ok = if vararg { call.args.len() >= params.len() } else { diff --git a/crates/metal2vulkan-air/src/ir/verify_tests.rs b/crates/metal2vulkan-air/src/ir/verify_tests.rs index b916c2b44..d56d274af 100644 --- a/crates/metal2vulkan-air/src/ir/verify_tests.rs +++ b/crates/metal2vulkan-air/src/ir/verify_tests.rs @@ -1052,3 +1052,60 @@ fn dominance_is_charged_to_the_ledger_and_returned() { Err(Error::LimitExceeded(crate::error::Limit::LedgerBytes)) ); } + +/// A memory intrinsic's call is one operand short of its declaration only where the declaration is +/// the older LLVM's form, an `i32` alignment before the `i1` volatile flag (decode removed the +/// call's alignment operand): a call one short of the current four-parameter form, or of a +/// five-parameter declaration whose fourth parameter is not `i32`, is refused. +#[test] +fn a_memory_intrinsic_call_one_short_only_of_the_legacy_declaration() { + let call = |legacy: bool, align_ty_i32: bool, args: usize| { + let mut m = ModuleBuilder::new(); + let t = tys(&mut m); + let i64t = m.int(64); + let mut params = vec![t.dev, t.dev, i64t]; + if legacy { + params.push(if align_ty_i32 { t.i32 } else { i64t }); + } + params.push(t.i1); + let decl_ty = m.fn_ty(t.void, ¶ms); + let decl = m.declare("llvm.memcpy.p1i8.p1i8.i64", decl_ty); + let len = m.const_int(i64t, 16); + let no = m.const_int(t.i1, 0); + let fty = m.fn_ty(t.void, &[t.dev, t.i32]); + let mut f = m.define("k", fty); + let all = [f.arg(0), f.arg(0), len, no]; + let args: Box<[Value]> = match args { + 4 => all.into(), + _ => [all[0], all[1], all[3]].into(), + }; + f.push( + t.void, + InstKind::Call(Box::new(Call { + callee: Callee::Llvm { + decl, + op: crate::intrinsics::LlvmIntrinsic::Memcpy { + dst: AddrSpace::Device, + src: AddrSpace::Device, + len: crate::intrinsics::Elem::I64, + volatile: false, + }, + }, + args, + fmf: FastMath::NONE, + tail: TailKind::None, + attrs: None, + range: None, + })), + ); + f.ret(None); + f.finish(); + m.finish() + }; + // Four operands of the current declaration, and of the legacy one. + assert!(call(false, true, 4).is_ok()); + assert!(call(true, true, 4).is_ok()); + // One short of the current declaration, and of a five-parameter one without the `i32`. + assert_eq!(verify_kind(call(false, true, 3)), VerifyError::OperandType); + assert_eq!(verify_kind(call(true, false, 4)), VerifyError::OperandType); +} diff --git a/crates/metal2vulkan/src/cache/mod.rs b/crates/metal2vulkan/src/cache/mod.rs index 346de8df3..d95be8597 100644 --- a/crates/metal2vulkan/src/cache/mod.rs +++ b/crates/metal2vulkan/src/cache/mod.rs @@ -60,7 +60,7 @@ mod tests; /// unchanged version, and its bless records the version. Independent of the crate's version and of /// [`ARTIFACT_FORMAT_VERSION`]. The commit that bumps it says what changed; this comment keeps no /// history. -pub const SEMANTICS_VERSION: u32 = 2390; +pub const SEMANTICS_VERSION: u32 = 2391; /// The byte-layout version of encoded artifacts (`CompiledFunction::to_bytes` and the /// [`PipelineArtifact`] encodings). Every encoded artifact carries it, and a decode under another