llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[mlir][SPIR-V] `canonicalize` produces invalid `spirv.SpecConstantOperation` by folding and hoisting enclosed op

Open lin334141-cell opened this issue 1 month ago • 3 comments

[mlir][SPIR-V] canonicalize produces invalid spirv.SpecConstantOperation by folding and hoisting enclosed op

Summary

Running mlir-opt --canonicalize on a valid module containing spirv.SpecConstantOperation with a constant-foldable enclosed op breaks the operation's structural verifier invariants, triggering:

error: 'spirv.SpecConstantOperation' op expected exactly 2 nested ops

The failure is caused by a two-step interaction between constant folding and OperationFolder constant hoisting:

  1. Step 1 (Folding): The greedy rewriter constant-folds the enclosed operation (e.g., spirv.IAdd(1, 1) into spirv.Constant 2) and materializes the new constant inside the spirv.SpecConstantOperation region.
    • Invariant violation 1: spirv.Constant does not have the UsableInSpecConstantOp trait, violating the enclosed-op contract.
  2. Step 2 (Hoisting): In the next iteration, OperationFolder::insertKnownConstant (mlir/lib/Transforms/Utils/FoldUtils.cpp) encounters this constant. Because spirv.SpecConstantOperation does not have RegionKind::IsolatedFromAbove (nor does the SPIR-V dialect implement DialectFoldInterface::shouldMaterializeInto for this region), getInsertionRegion resolves to the parent spirv.func body.
  3. The constant is hoisted out of spirv.SpecConstantOperation into the enclosing function.
    • Invariant violation 2 (observed crash): The region is left containing only spirv.mlir.yield (1 nested op instead of the required 2), failing the region cardinality verification check in spirv.SpecConstantOperationOp::verifyRegions.

Minimal Reproducer

// min.mlir
"builtin.module"() ({
  "spirv.module"() <{addressing_model = #spirv.addressing_model<Logical>, memory_model = #spirv.memory_model<GLSL450>}> ({
    "spirv.func"() <{function_control = #spirv.function_control<None>, function_type = () -> i32, sym_name = "f"}> ({
      %0 = "spirv.Constant"() <{value = 1 : i32}> : () -> i32
      %1 = "spirv.SpecConstantOperation"() ({
        %2 = "spirv.IAdd"(%0, %0) : (i32, i32) -> i32
        "spirv.mlir.yield"(%2) : (i32) -> ()
      }) : () -> i32
      "spirv.ReturnValue"(%1) : (i32) -> ()
    }) : () -> ()
  }) : () -> ()
}) : () -> ()

Run canonicalization:

mlir-opt min.mlir --canonicalize

Expected Behavior

canonicalize should preserve valid IR. If the enclosed operation within spirv.SpecConstantOperation folds, either:

  • The entire spirv.SpecConstantOperation should fold as a unit (e.g., replaced by the resulting constant in the parent block), or
  • The rewrite should be rejected if spirv.SpecConstantOperation semantics prevent partial in-region folding.

In no case should it emit a partially stripped spirv.SpecConstantOperation that fails verification.

Actual Behavior

Verification fails immediately on the modified IR:

min.mlir:5:12: error: 'spirv.SpecConstantOperation' op expected exactly 2 nested ops
note: see current operation:
%1 = "spirv.SpecConstantOperation"() ({
  "spirv.mlir.yield"(%0) : (i32) -> ()
}) : () -> i32

Suggested Fix Direction

  1. Fold the whole operation: When the enclosed operation in spirv.SpecConstantOperation is constant-foldable, treat spirv.SpecConstantOperation as foldable as a unit, replacing the entire op with the folded result in the enclosing scope.
  2. Prevent partial inner folding/hoisting: Ensure that constants are not individually materialized inside SpecConstantOperation or hoisted out leaving an invalid empty shell. Merely preventing the hoist (e.g. via DialectFoldInterface) is insufficient on its own, because spirv.Constant is not legal inside SpecConstantOperation (UsableInSpecConstantOp requirement).

Tested Versions

  • LLVM main at commit ca566d552f7a9e507388cdba9539dd6e36c94bef
  • LLVM 24.0.0git (67005b724c917e1bdca50c82ecaa1b21a69244ed, macOS arm64)

