How do I count leading zeros on both mac M1 and x86-64?

  apple-m1, armv8, c++, x86-64

Originally I tried lzcnt but that doesn’t seem to work on a mac. I’m working with someone who is using the apple M1 CPU which is ARM64v8.4

In this arm document which list ARM 8 it appears clz supports using 0

CLZ Xd, Xm
Count Leading Zeros (64-bit): sets Xd to the number of binary zeros at the most significant end of Xm. The result will be in the range 0 to 64 inclusive.

The CPU we originally support is x86-64 which has _lzcnt_u64

Both instructions appear to return 64 if the value is 0. Specifically "0 to 64 inclusive" on ARM and the intel site suggest it too (and confirmed by my code) https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=lzcnt&ig_expand=4425

However GCC says the below

Built-in Function: int __builtin_clzll (unsigned long long)

Similar to __builtin_clz, except the argument type is unsigned long long.

Can I safely use 0 or does this builtin use a different instruction? I tried on clang and the sanitizer stop the program and told me it is a problem which was surprising to me.

How should I get the leading zero count when I want to get 64 if I pass in 0 like these two instructions do

Source: Windows Questions C++

LEAVE A COMMENT