Issue 239566
Summary Missing fold of min/max in a select where the condition makes it redundant
Labels missed-optimization
Assignees
Reporter kubamracek
    Reproducer:
```c
// Branch-lesss bit-stream reader refill:
// - when avail < 0, shift the next input word w into place.
uint64_t refill(uint64_t bits, uint32_t w, const int *availp) {
    int avail = *availp;               // only to avoid having noundef
    int need = avail < 0 ? -avail : 0; // -min(avail, 0)
 uint64_t add = avail < 0
        ? (uint64_t)w << need          // avail < 0, need == -avail => the min is no-op
        : 0;
    return bits | add;
}
```

Godbolt: https://godbolt.org/z/x5E9zo6aM (also GCC for comparison, which does handle this

We currently can't eliminate the llvm.smin(), even though the condition on that side of the select is implying that it's a no-op:

```llvm
define dso_local i64 @refill(i64 noundef %0, i32 noundef %1, ptr nofree noundef readonly captures(none) %2) local_unnamed_addr #0 {
  %4 = load i32, ptr %2, align 4
  %5 = icmp slt i32 %4, 0
  %6 = tail call i32 @llvm.smin.i32(i32 %4, i32 0)
  %7 = sub nsw i32 0, %6
  %8 = zext i32 %1 to i64
  %9 = zext nneg i32 %7 to i64
  %10 = shl i64 %8, %9
  %11 = select i1 %5, i64 %10, i64 0
  %12 = or i64 %11, %0
  ret i64 %12
}
```

```asm
refill:
        ldr     w8, [x2]
 mov     w10, w1
        neg     w9, w8
        cmp     w8, #0
 and     w9, w9, w8, asr #31
        lsl     x9, x10, x9
        csel    x8, x9, xzr, mi
        orr     x0, x8, x0
        ret
```

The expected optimization should remove the llvm.smin() instruction in IR, and in resulting assembly, it should remove the AND ..., ASR #31.
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to