lin334141-cell avatar Nov 01 '26 04:11 lin334141-cell

@llvm/issue-subscribers-mlir

Author: lin334141-cell

# [mlir][SPIR-V] canonicalize produces invalid `spirv.SpecConstantOperation` during constant folding and hoisting

Versions

  • Reproduced on LLVM 24.0.0git at 67005b724c917e1bdca50c82ecaa1b21a69244ed (mlir-opt, Release + assertions) and on LLVM main at 61817b48e757f9a07f2a84e36326542052c12c22 (checked out 2026-10-29). Both fail identically. We do not claim these are the newest available revisions.
  • Source-status note (not a reproduction claim): as of 2026-11-01 the relevant logic on main is functionally unchanged — OperationFolder::insertKnownConstant in mlir/lib/Transforms/Utils/FoldUtils.cpp still hoists constants to the computed insertion region; the Oct-2026 refactors (#232574, #233776) only replaced op-&gt;moveBefore(...) with rewriter.moveOpBefore(...) and added a ConstantInsertionResult return. We have not built or run a newer revision.
  • The same failure signature ('spirv.SpecConstantOperation' op expected exactly 2 nested ops, exit code 1) was independently observed on Linux x86_64 builds by an external fuzzer pipeline on four distinct generated programs, all reducing to the structure below.

Description

mlir-opt --canonicalize rewrites a verifier-accepted module containing a spirv.SpecConstantOperation whose enclosed op can be constant-folded into IR that violates the spirv.SpecConstantOperation verification invariants. Two invariants are broken by the combined rewrite:

  • the enclosed-op contract: the region's first op must have the UsableInSpecConstantOp trait (mlir/include/mlir/Dialect/SPIRV/IR/SPIRVOps.h-declared trait; check at mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp:2181 at 67005b72), and
  • the region cardinality: the region must contain exactly 2 ops (mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp:2176-2177 at 67005b72).

Mechanism (traced with -debug-only=greedy-rewriter and a debugger breakpoint on Operation::moveBefore):

  1. Iteration 1 of the greedy driver constant-folds the enclosed op (e.g. spirv.ISub(x, x) or spirv.IAdd(c, c)) and materializes the resulting spirv.Constant inside the SpecConstantOperation region (at the folded op's insertion point). The region now has 2 ops, but the enclosed op is spirv.Constant, which does not have the UsableInSpecConstantOp trait (SPIRVStructureOps.td:68-72 at 67005b72 lists spirv.Constant's traits; the trait is carried by arithmetic ops such as spirv.IAdd), so this intermediate state already fails the enclosed-op contract if fully verified.
  2. Iteration 2: the per-iteration OperationFolder constant CSE calls OperationFolder::insertKnownConstant (mlir/lib/Transforms/Utils/FoldUtils.cpp, at revision 67005b72: line 113). getInsertionRegion (FoldUtils.cpp:26-45 at 67005b72) walks up from the constant's block: spirv.SpecConstantOperation is neither IsIsolatedFromAbove nor does the SPIR-V dialect implement DialectFoldInterface::shouldMaterializeInto for its region, so the insertion region resolves to the enclosing spirv.func body.
  3. The hoist then moves the constant out of the region (at 67005b72: FoldUtils.cpp:161-166, op-&gt;moveBefore(&amp;insertBlock-&gt;front())).
  4. The region now contains only the spirv.mlir.yield, whose operand references a value defined outside the region. Per-pass verification then fails on the cardinality invariant: 'spirv.SpecConstantOperation' op expected exactly 2 nested ops (spirv.SpecConstantOperationOp::verifyRegions, mlir/lib/Dialect/SPIRV/IR/SPIRVOps.cpp:2176-2177 at 67005b72).

In short, the constant folding and the subsequent hoisting together break the spirv.SpecConstantOperation verification invariants: the first step violates the enclosed-op trait contract, and the second step violates the region cardinality, the latter being the observed diagnostic.

Minimal reproducer (12 lines, file min.mlir)

"builtin.module"() ({
  "spirv.module"() &lt;{addressing_model = #spirv.addressing_model&lt;Logical&gt;, memory_model = #spirv.memory_model&lt;GLSL450&gt;}&gt; ({
    "spirv.func"() &lt;{function_control = #spirv.function_control&lt;None&gt;, function_type = () -&gt; i32, sym_name = "f"}&gt; ({
      %0 = "spirv.Constant"() &lt;{value = 1 : i32}&gt; : () -&gt; i32
      %1 = "spirv.SpecConstantOperation"() ({
        %2 = "spirv.IAdd"(%0, %0) : (i32, i32) -&gt; i32
        "spirv.mlir.yield"(%2) : (i32) -&gt; ()
      }) : () -&gt; i32
      "spirv.ReturnValue"(%1) : (i32) -&gt; ()
    }) : () -&gt; ()
  }) : () -&gt; ()
}) : () -&gt; ()

