autoupdate
[gnulib.git] / lib / count-leading-zeros.h
index 4d7c291..204fa5a 100644 (file)
@@ -1,5 +1,5 @@
 /* count-leading-zeros.h -- counts the number of leading 0 bits in a word.
-   Copyright (C) 2012 Free Software Foundation, Inc.
+   Copyright (C) 2012-2013 Free Software Foundation, Inc.
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
 #include <stdlib.h>
 #include "verify.h"
 
+#ifndef _GL_INLINE_HEADER_BEGIN
+ #error "Please include config.h first."
+#endif
+_GL_INLINE_HEADER_BEGIN
+#ifndef COUNT_LEADING_ZEROS_INLINE
+# define COUNT_LEADING_ZEROS_INLINE _GL_INLINE
+#endif
+
 /* Expand the code which computes the number of leading zeros of the local
    variable 'x' of type TYPE (an unsigned integer type) and returns it
    from the current function.  */
-#if 0 && __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
+#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
 # define COUNT_LEADING_ZEROS(BUILTIN, TYPE)     \
   return x ? BUILTIN (x) : CHAR_BIT * sizeof x;
 #else
 
 /* Compute and return the number of leading zeros in the least
    significant 32 bits of X. */
-static inline int
+COUNT_LEADING_ZEROS_INLINE int
 count_leading_zeros_32 (unsigned int x)
 {
-  int count = 0;
-  if (x & 0xffff0000U)
-    x >>= 16;
-  else
-    count += 16;
-  if (x & 0xff00)
-    x >>= 8;
-  else
-    count += 8;
-  if (x & 0xf0)
-    x >>= 4;
-  else
-    count += 4;
-  if (x & 0xc)
-    x >>= 2;
-  else
-    count += 2;
-  if (x & 2)
-    x >>= 1;
-  else
-    count++;
-  if (!(x & 1))
-    count++;
-  return count;
+  /* http://graphics.stanford.edu/~seander/bithacks.html */
+  static const char deBruijnLookup[32] = {
+    0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
+    8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
+  };
+
+  x &= 0xffffffffU;
+  if (!x)
+    return 32;
+  x |= x >> 1;
+  x |= x >> 2;
+  x |= x >> 4;
+  x |= x >> 8;
+  x |= x >> 16;
+  return 31 - deBruijnLookup[(x * 0x07c4acddU) >> 27];
 }
 #endif
 
 /* Compute and return the number of leading zeros in X. */
-static inline int
+COUNT_LEADING_ZEROS_INLINE int
 count_leading_zeros (unsigned int x)
 {
   COUNT_LEADING_ZEROS (__builtin_clz, unsigned int);
 }
 
 /* Compute and return the number of leading zeros in X. */
-static inline int
+COUNT_LEADING_ZEROS_INLINE int
 count_leading_zeros_l (unsigned long int x)
 {
   COUNT_LEADING_ZEROS (__builtin_clzl, unsigned long int);
@@ -90,11 +89,13 @@ count_leading_zeros_l (unsigned long int x)
 
 #if HAVE_UNSIGNED_LONG_LONG_INT
 /* Compute and return the number of leading zeros in X. */
-static inline int
+COUNT_LEADING_ZEROS_INLINE int
 count_leading_zeros_ll (unsigned long long int x)
 {
   COUNT_LEADING_ZEROS (__builtin_clzll, unsigned long long int);
 }
 #endif
 
+_GL_INLINE_HEADER_END
+
 #endif /* COUNT_LEADING_ZEROS_H */