From 0630c1d9a7d238f1b85dfcbbdac3190a8fb80ee9 Mon Sep 17 00:00:00 2001 From: Anees Iqbal Date: Mon, 23 Nov 2026 20:36:41 -0800 Subject: [PATCH] Translator: specialize refuses an instruction it would leave half specialized pipeline::specialize copied every instruction outside its list as it was. An OpExecutionModeId (a LocalSizeId mode among them) beside a WorkgroupSize composite would leave the entry point with two sizes, and an OpDecorationGroup could carry a SpecId the pass never reads, so that constant would keep its default. The translator writes neither, so the pass now refuses both with an Error::Internal that names the instruction. An OpSpecConstantOp of an opcode outside SpecOp was already refused; its refusal now names the opcode. Op::ExecutionModeId and Op::DecorationGroup move into every build, and ExecutionMode::LocalSizeId into test builds. Both come through scripts/regen-spirv-grammar's items.txt and a regeneration from Khronos's grammar (vulkan-sdk-1.4.341.0); table.rs comes out unchanged. Test: a_module_of_an_instruction_the_pass_does_not_specialize_is_refused takes the deep kernel with an OpExecutionModeId LocalSizeId of its LocalSize constants, with an OpDecorationGroup, and with an OpSpecConstantOp turned to ISub. Each must be refused, and the refusal must name the instruction. The next check job runs it. --- .../src/spirv/serialize/tests/specialize.rs | 69 +++++++++++++++++++ crates/metal2vulkan/src/spirv/specialize.rs | 26 +++++-- crates/metal2vulkan/src/spv.rs | 8 +-- scripts/regen-spirv-grammar/items.txt | 4 +- 4 files changed, 92 insertions(+), 15 deletions(-) diff --git a/crates/metal2vulkan/src/spirv/serialize/tests/specialize.rs b/crates/metal2vulkan/src/spirv/serialize/tests/specialize.rs index 68ab29ab4..511b667d5 100644 --- a/crates/metal2vulkan/src/spirv/serialize/tests/specialize.rs +++ b/crates/metal2vulkan/src/spirv/serialize/tests/specialize.rs @@ -217,3 +217,72 @@ fn a_module_without_a_workgroup_composite_keeps_its_mode() { .count(); assert_eq!(modes, 1); } + +/// `words` with `inst` after the first instruction of `after`, its id bound grown by `ids`. +fn inserted(words: &[u32], after: Op, inst: &[u32], ids: u32) -> Vec { + let mut at = 5; + while words[at] & 0xFFFF != after as u32 { + at += (words[at] >> 16) as usize; + } + at += (words[at] >> 16) as usize; + let mut out = words.to_vec(); + out.splice(at..at, inst.iter().copied()); + out[3] += ids; + out +} + +/// A module holding an instruction the translator does not write, whose constants the pass would +/// leave half specialized, is refused, the refusal naming it: an `OpExecutionModeId` of +/// `LocalSizeId`, an `OpDecorationGroup`, an `OpSpecConstantOp` of `ISub`. +#[test] +fn a_module_of_an_instruction_the_pass_does_not_specialize_is_refused() { + let (words, ids, _) = linked(deep_kernel()); + let entry = (insts(&words).into_iter()) + .find(|(op, _)| *op == Op::EntryPoint as u32) + .map(|(_, operands)| operands[1]) + .expect("entry point"); + let local = |axis| { + (ids.iter()) + .find(|&&(key, _)| key == SpecKey::LocalSize(axis)) + .map(|&(_, id)| id) + .expect("a LocalSize constant") + }; + // The LocalSize constants' result ids, by the SpecId decorations that name them. + let decorated = |spec: u32| { + (insts(&words).into_iter()) + .find(|(op, operands)| { + *op == Op::Decorate as u32 && operands[1..] == [Decoration::SpecId as u32, spec] + }) + .map(|(_, operands)| operands[0]) + .expect("a SpecId decoration") + }; + let [x, y, z] = [Axis::X, Axis::Y, Axis::Z].map(|axis| decorated(local(axis))); + let mode_id = [ + (6 << 16) | Op::ExecutionModeId as u32, + entry, + ExecutionMode::LocalSizeId as u32, + x, + y, + z, + ]; + let bound = words[3]; + let group = [(2 << 16) | Op::DecorationGroup as u32, bound]; + let mut subtract = words.clone(); + let mut at = 5; + while subtract[at] & 0xFFFF != Op::SpecConstantOperation as u32 { + at += (subtract[at] >> 16) as usize; + } + subtract[at + 3] = Op::ISub as u32; + for (module, named) in [ + (inserted(&words, Op::EntryPoint, &mode_id, 0), "OpExecutionModeId"), + (inserted(&words, Op::Decorate, &group, 1), "OpDecorationGroup"), + (subtract, "OpSpecConstantOp of opcode 130"), + ] { + match specialize(&module, &[]) { + Err(crate::error::Error::Internal(error)) => { + assert!(error.detail.contains(named), "{named}: {error}"); + } + other => panic!("{named}: {:?}", other.map(|w| w.len())), + } + } +} diff --git a/crates/metal2vulkan/src/spirv/specialize.rs b/crates/metal2vulkan/src/spirv/specialize.rs index db9f16798..b400f4ceb 100644 --- a/crates/metal2vulkan/src/spirv/specialize.rs +++ b/crates/metal2vulkan/src/spirv/specialize.rs @@ -26,10 +26,12 @@ enum Scalar { } /// The instructions the pass reads or rewrites; it copies every other as it is. -const READ: [Op; 15] = [ +const READ: [Op; 17] = [ Op::Decorate, + Op::DecorationGroup, Op::EntryPoint, Op::ExecutionMode, + Op::ExecutionModeId, Op::TypeBool, Op::TypeInt, Op::TypeFloat, @@ -54,9 +56,11 @@ const READ: [Op; 15] = [ /// literal workgroup size states it. The result is valid where `words` is, under the same /// requirements, and runs as `words` specialized by `values` does. /// -/// Err: [`Error::Internal`] where the words are not such a module: a malformed instruction, a -/// specialization operation of an opcode the translator does not write, or a `WorkgroupSize` -/// beside a `LocalSize` mode or beside other than one entry point. +/// Err: [`Error::Internal`], naming what it met, where the words are not such a module: a +/// malformed instruction; an instruction the translator does not write, whose constants the pass +/// would leave half specialized (an `OpExecutionModeId`, a `LocalSizeId` mode among them; an +/// `OpDecorationGroup`; an `OpSpecConstantOp` of another opcode); or a `WorkgroupSize` beside a +/// `LocalSize` mode or beside other than one entry point. pub fn specialize(words: &[u32], values: &[(u32, u64)]) -> Result, Error> { let header = words .get(..5) @@ -99,6 +103,13 @@ pub fn specialize(words: &[u32], values: &[(u32, u64)]) -> Result, Erro workgroup = Some(operand(1)?); continue; } + // A mode of id operands (`LocalSizeId` among them) could name a size the pass would + // set a second time, and a group's decorations a `SpecId` it would miss. + Some(unknown @ (Op::ExecutionModeId | Op::DecorationGroup)) => { + return Err(malformed(format!( + "an Op{unknown:?}, which the translator does not write" + ))); + } Some(Op::EntryPoint) => { out.extend_from_slice(inst); entries.push((operand(2)?, out.len())); @@ -148,8 +159,9 @@ pub fn specialize(words: &[u32], values: &[(u32, u64)]) -> Result, Erro } Some(Op::SpecConstantOperation) => { let (ty, id) = (operand(1)?, operand(2)?); - let op = SpecOp::of_opcode(operand(3)?) - .ok_or_else(|| malformed("a specialization operation of another opcode"))?; + let code = operand(3)?; + let unknown = || malformed(format!("an OpSpecConstantOp of opcode {code}")); + let op = SpecOp::of_opcode(code).ok_or_else(unknown)?; let operands: Vec<(u64, Scalar)> = (tail(4).iter()) .map(|o| known.get(o).copied()) .collect::>() @@ -211,7 +223,7 @@ pub fn specialize(words: &[u32], values: &[(u32, u64)]) -> Result, Erro Ok(out) } -fn malformed(detail: &str) -> Error { +fn malformed(detail: impl std::fmt::Display) -> Error { Error::Internal(InternalError::new( InternalKind::Invariant, format!("specialize: {detail}"), diff --git a/crates/metal2vulkan/src/spv.rs b/crates/metal2vulkan/src/spv.rs index a14ef2b42..45e71e039 100644 --- a/crates/metal2vulkan/src/spv.rs +++ b/crates/metal2vulkan/src/spv.rs @@ -141,7 +141,6 @@ pub enum Op { InBoundsPtrAccessChain = 70, Decorate = 71, MemberDecorate = 72, - #[cfg(test)] DecorationGroup = 73, #[cfg(test)] GroupDecorate = 74, @@ -474,7 +473,6 @@ pub enum Op { MemoryNamedBarrier = 329, #[cfg(test)] ModuleProcessed = 330, - #[cfg(test)] ExecutionModeId = 331, #[cfg(test)] DecorateId = 332, @@ -1631,7 +1629,6 @@ impl std::fmt::Debug for Op { Self::InBoundsPtrAccessChain => "InBoundsPtrAccessChain", Self::Decorate => "Decorate", Self::MemberDecorate => "MemberDecorate", - #[cfg(test)] Self::DecorationGroup => "DecorationGroup", #[cfg(test)] Self::GroupDecorate => "GroupDecorate", @@ -1966,7 +1963,6 @@ impl std::fmt::Debug for Op { Self::MemoryNamedBarrier => "MemoryNamedBarrier", #[cfg(test)] Self::ModuleProcessed => "ModuleProcessed", - #[cfg(test)] Self::ExecutionModeId => "ExecutionModeId", #[cfg(test)] Self::DecorateId => "DecorateId", @@ -3327,7 +3323,6 @@ impl Op { 70 => Self::InBoundsPtrAccessChain, 71 => Self::Decorate, 72 => Self::MemberDecorate, - #[cfg(test)] 73 => Self::DecorationGroup, #[cfg(test)] 74 => Self::GroupDecorate, @@ -3660,7 +3655,6 @@ impl Op { 329 => Self::MemoryNamedBarrier, #[cfg(test)] 330 => Self::ModuleProcessed, - #[cfg(test)] 331 => Self::ExecutionModeId, #[cfg(test)] 332 => Self::DecorateId, @@ -5725,6 +5719,8 @@ pub enum ExecutionMode { OutputPoints = 27, #[cfg(test)] ContractionOff = 31, + #[cfg(test)] + LocalSizeId = 38, SubgroupUniformControlFlowKHR = 4421, DenormPreserve = 4459, SignedZeroInfNanPreserve = 4461, diff --git a/scripts/regen-spirv-grammar/items.txt b/scripts/regen-spirv-grammar/items.txt index 52bf16041..07148ab75 100644 --- a/scripts/regen-spirv-grammar/items.txt +++ b/scripts/regen-spirv-grammar/items.txt @@ -64,7 +64,7 @@ values RayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR values RayQueryGetIntersectionGeometryIndexKHR RayQueryGetIntersectionPrimitiveIndexKHR values RayQueryGetIntersectionBarycentricsKHR RayQueryGetIntersectionFrontFaceKHR values RayQueryGetIntersectionObjectToWorldKHR RayQueryGetIntersectionWorldToObjectKHR -values AtomicFAddEXT +values AtomicFAddEXT ExecutionModeId DecorationGroup test-values * enum Capability @@ -89,7 +89,7 @@ values Quads OutputVertices OutputPoints SubgroupUniformControlFlowKHR SignedZer values StencilRefReplacingEXT RequireFullQuadsKHR OutputLinesEXT OutputPrimitivesEXT values DerivativeGroupLinearKHR OutputTrianglesEXT PixelInterlockOrderedEXT values MaximallyReconvergesKHR DenormPreserve RoundingModeRTE -test-values ContractionOff FPFastMathDefault +test-values ContractionOff FPFastMathDefault LocalSizeId enum StorageClass values UniformConstant Input Uniform Output Workgroup Private Function PushConstant Image