Merge pull request #14698 from benpicco/core/bitarithm-msb_clz

core/bitarithm: use __builtin_clz() for bitarithm_msb()
This commit is contained in:
Koen Zandberg 2020-08-06 13:00:34 +02:00 committed by GitHub
commit 5dbcfa3391
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 11 deletions

View File

@ -23,11 +23,9 @@
#include "bitarithm.h" #include "bitarithm.h"
unsigned bitarithm_msb(unsigned v) unsigned bitarith_msb_32bit_no_native_clz(unsigned v)
{ {
register unsigned r; /* result of log2(v) will go here */ register unsigned r; /* result of log2(v) will go here */
#if ARCH_32_BIT
register unsigned shift; register unsigned shift;
/* begin{code-style-ignore} */ /* begin{code-style-ignore} */
@ -37,13 +35,6 @@ unsigned bitarithm_msb(unsigned v)
shift = (v > 0x3 ) << 1; v >>= shift; r |= shift; shift = (v > 0x3 ) << 1; v >>= shift; r |= shift;
r |= (v >> 1); r |= (v >> 1);
/* end{code-style-ignore} */ /* end{code-style-ignore} */
#else
r = 0;
while (v >>= 1) { /* unroll for more speed... */
r++;
}
#endif
return r; return r;
} }

View File

@ -102,7 +102,7 @@ extern "C" {
* *
* Source: http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious * Source: http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious
*/ */
unsigned bitarithm_msb(unsigned v); static inline unsigned bitarithm_msb(unsigned v);
/** /**
* @brief Returns the number of the lowest '1' bit in a value * @brief Returns the number of the lowest '1' bit in a value
@ -136,8 +136,33 @@ static inline uint8_t bitarithm_bits_set_u32(uint32_t v)
uint8_t bitarithm_bits_set_u32(uint32_t v); uint8_t bitarithm_bits_set_u32(uint32_t v);
#endif #endif
/**
* @brief Returns the number of the highest '1' bit in a value
*
* Internal software implementation for 32 bit platforms,
* use @see bitarithm_msb in application code.
* @param[in] v Input value
* @return Bit Number
*/
unsigned bitarith_msb_32bit_no_native_clz(unsigned v);
/* implementations */ /* implementations */
static inline unsigned bitarithm_msb(unsigned v)
{
#if defined(BITARITHM_HAS_CLZ)
return 8 * sizeof(v) - __builtin_clz(v) - 1;
#elif ARCH_32_BIT
return bitarith_msb_32bit_no_native_clz(v);
#else
unsigned r = 0;
while (v >>= 1) { /* unroll for more speed... */
++r;
}
return r;
#endif
}
static inline unsigned bitarithm_lsb(unsigned v) static inline unsigned bitarithm_lsb(unsigned v)
#if defined(BITARITHM_LSB_BUILTIN) #if defined(BITARITHM_LSB_BUILTIN)
{ {