https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101950
Bug ID: 101950
Summary: __builtin_clrsb is never inlined
Product: gcc
Version: 11.1.0
Status: UNCONFIRMED
Severity: normal
Priority: P3
Component: c
Assignee: unassigned at gcc dot gnu.org
Reporter: sven.koehler at gmail dot com
Target Milestone: ---
With gcc 11.1 on ARM 32-bit and Intel, I don't see that __builtin_clrsb is
inlined. On AARCH64 it is inlined and the cls instruction is used, as expected.
I use the C-code below to compare the assembly generated. For ARM, I use -O3
-mcpu=cortex-a53 -marm and for Intel I just use -O3.
On ARM 32-bit, clrsb1 seems to be the fastest code (see below for the assembly
code) since clz handles zero correctly. On Intel, bsr does not handle zero,
hence the workaround of setting the lsb before calling __builtin_clzl (see
below for the assembly code). On Intel, clrsb1 is slighly longer and uses a
jump to handle the zero case. clang apparently uses variant clrsb1 on ARM and
Intel, and it's inlined on both architectures when using -O3.
#define SHIFT (sizeof(x)*8-1)
int clz(unsigned long x) {
if (x == 0) {
return sizeof(x)*8;
}
return __builtin_clzl(x);
}
int clsb(long x) {
return clz(x ^ (x >> SHIFT));
}
int clrsb1(long x) {
return clsb(x)-1;
}
int clrsb2(long x) {
x = ((x << 1) ^ (x >> SHIFT)) | 1;
return __builtin_clzl(x);
}
int clrsb3(long x) {
return __builtin_clrsbl(x);
}
on ARM 32-bit:
clrsb1:
eor x0, x0, x0, asr 63
clz x0, x0
sub w0, w0, #1
ret
on Intel:
clrsb2:
lea rax, [rdi+rdi]
sar rdi, 63
xor rax, rdi
or rax, 1
bsr rax, rax
xor eax, 63
ret