[llvm] b157193 - [ADT] Handle uint8_t and uint16_t in countr_zero (#158518)

via llvm-commits llvm-commits at lists.llvm.org
Sun Sep 14 20:31:52 PDT 2025


Author: Kazu Hirata
Date: 2025-09-14T20:31:47-07:00
New Revision: b15719365861502cd1c6d216ad4a0425ee6431ea

URL: https://github.com/llvm/llvm-project/commit/b15719365861502cd1c6d216ad4a0425ee6431ea
DIFF: https://github.com/llvm/llvm-project/commit/b15719365861502cd1c6d216ad4a0425ee6431ea.diff

LOG: [ADT] Handle uint8_t and uint16_t in countr_zero (#158518)

Without this patch, the uint8_t and uint16_t cases are sent to the
fallback route.  This patch fixes that by relaxing the "if" condition.

While it's hard to test that the correct control path is taken within
countr_zero, this patch adds a few tests just to verify the
correctness on uint8_t and uint16_t inputs.

Added: 
    

Modified: 
    llvm/include/llvm/ADT/bit.h
    llvm/unittests/ADT/BitTest.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm/ADT/bit.h b/llvm/include/llvm/ADT/bit.h
index d6e33c3e6133a..2ca9b43519740 100644
--- a/llvm/include/llvm/ADT/bit.h
+++ b/llvm/include/llvm/ADT/bit.h
@@ -161,7 +161,7 @@ template <typename T> [[nodiscard]] int countr_zero(T Val) {
     return std::numeric_limits<T>::digits;
 
   // Use the intrinsic if available.
-  if constexpr (sizeof(T) == 4) {
+  if constexpr (sizeof(T) <= 4) {
 #if __has_builtin(__builtin_ctz) || defined(__GNUC__)
     return __builtin_ctz(Val);
 #elif defined(_MSC_VER)

diff  --git a/llvm/unittests/ADT/BitTest.cpp b/llvm/unittests/ADT/BitTest.cpp
index 2377ce3b78261..88ae36c44bdb9 100644
--- a/llvm/unittests/ADT/BitTest.cpp
+++ b/llvm/unittests/ADT/BitTest.cpp
@@ -297,6 +297,14 @@ TEST(BitTest, CountrZero) {
   EXPECT_EQ(1, llvm::countr_zero(NZ16));
   EXPECT_EQ(1, llvm::countr_zero(NZ32));
   EXPECT_EQ(1, llvm::countr_zero(NZ64));
+
+  EXPECT_EQ(0, llvm::countr_zero(uint8_t(1)));
+  EXPECT_EQ(3, llvm::countr_zero(uint8_t(8)));
+  EXPECT_EQ(7, llvm::countr_zero(uint8_t(128)));
+
+  EXPECT_EQ(0, llvm::countr_zero(uint16_t(1)));
+  EXPECT_EQ(8, llvm::countr_zero(uint16_t(256)));
+  EXPECT_EQ(15, llvm::countr_zero(uint16_t(32768)));
 }
 
 TEST(BitTest, CountlOne) {


        


More information about the llvm-commits mailing list