Issue 83772
Summary Missed optimization: fold `is_power_of_2(A)` to `ctpop(A) == 1`
Labels new issue
Assignees
Reporter XChy
    Alive2 proof: https://alive2.llvm.org/ce/z/pEwoSR
Missed example: https://godbolt.org/z/Ex3e6P8c8

### Motivating example 

For simple C code from QEMU:
```c
bool is_power_of_2(uint64_t value)
{
    if (!value) {
        return false;
    }

 return !(value & (value - 1));
}
```
`clang -O3` produces suboptimal IR (also codegen):
```llvm
define i1 @is_power_of_2(i64 %value) {
entry:
  %tobool.not = icmp eq i64 %value, 0
  br i1 %tobool.not, label %return, label %if.end

if.end:
  %0 = call i64 @llvm.ctpop.i64(i64 %value)
  %tobool1.not = icmp ult i64 %0, 2
  br label %return

return:
  %retval.0 = phi i1 [ %tobool1.not, %if.end ], [ false, %entry ]
  ret i1 %retval.0
}
```
However, it's can be simpler:
```llvm
define i1 @tgt(i64 %value) {
entry:
  %0 = call i64 @llvm.ctpop.i64(i64 %value)
  %retval.0 = icmp eq i64 %0, 1
 ret i1 %retval.0
}
```

### For reference

### Real-world motivation

This snippet of IR is derived from [qemu/include/qemu/host-utils.h@is_power_of_2](https://github.com/qemu/qemu/blob/e1007b6bab5cf97705bf4f2aaec1f607787355b8/include/qemu/host-utils.h#L705) (after O3 pipeline).

**Let me know if you can confirm that it's an optimization opportunity, thanks.**
_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to