Issue 238834
Summary [mlir][SPIR-V] `convert-spirv-to-llvm` miscompiles `spirv.BitFieldInsert`: the `insert` operand is never masked to `count` bits (and `count = 0` returns the wrong value)
Labels
Assignees
Reporter lin334141-cell
    # [mlir][SPIR-V] `convert-spirv-to-llvm` miscompiles `spirv.BitFieldInsert`: the `insert` operand is never masked to `count` bits (and `count = 0` returns the wrong value)

## Versions

- Reproduced (**executed end-to-end**, outputs 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). Both produce identical wrong results.
- Source-level check: `BitFieldInsertPattern` in `mlir/lib/Conversion/SPIRVToLLVM/SPIRVToLLVM.cpp` is **byte-identical** between `67005b72` (lines 395–436) and today's `main` (lines 397–440). The wrong lowering is still present at the checked `main` snapshot; that snapshot was not built or executed, and no newer revision was checked.
- Upstream dedup (checked 2026-11-04): #237680 (SpecConstantOperation canonicalization) is unrelated; targeted searches found no existing report for this defect.

## Description

`BitFieldInsertPattern::matchAndRewrite` lowers

```mlir
%r = "spirv.BitFieldInsert"(%base, %insert, %offset, %count)
```

to (result type width `W`, mask `= (~(-1 << count)) << offset`):

```llvm
%mask       = xor (shl iW -1, %count), -1     ; (1 << count) - 1
%clearmask  = xor (shl %mask, %offset), -1     ; ~((1<<count)-1) << offset
%base_kept  = and %base, %clearmask
%insert_up  = shl %insert, %offset            ; ← never masked to `count` bits
%r          = or %base_kept, %insert_up
```

The `insert` operand is **not** masked to `count` bits before the shift (`and(shl(insert, offset), mask << offset)` is required). Per the SPIR-V spec, `OpBitFieldInsert` "replaces bits [Offset, Offset + Count - 1 : 0] of Base with the low Count bits of Insert" — all bits of `Insert` at `>= Count` must be discarded. Any `insert` with high bits set produces a wrong result whenever those bits survive the shift.

The same missing mask breaks the `count = 0` case: the spec says `OpBitFieldInsert` with `Count = 0` returns `Base` unchanged, but the emitted code computes `base | (insert << offset)` instead.

(First-error location: `mlir/lib/Conversion/SPIRVToLLVM/SPIRVToLLVM.cpp` at the checked revisions — `BitFieldInsertPattern::matchAndRewrite`, the `insertShiftedByOffset` / final `OrOp` emission; 67005b72 lines 431–435, main lines 433–437. Note the "MLIR SPIR-V to LLVM conversion manual" pseudo-code shows the same unmasked form and cannot serve as the normative reference; the SPIR-V specification is the semantic authority.)

## Minimal reproducer (`min.mlir`, 3 lines)

```mlir
module{func.func @ins(%base:i32,%ins:i32,%off:i32,%cnt:i32)->i32{
%r="spirv.BitFieldInsert"(%base,%ins,%off,%cnt):(i32,i32,i32,i32)->i32
func.return %r:i32
}}
```

## Commands (verified as shown, clean directory)

```bash
mlir-opt min.mlir --mlir-disable-threading \
  '--pass-pipeline=builtin.module(convert-spirv-to-llvm,convert-arith-to-llvm,convert-func-to-llvm,reconcile-unrealized-casts)' \
  -o lowered.mlir
mlir-translate --mlir-to-llvmir lowered.mlir -o min.ll
llvm-as driver.ll -o driver.bc
llvm-link min.ll driver.bc -o p.bc
llc -O2 -filetype=obj p.bc -o p.o
clang p.o -o run && ./run
```

Driver (`driver.ll`):

```llvm
target triple = "arm64-apple-macos"
@pf = private unnamed_addr constant [12 x i8] c"ins: %d %d\0A\00"
declare i32 @printf(ptr, ...)
declare i32 @ins(i32, i32, i32, i32)
define i32 @main() {
entry:
  %a = call i32 @ins(i32 3, i32 -1, i32 0, i32 3)
  %b = call i32 @ins(i32 5, i32 9, i32 2, i32 0)
  call i32 (ptr, ...) @printf(ptr @pf, i32 %a, i32 %b)
  ret i32 0
}
```

Call 1 is the insert witness (`base=3, insert=0xFFFFFFFF, offset=0, count=3`); call 2 is the `count = 0` witness (`base=5, insert=9, offset=2, count=0`). Both inputs are in the SPIR-V-defined domain (`offset + count <= 32`; `count = 0` is explicitly defined by the spec).

## Expected behavior (SPIR-V 1.x spec)

- Call 1: bits `[0, 3)` of `3` replaced by the low 3 bits of `0xFFFFFFFF` → `0b111` = **7**.
- Call 2: `count = 0` → result is `Base` = **5**.

```
ins: 7 5
```

## Actual behavior (executed on both revisions)

```
ins: -1 37
```

- Call 1 returned `-1` (`0xFFFFFFFF`): the unmasked `insert` was OR-ed in wholesale.
- Call 2 returned `37` (`5 | (9 << 2)` = `0b100101`): `insert << offset` was OR-ed into `Base` despite `count = 0`.

## A second, separate boundary mechanism in the same rule (mask construction)

The missing insert mask above is not the only defect in this pattern. With `offset = 0, count = W` (spec: result = `insert` unchanged), the **mask construction itself** — `shl iW -1, %count` with `%count = W` — is a bit-width shift (LLVM poison). This is a different mechanism from the dropped insert mask: even a correctly masked `insert` would still flow through the poison mask here. Witness: `BitFieldInsert(0xAAAAAAAA, 0x12345678, 0, 32)` executed as `0xaaaaaaaa` on both revisions (spec: `0x12345678`); the same `shl -1, %count` construction also poisons every input at `count = W`. This mask-construction mechanism is tracked in a separate sibling issue (cross-reference number to be added) because its fix site is the mask emission rather than the insert masking, and it also affects the `spirv.BitFieldUExtract` conversion path. A complete fix must therefore handle, at minimum:

1. `0 < count < W`: mask `insert` to `count` bits (`and` after the shift, or before it);
2. `count = 0`: return `base` (spec-defined);
3. `count = W`: return `insert` (spec-defined), and ensure the mask construction itself performs no bit-width shift for this input;
4. all other legal boundaries (`offset = W` with `count = 0`, i.e. the empty range at the end of the field).

The correction sketched in "Suggested fix direction" below was **verified only for the general `0 < count < W` path and the executed witnesses above**; items 2–4 require the selects/guards described, and we have not tested a patch beyond the witnesses shown.

## Broader evidence (not required for reproduction)

An 81-frame replay of a four-width (i8/i16/i32/i64) bitfield program against an independent SPIR-V-spec reference produced a 36-frame difference set; every wrong `insert` output slot (32 of the 36 frames' wrong values, spanning all four widths and `count = 0` frames) is explained by this missing mask.

## Suggested fix direction

```text
%ins_masked = and %insert, (1 << count) - 1      ; with count=0/count=W shifts guarded
%r = (base & ~((1 << count) - 1) << offset) | (%ins_masked << offset)
```

plus explicit handling of `count = 0` (return `base`) and `count = W` (return `insert`), e.g. via selects, so no shift amount ever reaches the bit width. Happy to test a patch.

_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to