How to use __builtin_clzll in Rust?

Viewed 402

GCC has the __builtin_clzll builtin function that according to https://www.geeksforgeeks.org/builtin-functions-gcc-compiler/:

__builtin_clz(x): This function is used to count the leading zeros of the integer. Note : clz = count leading zero’s 

I think LLVM also has these functions, and Rust is compiled with LLVM. Is there a way to use this function in Rust?

1 Answers

Rust has the leading_zeros method on all built-in integer types. And if compiled on a CPU supporting an efficient hardware leading zeros instruction it will use that:

pub fn foo(n: u32) -> u32 {
    n.leading_zeros()
}

rustc -O -C target-cpu=broadwell:

example::foo:
  lzcnt eax, edi
  ret

rustc -O --target arm-unknown-linux-gnueabihf -C target-cpu=cortex-a76:

example::foo:
  clz r0, r0
  bx lr
Related