| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
#pragma once |
| 3 |
|
| 4 |
#include <stdint.h> |
| 5 |
|
| 6 |
/* Note: log2(0) == log2(1) == 0 here and below. */ |
| 7 |
|
| 8 |
#define CONST_LOG2ULL(x) ((x) > 1 ? (unsigned) __builtin_clzll(x) ^ 63U : 0) |
| 9 |
#define NONCONST_LOG2ULL(x) ({ \ |
| 10 |
unsigned long long _x = (x); \ |
| 11 |
_x > 1 ? (unsigned) __builtin_clzll(_x) ^ 63U : 0; \ |
| 12 |
}) |
| 13 |
#define LOG2ULL(x) __builtin_choose_expr(__builtin_constant_p(x), CONST_LOG2ULL(x), NONCONST_LOG2ULL(x)) |
| 14 |
|
| 15 |
static inline unsigned log2u64(uint64_t x) { |
| 16 |
#if __SIZEOF_LONG_LONG__ == 8 |
| 17 |
return LOG2ULL(x); |
| 18 |
#else |
| 19 |
# error "Wut?" |
| 20 |
#endif |
| 21 |
} |
| 22 |
|
| 23 |
static inline unsigned u32ctz(uint32_t n) { |
| 24 |
#if __SIZEOF_INT__ == 4 |
| 25 |
return n != 0 ? __builtin_ctz(n) : 32; |
| 26 |
#else |
| 27 |
# error "Wut?" |
| 28 |
#endif |
| 29 |
} |
| 30 |
|
| 31 |
#define popcount(n) \ |
| 32 |
_Generic((n), \ |
| 33 |
unsigned char: __builtin_popcount(n), \ |
| 34 |
unsigned short: __builtin_popcount(n), \ |
| 35 |
unsigned: __builtin_popcount(n), \ |
| 36 |
unsigned long: __builtin_popcountl(n), \ |
| 37 |
unsigned long long: __builtin_popcountll(n)) |
| 38 |
|
| 39 |
#define CONST_LOG2U(x) ((x) > 1 ? __SIZEOF_INT__ * 8 - __builtin_clz(x) - 1 : 0) |
| 40 |
#define NONCONST_LOG2U(x) ({ \ |
| 41 |
unsigned _x = (x); \ |
| 42 |
_x > 1 ? __SIZEOF_INT__ * 8 - __builtin_clz(_x) - 1 : 0; \ |
| 43 |
}) |
| 44 |
#define LOG2U(x) __builtin_choose_expr(__builtin_constant_p(x), CONST_LOG2U(x), NONCONST_LOG2U(x)) |
| 45 |
|
| 46 |
static inline unsigned log2i(int x) { |
| 47 |
return LOG2U(x); |
| 48 |
} |
| 49 |
|
| 50 |
static inline unsigned log2u(unsigned x) { |
| 51 |
return LOG2U(x); |
| 52 |
} |
| 53 |
|
| 54 |
static inline unsigned log2u_round_up(unsigned x) { |
| 55 |
if (x <= 1) |
| 56 |
return 0; |
| 57 |
|
| 58 |
return log2u(x - 1) + 1; |
| 59 |
} |