Issue 148041
Summary Pessimising rewrite in `contains_zero_byte`
Labels llvm:instcombine, missed-optimization
Assignees
Reporter Kmeakin
    Consider the following Rust code for determining if any of the 8 bytes in a u64 are zero, taken from [the Rust standard library's implementation of `memchr`](https://github.com/rust-lang/rust/blob/master/library/core/src/slice/memchr.rs):
```rust
const LO: u64 = 0x01_01_01_01_01_01_01_01;
const HI: u64 = 0x80_80_80_80_80_80_80_80;

const fn contains_zero_byte(x: u64) -> bool {
 x.wrapping_sub(LO_USIZE) & !x & HI_USIZE != 0
}
```

The equivalent C++ code is:
https://godbolt.org/z/Ej8TT8v84
```c++
constexpr u64 LO = 0x01'01'01'01'01'01'01'01;
constexpr u64 HI = 0x80'80'80'80'80'80'80'80;

bool contains_zero_byte(u64 x) { 
    return ((x - LO) & ~x & HI) != 0;
}
```

For this function, GCC generates
```asm
;; AArch64:
contains_zero(unsigned long):
        mov x1, -72340172838076674
        movk    x1, 0xfeff, lsl 0
        add x1, x0, x1
        bic     x1, x1, x0
        tst     x1, -9187201950435737472
        cset    w0, ne
        ret

;; x86_64:
contains_zero_byte(unsigned long):
        movabs  rax, -72340172838076673
        add     rax, rdi
        andn    rdi, rdi, rax
 movabs  rax, -9187201950435737472
        test    rdi, rax
 setne   al
        ret
```

but LLVM generates:
```asm
;; AArch64:
contains_zero_byte(unsigned long):
        mov     x8, #72340172838076673
        mov     x9, #-9187201950435737472
        movk x8, #256
        sub     x8, x8, x0
        orr     x8, x8, x0
 bics    xzr, x9, x8
        cset    w0, ne
        ret

;; x86_64:
contains_zero_byte(unsigned long):
        movabs  rax, 72340172838076672
        sub     rax, rdi
        or      rax, rdi
 movabs  rcx, -9187201950435737472
        andn    rax, rax, rcx
 setne   al
        ret
```
_______________________________________________
llvm-bugs mailing list
llvm-bugs@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to