2 * Copyright (c) 2017, 2019 ARM Limited
5 * The license below extends only to copyright in the software and shall
6 * not be construed as granting a license to any other intellectual
7 * property including but not limited to intellectual property relating
8 * to a hardware implementation of the functionality of the software
9 * licensed hereunder. You may use the software subject to the license
10 * terms below provided that you ensure that this notice is replicated
11 * unmodified and in its entirety in all distributions of the software,
12 * modified or unmodified, in source code or in binary form.
14 * Copyright (c) 2003-2005 The Regents of The University of Michigan
15 * All rights reserved.
17 * Redistribution and use in source and binary forms, with or without
18 * modification, are permitted provided that the following conditions are
19 * met: redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer;
21 * redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution;
24 * neither the name of the copyright holders nor the names of its
25 * contributors may be used to endorse or promote products derived from
26 * this software without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
41 #ifndef __BASE_BITFIELD_HH__
42 #define __BASE_BITFIELD_HH__
47 #include <type_traits>
49 /** Lookup table used for High Speed bit reversing */
50 extern const uint8_t reverseLookUpTable[];
53 * Generate a 64-bit mask of 'nbits' 1s, right justified. If a number of bits
54 * greater than 64 is given, it is truncated to 64.
56 * @param nbits The number of bits set in the mask.
58 * @ingroup api_bitfield
63 return (nbits >= 64) ? (uint64_t)-1LL : (1ULL << nbits) - 1;
67 * Extract the bitfield from position 'first' to 'last' (inclusive)
68 * from 'val' and right justify it. MSB is numbered 63, LSB is 0.
70 * @ingroup api_bitfield
75 bits(T val, int first, int last)
77 int nbits = first - last + 1;
78 assert((first - last) >= 0);
79 return (val >> last) & mask(nbits);
83 * Extract the bit from this position from 'val' and right justify it.
85 * @ingroup api_bitfield
92 return bits(val, bit, bit);
96 * Mask off the given bits in place like bits() but without shifting.
99 * @ingroup api_bitfield
104 mbits(T val, int first, int last)
106 return val & (mask(first+1) & ~mask(last));
110 * @ingroup api_bitfield
113 mask(int first, int last)
115 return mbits((uint64_t)-1LL, first, last);
119 * Sign-extend an N-bit value to 64 bits.
121 * @ingroup api_bitfield
128 int sign_bit = bits(val, N-1, N-1);
129 return sign_bit ? (val | ~mask(N)) : val;
133 * Returns val with bits first to last set to the LSBs of bit_val
142 * @ingroup api_bitfield
144 template <class T, class B>
147 insertBits(T val, int first, int last, B bit_val)
149 T t_bit_val = bit_val;
150 assert((first - last) >= 0);
151 T bmask = mask(first - last + 1) << last;
152 return ((t_bit_val << last) & bmask) | (val & ~bmask);
156 * Overloaded for access to only one bit in value
158 * @ingroup api_bitfield
160 template <class T, class B>
163 insertBits(T val, int bit, B bit_val)
165 return insertBits(val, bit, bit, bit_val);
169 * A convenience function to replace bits first to last of val with bit_val
170 * in place. It is functionally equivalent to insertBits.
172 * \note "first" is the MSB and "last" is the LSB. "first" >= "last"
174 * @ingroup api_bitfield
176 template <class T, class B>
179 replaceBits(T& val, int first, int last, B bit_val)
181 val = insertBits(val, first, last, bit_val);
185 * Overloaded function to allow to access only 1 bit
187 * @ingroup api_bitfield
189 template <class T, class B>
192 replaceBits(T& val, int bit, B bit_val)
194 val = insertBits(val, bit, bit, bit_val);
198 * Takes a variable lenght word and returns the mirrored version
199 * (Bit by bit, LSB=>MSB).
202 * http://graphics.stanford.edu/~seander/bithacks.html
203 * #ReverseBitsByLookupTable
205 * @param val: variable lenght word
206 * @param size: number of bytes to mirror
207 * @return mirrored word
209 * @ingroup api_bitfield
213 reverseBits(T val, std::size_t size = sizeof(T))
215 static_assert(std::is_integral<T>::value, "Expecting an integer type");
217 assert(size <= sizeof(T));
220 for (auto byte = 0; byte < size; byte++, val = static_cast<T>(val >> 8)) {
221 output = (output << 8) | reverseLookUpTable[val & 0xFF];
228 * Returns the bit position of the MSB that is set in the input
230 * @ingroup api_bitfield
234 findMsbSet(uint64_t val) {
238 if (bits(val, 63,32)) { msb += 32; val >>= 32; }
239 if (bits(val, 31,16)) { msb += 16; val >>= 16; }
240 if (bits(val, 15,8)) { msb += 8; val >>= 8; }
241 if (bits(val, 7,4)) { msb += 4; val >>= 4; }
242 if (bits(val, 3,2)) { msb += 2; val >>= 2; }
243 if (bits(val, 1,1)) { msb += 1; }
248 * Returns the bit position of the LSB that is set in the input
250 * @ingroup api_bitfield
253 findLsbSet(uint64_t val) {
256 return sizeof(val) * 8;
257 if (!bits(val, 31,0)) { lsb += 32; val >>= 32; }
258 if (!bits(val, 15,0)) { lsb += 16; val >>= 16; }
259 if (!bits(val, 7,0)) { lsb += 8; val >>= 8; }
260 if (!bits(val, 3,0)) { lsb += 4; val >>= 4; }
261 if (!bits(val, 1,0)) { lsb += 2; val >>= 2; }
262 if (!bits(val, 0,0)) { lsb += 1; }
267 * Checks if a number is a power of two, or zero.
269 * @ingroup api_bitfield
274 return (v & (v - 1)) == (T)0;
278 * Returns the number of set ones in the provided value.
280 * http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
282 * @ingroup api_bitfield
285 popCount(uint64_t val) {
286 #ifndef __has_builtin
287 #define __has_builtin(foo) 0
289 #if defined(__GNUC__) || (defined(__clang__) && __has_builtin(__builtin_popcountl))
290 return __builtin_popcountl(val);
292 const uint64_t m1 = 0x5555555555555555; // ..010101b
293 const uint64_t m2 = 0x3333333333333333; // ..110011b
294 const uint64_t m4 = 0x0f0f0f0f0f0f0f0f; // ..001111b
295 const uint64_t sum = 0x0101010101010101;
297 val -= (val >> 1) & m1; // 2 bits count -> 2 bits
298 val = (val & m2) + ((val >> 2) & m2); // 4 bits count -> 4 bits
299 val = (val + (val >> 4)) & m4; // 8 bits count -> 8 bits
300 return (val * sum) >> 56; // horizontal sum
301 #endif // defined(__GNUC__) || (defined(__clang__) && __has_builtin(__builtin_popcountl))
305 * Align to the next highest power of two.
307 * The number passed in is aligned to the next highest power of two,
308 * if it is not already a power of two. Please note that if 0 is
309 * passed in, 0 is returned.
311 * This code has been modified from the following:
312 * http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
314 * @ingroup api_bitfield
316 inline uint64_t alignToPowerOfTwo(uint64_t val)
331 * Count trailing zeros in a 32-bit value.
333 * @param An input value
334 * @return The number of trailing zeros or 32 if the value is zero.
336 * @ingroup api_bitfield
338 inline int ctz32(uint32_t value)
340 return value ? __builtin_ctzl(value) : 32;
344 * Count trailing zeros in a 64-bit value.
346 * @param An input value
347 * @return The number of trailing zeros or 64 if the value is zero.
349 * @ingroup api_bitfield
351 inline int ctz64(uint64_t value)
353 return value ? __builtin_ctzll(value) : 64;
356 #endif // __BASE_BITFIELD_HH__