1 year ago

#67986

test-img

user1020406

Is __builtin_ctzll(0) "undefined behavior" or just "undefined"?

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

gcc

x86

clang

undefined-behavior

compiler-bug

0 Answers

Your Answer

Accepted video resources