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

[mlir][linalg] `convert-elementwise-to-linalg` miscompiles scalar `i1` `arith.select` on dynamically-shaped tensors

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

[mlir][linalg] convert-elementwise-to-linalg miscompiles scalar i1 arith.select on dynamically-shaped tensors

Summary

convert-elementwise-to-linalg incorrectly treats arith.select with a scalar i1 condition and tensor operands as an elementwise operation.

Per the MLIR Arith Dialect documentation for arith.select:

If an i1 is provided as the condition, the entire vector or tensor is chosen... and the un-chosen operand is ignored.

Thus, scalar i1 selection is a whole-value select, not an elementwise map.

However, convert-elementwise-to-linalg lowers this into a linalg.generic that reuses the first operand (%a) as its outs buffer and iterates over %a's runtime shape:

// Lowered linalg.generic:
%0 = linalg.generic {
  indexing_maps = [
    affine_map<(d0) -> ()>,   // %cond (scalar broadcast)
    affine_map<(d0) -> (d0)>, // %a
    affine_map<(d0) -> (d0)>, // %b
    affine_map<(d0) -> (d0)>  // outs: reuses %a!
  ],
  iterator_types = ["parallel"]
} ins(%cond, %a, %b : i1, tensor<?xi8>, tensor<?xi8>)
  outs(%a : tensor<?xi8>) {   // <-- Always iterates over %a and writes into %a!
^bb0(%c: i1, %va: i8, %vb: i8, %out: i8):
  %res = arith.select %c, %va, %vb : i8
  linalg.yield %res : i8
}

When %a and %b have different runtime extents (e.g., length(%a) = 1 and length(%b) = 2) and %cond == false:

  1. The loop executes only for 0..length(%a) (length 1 instead of length 2).
  2. It writes %b[0] into %a[0], mutating the un-chosen input buffer.
  3. It returns %a's descriptor (wrong size, truncated data).

