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

[X86] Failure to fold bit count instructions if EFLAGS is used

Open RKSimon opened this issue 1 year ago • 5 comments

https://zig.godbolt.org/z/v6x91zxed

define i64 @lzcnt64(ptr %p0) {
  %a0 = load i64, ptr %p0, align 8
  %cnt = tail call range(i64 0, 65) i64 @llvm.ctlz.i64(i64 %a0, i1 true)
  ret i64 %cnt
}
define i64 @lzcnt64_64(ptr %p0, i64 %a1) {
  %a0 = load i64, ptr %p0, align 8
  %cnt = tail call range(i64 0, 65) i64 @llvm.ctlz.i64(i64 %a0, i1 true)
  %iszero = icmp eq i64 %a0, 0
  %res = select i1 %iszero, i64 %a1, i64 %cnt
  ret i64 %res
}
lzcnt64: # @lzcnt64
  lzcntq (%rdi), %rax
  retq
lzcnt64_64: # @lzcnt64_64
  movq (%rdi), %rax
  lzcntq %rax, %rax
  cmovbq %rsi, %rax
  retq

but should be:

lzcnt64_64: # @lzcnt64_64
  lzcntq (%rdi), %rax
  cmovbq %rsi, %rax
  retq

RKSimon avatar Oct 23 '25 09:10 RKSimon

@llvm/issue-subscribers-backend-x86

Author: Simon Pilgrim (RKSimon)

https://zig.godbolt.org/z/v6x91zxed ```ll define i64 @lzcnt64(ptr %p0) { %a0 = load i64, ptr %p0, align 8 %cnt = tail call range(i64 0, 65) i64 @llvm.ctlz.i64(i64 %a0, i1 true) ret i64 %cnt } define i64 @lzcnt64_64(ptr %p0, i64 %a1) { %a0 = load i64, ptr %p0, align 8 %cnt = tail call range(i64 0, 65) i64 @llvm.ctlz.i64(i64 %a0, i1 true) %iszero = icmp eq i64 %a0, 0 %res = select i1 %iszero, i64 %a1, i64 %cnt ret i64 %res } ``` ```asm lzcnt64: # @lzcnt64 lzcntq (%rdi), %rax retq lzcnt64_64: # @lzcnt64_64 movq (%rdi), %rax lzcntq %rax, %rax cmovbq %rsi, %rax retq ``` but should be: ```asm lzcnt64_64: # @lzcnt64_64 lzcntq (%rdi), %rax cmovbq %rsi, %rax retq ```

llvmbot avatar Oct 23 '25 09:10 llvmbot

Can I give it a try?

Michael-Chen-NJU avatar Apr 28 '26 03:04 Michael-Chen-NJU

Sure - maybe consult with @Takashiidobe who was looking at something related with #186932

RKSimon avatar Apr 28 '26 07:04 RKSimon

I didn't get too far in my investigation for this. topperc pointed out:

... The optimization that knows how to use the C flag from LZCNT is in the Peephole optimizer that runs before the MachineScheduler.

So I would take a look there. Hopefully you get further than me on this.

Takashiidobe avatar Apr 28 '26 12:04 Takashiidobe

Can this be another freeze blocking the combination?

chfast avatar Apr 28 '26 12:04 chfast