Commands

mlir-opt min.mlir --mlir-disable-threading --verify-each --mlir-print-op-generic \
  --pass-pipeline='builtin.module(canonicalize)' -o out.mlir

Expected behavior

canonicalize must preserve the spirv.SpecConstantOperation invariants: a legal enclosed op must not be individually rewritten into an op that fails the UsableInSpecConstantOp contract, and no constant hoisting may break the region's fixed structure. Alternatively, canonicalize may fold the entire spirv.SpecConstantOperation into a constant at a legal scope, or refuse the rewrite — it must not emit IR that fails the SpecConstantOperation verifier.

Actual behavior

Exit code 1:

min.mlir:5:12: error: 'spirv.SpecConstantOperation' op expected exactly 2 nested ops
note: see current operation:
%1 = "spirv.SpecConstantOperation"() ({
  "spirv.mlir.yield"(%0) : (i32) -&gt; ()
}) : () -&gt; i32

Upstream dedup (re-checked 2026-11-01)

  • GitHub issue/PR search repo:llvm/llvm-project SpecConstantOperation: only PR #207328 (closed; null-deref fix inside verifyRegions — different defect) and PR #147067 (SPV_EXT_replicated_composites — unrelated).
  • Exact diagnostic string "expected exactly 2 nested ops": no matching issue/PR (only an unrelated PR #2 whose diff contains the phrase as a typo fix).
  • The recent OperationFolder refactors #232574 and #233776 (Oct 2026) changed listener notification and return types but kept the hoisting behavior; our main reproduction build post-dates them and still fails.
  • Not covered by #236718 (tensor.cast canonicalize abort) or the RemoveDeadValues assertion family (#131433, #128332) — different passes and mechanisms.

We could not find an existing report covering this specific failure mechanism as of 2026-11-01.

Suggested fix directions

A complete fix needs to address both broken invariants:

  • A legal enclosed operation must not be individually constant-folded into an operation that does not satisfy the UsableInSpecConstantOp contract (so merely preventing the hoist, e.g. via DialectFoldInterface::shouldMaterializeInto, is not sufficient on its own — it would still leave an invalid enclosed spirv.Constant inside the region).
  • The subsequent constant hoisting (OperationFolder::insertKnownConstant) must not break the fixed structure of such regions.

An alternative is to treat the spirv.SpecConstantOperation as a unit: fold or rewrite the whole op (e.g. into the folded constant at a legal scope) when its enclosed op folds. The concrete approach is up to the maintainers; we are happy to help test any proposed fix.

Context

Four independently generated programs (two from a fresh pilot, two from a 24h production run) all hit this exact signature; all reduce to the same structure above, so we file this as a single defect.

Thank you for taking the time to review this report. I would greatly appreciate it if the maintainers could take a look when possible and help confirm whether this is indeed a compiler bug.

If you encounter any difficulties reproducing the issue, or if additional information or test cases would be helpful, please let me know. I would be happy to provide further details or assist with reproduction.

Thank you very much for your time and help!

lin334141-cell avatar Nov 05 '26 10:11 lin334141-cell

@llvm/issue-subscribers-mlir-spirv

Author: lin334141-cell

# [mlir][SPIR-V] `canonicalize` produces invalid `spirv.SpecConstantOperation` by folding and hoisting enclosed op

Summary

Running mlir-opt --canonicalize on a valid module containing spirv.SpecConstantOperation with a constant-foldable enclosed op breaks the operation's structural verifier invariants, triggering:

error: 'spirv.SpecConstantOperation' op expected exactly 2 nested ops

The failure is caused by a two-step interaction between constant folding and OperationFolder constant hoisting:

  1. Step 1 (Folding): The greedy rewriter constant-folds the enclosed operation (e.g., spirv.IAdd(1, 1) into spirv.Constant 2) and materializes the new constant inside the spirv.SpecConstantOperation region.
    • Invariant violation 1: spirv.Constant does not have the UsableInSpecConstantOp trait, violating the enclosed-op contract.
  2. Step 2 (Hoisting): In the next iteration, OperationFolder::insertKnownConstant (mlir/lib/Transforms/Utils/FoldUtils.cpp) encounters this constant. Because spirv.SpecConstantOperation does not have RegionKind::IsolatedFromAbove (nor does the SPIR-V dialect implement DialectFoldInterface::shouldMaterializeInto for this region), getInsertionRegion resolves to the parent spirv.func body.
  3. The constant is hoisted out of spirv.SpecConstantOperation into the enclosing function.
    • Invariant violation 2 (observed crash): The region is left containing only spirv.mlir.yield (1 nested op instead of the required 2), failing the region cardinality verification check in spirv.SpecConstantOperationOp::verifyRegions.

Minimal Reproducer

// min.mlir
"builtin.module"() ({
  "spirv.module"() &lt;{addressing_model = #spirv.addressing_model&lt;Logical&gt;, memory_model = #spirv.memory_model&lt;GLSL450&gt;}&gt; ({
    "spirv.func"() &lt;{function_control = #spirv.function_control&lt;None&gt;, function_type = () -&gt; i32, sym_name = "f"}&gt; ({
      %0 = "spirv.Constant"() &lt;{value = 1 : i32}&gt; : () -&gt; i32
      %1 = "spirv.SpecConstantOperation"() ({
        %2 = "spirv.IAdd"(%0, %0) : (i32, i32) -&gt; i32
        "spirv.mlir.yield"(%2) : (i32) -&gt; ()
      }) : () -&gt; i32
      "spirv.ReturnValue"(%1) : (i32) -&gt; ()
    }) : () -&gt; ()
  }) : () -&gt; ()
}) : () -&gt; ()