(Note: MLIR's own bufferization for arith.select in BufferizableOpInterfaceImpl.cpp implements the correct whole-value semantics for scalar i1 conditions; the two passes currently conflict).

Minimal Reproducer

// repro.mlir
func.func @choose(%cond: i1, %a: tensor<?xi8>, %b: tensor<?xi8>) -> tensor<?xi8> {
  %r = arith.select %cond, %a, %b : tensor<?xi8>
  return %r : tensor<?xi8>
}

Run lowering:

mlir-opt repro.mlir --convert-elementwise-to-linalg

Actual Lowered IR

The pass converts the whole-value select into a linalg.generic iterating over %a:

func.func @choose(%arg0: i1, %arg1: tensor<?xi8>, %arg2: tensor<?xi8>) -> tensor<?xi8> {
  %0 = linalg.generic {
    indexing_maps = [affine_map<(d0) -> ()>, affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>],
    iterator_types = ["parallel"]
  } ins(%arg0, %arg1, %arg2 : i1, tensor<?xi8>, tensor<?xi8>)
    outs(%arg1 : tensor<?xi8>) {
  ^bb0(%in: i1, %in_0: i8, %in_1: i8, %out: i8):
    %1 = arith.select %in, %in_0, %in_1 : i8
    linalg.yield %1 : i8
  } -> tensor<?xi8>
  return %0 : tensor<?xi8>
}

Expected Behavior

When %arg0 is a scalar i1, the operation represents a whole-value select between %arg1 and %arg2.

  • It should not be converted to a linalg.generic iterating over %arg1.
  • When %arg0 == false, the returned tensor must retain %arg2's runtime size and contents, without mutating %arg1.

End-to-End Observation

When evaluated through full lowering with %a = [0x80] (size 1), %b = [0xff, 0xfe] (size 2), and %cond = false:

  • With convert-elementwise-to-linalg: Returns size 1, data [0xff], and mutates %a to 0xff.
  • Without convert-elementwise-to-linalg (relying directly on one-shot-bufferize): Returns size 2, data [0xff, 0xfe], leaving %a unchanged.

Suggested Fix Direction

  1. Exclude scalar condition selects from convert-elementwise-to-linalg: Check the condition operand type in ConvertAnyElementwiseMappableOpOnRankedTensors. If the op is arith.select and the condition is a scalar i1 (not a tensor of i1s), skip conversion and preserve it as a whole-value select.
  2. Allow downstream passes (such as scf.if or SelectOpInterface::bufferize) to handle the whole-value branch.

Tested Versions

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

lin334141-cell avatar Nov 02 '26 16:11 lin334141-cell

@llvm/issue-subscribers-mlir

Author: lin334141-cell

# [mlir] `convert-elementwise-to-linalg` miscompiles `arith.select` with an i1 condition and dynamically-shaped tensor operands of differing runtime extents

Versions

  • Reproduced (executed end-to-end, results below) on LLVM 24.0.0git at 67005b724c917e1bdca50c82ecaa1b21a69244ed (same-source rebuild, Release+assertions, macOS arm64) and on main at 61817b48e757f9a07f2a84e36326542052c12c22 (2026-10-29, local build). The responsible code is unchanged on today's main HEAD 040451d70105586ecbf77df1e5945e4d44b6f497 (2026-11-02, source-level check only — that exact build was not executed). We do not claim these are the newest available revisions.
  • Independently observed by an external differential-testing pipeline on Linux x86_64: a dynamic-tensor select program with 64 frozen input frames where two compiled arms agree (P-Q MATCH 64/64) but both differ from an independent reference on exactly the 48 frames whose (i1) condition is false.

Provenance note

This candidate comes from a development/regression program (D1302) of the SEMA project's dynamic-interface smoke test — not a fuzzer-generated original. The original program and its automatic variant form one root-cause cluster (both show the identical signature); the variant's exact bytes live in a sealed run root that is not archived, so only the original text is quoted.

Description

The arith.select description says that with an i1 condition "the entire vector or tensor is chosen" and that the un-chosen operand "is ignored, even if it was poison". Consistently, MLIR's own bufferization for arith.select (mlir/lib/Dialect/Arith/Transforms/BufferizableOpInterfaceImpl.cpp, SelectOpInterface::bufferize) implements exactly this whole-value mode for i1 conditions: it forwards one of the operand buffers (getAliasingValues: result Equivalent to both operands, isDefinite=false), and it explicitly rejects elementwise conditions ("Elementwise conditions are not supported yet. To bufferize such an op, it could be lowered to an elementwise linalg.generic…").

convert-elementwise-to-linalg (ConvertAnyElementwiseMappableOpOnRankedTensors in mlir/lib/Dialect/Linalg/Transforms/ElementwiseToLinalg.cpp) nevertheless rewrites the same op into an elementwise linalg.generic whose output is the first operand:

// verifier-accepted input (see reproducer): %cond is an i1 scalar
%r = arith.select %cond, %a, %b : tensor&lt;?xi8&gt;       // %a len La=1, %b len Lb=2 at runtime

// after convert-elementwise-to-linalg (both statically tensor&lt;?xi8&gt;):
linalg.generic {indexing_maps = [scalar, id, id, id], iterator_types = ["parallel"]}
  ins(%cond, %a, %b : i1, tensor&lt;?xi8&gt;, tensor&lt;?xi8&gt;) outs(%a : tensor&lt;?xi8&gt;) {
    ^bb0(%c: i1, %x: i8, %y: i8):
      %s = arith.select %c, %x, %y : i8
      linalg.yield %s : i8
}
func.return %a

getOrCreateOperandsMatchingResultTypes reuses the first operand as the output, justified by "ElementwiseMappable guarantees that the static types of all tensor operands and results must have the same shape". That holds statically, but it ignores the i1 whole-value mode, in which the result must be the chosen operand with the chosen operand's runtime shape and the un-chosen operand must be left alone.

After one-shot-bufferize + convert-linalg-to-loops the executable becomes a loop for i in 0..size(%a): a[i] = select(cond, a[i], b[i]) returning %a's descriptor. When the two operands have different runtime extents this silently returns a wrong length and wrong trailing content, and it writes into %a's buffer — an observed bufferization side effect on an input the source never writes (we report it as a side effect of this lowering; we do not claim it is a separate second defect).

Note the two official components disagree about the semantics of the same operation: the bufferization interface implements the i1 whole-value mode, while this conversion reinterprets it elementwise.

Primary executed witness (La=1, Lb=2, cond=false)

Input (fresh, independent buffers; %a = [0x80] (1 byte), %b = [0xff, 0xfe] (2 bytes), condition = false):

  • Correct per the i1 whole-value semantics: result aliases/selects %b: size = 2, data [ff, fe], %a's buffer untouched (80).
  • Observed with convert-elementwise-to-linalg in the pipeline (executed): returned descriptor aliases %a (alloc-differs=0), size = 1, data [ff], and %a's buffer after the call reads ff (mutated from 80).
  • Same driver, same pipeline with only convert-elementwise-to-linalg removed (executed): returned descriptor aliases %b (alloc-differs=1), size = 2, data [ff, fe], %a's buffer reads 80 — correct.

Minimal reproducer (7 lines, min.mlir; condition is input-dependent so it cannot be folded)

module{func.func @<!-- -->choose(%a:tensor&lt;?xi8&gt;,%b:tensor&lt;?xi8&gt;,%seed:i16)-&gt;tensor&lt;?xi8&gt;{
%wide=arith.extsi %seed:i16 to i32
%mask=arith.constant 1:i32
%key=arith.xori %wide,%mask:i32
%zero=arith.constant 0:i32
%cond=arith.cmpi slt,%key,%zero:i32
%r=arith.select %cond,%a,%b:tensor&lt;?xi8&gt;
func.return %r:tensor&lt;?xi8&gt;
}}

Commands (verified as shown; driver included)

# 1) buggy lowering (with convert-elementwise-to-linalg):
mlir-opt min.mlir --mlir-disable-threading --verify-each \
  '--pass-pipeline=builtin.module(canonicalize,convert-elementwise-to-linalg,one-shot-bufferize{bufferize-function-boundaries function-boundary-type-conversion=identity-layout-map},convert-linalg-to-loops,convert-func-to-llvm,reconcile-unrealized-casts)' \
  -o buggy.mlir
# 2) reference lowering (same pipeline without convert-elementwise-to-linalg):
mlir-opt min.mlir --mlir-disable-threading --verify-each \
  '--pass-pipeline=builtin.module(canonicalize,one-shot-bufferize{bufferize-function-boundaries function-boundary-type-conversion=identity-layout-map},convert-linalg-to-loops,convert-func-to-llvm,reconcile-unrealized-casts)' \
  -o ref.mlir
mlir-translate --mlir-to-llvmir ref.mlir -o ref.ll

ref.ll contains the correct whole-value selection at the descriptor level:

%17 = llvm.select %16, %11, %5 : i1, !llvm.struct&lt;(ptr, ptr, i64, [1 x i64], [1 x i64])&gt;

Execution driver (driver.ll, linked with llvm-link ref.ll driver.ll, llc -O2, then a C launcher; full source in the repository copy):

declare { ptr, ptr, i64, [1 x i64], [1 x i64] } @<!-- -->choose(ptr, ptr, i64, i64, i64, ptr, ptr, i64, i64, i64, i16)
@<!-- -->abuf = global [1 x i8] [i8 -128]   ; %a = [0x80]
@<!-- -->bbuf = global [2 x i8] [i8 -1, i8 -2] ; %b = [0xff, 0xfe]
define i32 @<!-- -->main() {
  %r = call { ptr, ptr, i64, [1 x i64], [1 x i64] } @<!-- -->choose(
      ptr @<!-- -->abuf, ptr @<!-- -->abuf, i64 0, i64 1, i64 1,
      ptr @<!-- -->bbuf, ptr @<!-- -->bbuf, i64 0, i64 2, i64 1, i16 3)
  ; print returned alloc/align/off/size/stride and data bytes
  ...
}

(With the buggy lowering the printed result is alloc == @<!-- -->abuf, size = 1, data = [ff] and @<!-- -->abuf reads ff afterwards; with the reference lowering it is alloc == @<!-- -->bbuf, size = 2, data = [ff fe] and @<!-- -->abuf reads 80.)

Expected behavior

With an i1 condition the operation chooses one operand in its entirety: the result carries the chosen operand's runtime shape and values, and the un-chosen operand is not written.

Actual behavior

With convert-elementwise-to-linalg in the pipeline the compiled program returns the first operand's buffer and runtime extent; for a false condition the data is the second operand's head elements followed by the first operand's stale bytes, and the first operand's buffer is modified as a side effect.

Semantic-boundary statement

The ODS text contains both an elementwise clause ("applies … elementwise given the shape of all operands is identical") and the i1 whole-value clause. For dynamically-shaped operands whose runtime extents differ, the two clauses can be read differently; passing the verifier does not by itself prove definedness for every dynamic input. Our reading (whole-value mode for i1 conditions) is supported by the ODS sentence, by SelectLikeOpInterface, and by MLIR's own bufferization implementing exactly that mode; but if maintainers instead consider mismatched runtime extents outside the defined domain for this op, we accept that reclassification — in either case the two official components (bufferization vs this conversion) currently implement conflicting semantics for the same operation.

Upstream dedup (checked 2026-11-03)

We could not find an existing report covering this specific failure mechanism. Searches over elementwise-to-linalg select, select whole tensor i1 condition, one-shot-bufferize select dynamic, arith.select dynamic shape linalg, and related phrasings found no match; #228854 (assert in linalg-specialize-generic-ops on select with a captured scalar) is a different pass and failure mode. None of #237680, #237682, #236562, #236561, #234637, #228850 covers this.

Suggested fix directions

(a) In ConvertAnyElementwiseMappableOpOnRankedTensors, special-case scalar-condition arith.select: lower via scf.if/select-of-descriptors (matching the bufferization interface's whole-value mode) instead of an elementwise generic with an operand as outs; or (b) only reuse an operand as outs when operand/result runtime-shape equality is guaranteed; or (c) exclude arith.select from this conversion until its i1 mode is representable. Happy to test a patch.

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