Issue 233901
Summary [InstCombine][X86] Narrow comparison fails to reuse an already needed mask
Labels new issue
Assignees
Reporter adamant-pwn
    These functions have the same behavior, but the 32-bit comparison generates extra instructions:

```cpp
#include <cstdint>

bool narrow(uint64_t index, uint64_t &offset) {
    uint32_t local = index % 64;
    offset = local;
    return local < 62;
}

bool wide(uint64_t index, uint64_t &offset) {
    uint32_t local = index % 64;
 offset = local;
    return uint64_t(local) < 62;
}
```

Reproduced with Clang 23.1.3, Linux distribution package `clang 23.1.3-2`:

```sh
clang++ -std=c++20 -O2 -march=haswell -S repro.cpp
```

`narrow` computes a separate predicate from the original input:

```asm
movl  %edi, %eax
notl  %eax
andl  $63, %edi
movq  %rdi, (%rsi)
testb $62, %al
setne %al
retq
```

`wide` reuses the masked value:

```asm
andl $63, %edi
movq %rdi, (%rsi)
cmpq $62, %rdi
setb %al
retq
```

`narrowBinOp` first turns `trunc(and i64 %index, 63)` into `and i32 (trunc %index), 63`. The `zext` for the store recreates the wide mask; demanded-bits simplification then changes the comparison's separate mask to 62.

Can we preserve the shared mask when profitable? A guard retaining the wide `and` for comparison/`zext` users fixes this example and passed 2,560 applicable InstCombine/vectorizer tests on LLVM 20.1.2. However, broader client timings had both gains and regressions, so that guard needs a profitability decision. [Alive2 check of the mask-reuse equivalence](https://alive2.llvm.org/ce/z/NEZA6j).

Assisted by Codex and Claude.

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

Reply via email to