GCC documentation says this about the __builtin_ctz
family:
Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined.
Until now, I've been assuming that "undefined" here means "it can return any number, even non-deterministically" but it can't crash for example. In other words, it's not "undefined behavior" in the C++ sense. Comments on this question seem to confirm this.
However, both GCC and clang compile the following code
#include <bit>
#include <cstdint>
int clipped(std::uint64_t a) {
return __builtin_ctzll(a) & 0x7f;
}
to just
bsf rax, rdi
ret
This can return any value, even though the source code suggests that the return value should be between 0 and 127. I encountered this in actual code where I used the result of this function as lookup index, and got a segmentation fault.
Is this expected or a bug?
Compiler options used: -O3 -march=x86-64 --std=c++2a