Run canonicalization:

mlir-opt min.mlir --canonicalize

Expected Behavior

canonicalize should preserve valid IR. If the enclosed operation within spirv.SpecConstantOperation folds, either:

  • The entire spirv.SpecConstantOperation should fold as a unit (e.g., replaced by the resulting constant in the parent block), or
  • The rewrite should be rejected if spirv.SpecConstantOperation semantics prevent partial in-region folding.

In no case should it emit a partially stripped spirv.SpecConstantOperation that fails verification.

Actual Behavior

Verification fails immediately on the modified IR:

min.mlir:5:12: error: 'spirv.SpecConstantOperation' op expected exactly 2 nested ops
note: see current operation:
%1 = "spirv.SpecConstantOperation"() ({
  "spirv.mlir.yield"(%0) : (i32) -&gt; ()
}) : () -&gt; i32

Suggested Fix Direction

  1. Fold the whole operation: When the enclosed operation in spirv.SpecConstantOperation is constant-foldable, treat spirv.SpecConstantOperation as foldable as a unit, replacing the entire op with the folded result in the enclosing scope.
  2. Prevent partial inner folding/hoisting: Ensure that constants are not individually materialized inside SpecConstantOperation or hoisted out leaving an invalid empty shell. Merely preventing the hoist (e.g. via DialectFoldInterface) is insufficient on its own, because spirv.Constant is not legal inside SpecConstantOperation (UsableInSpecConstantOp requirement).

Tested Versions

  • LLVM main at commit ca566d552f7a9e507388cdba9539dd6e36c94bef
  • LLVM 24.0.0git (67005b724c917e1bdca50c82ecaa1b21a69244ed, macOS arm64)