blob: 1da6750b45d38e445889fa57672daabe55049795 [file] [log] [blame]
Vladimir Marko80afd022015-05-19 18:08:00 +01001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ART_RUNTIME_BASE_BIT_UTILS_H_
18#define ART_RUNTIME_BASE_BIT_UTILS_H_
19
20#include <iterator>
21#include <limits>
22#include <type_traits>
23
24#include "base/logging.h"
25#include "base/iteration_range.h"
26
27namespace art {
28
29template<typename T>
30static constexpr int CLZ(T x) {
31 static_assert(std::is_integral<T>::value, "T must be integral");
32 // TODO: assert unsigned. There is currently many uses with signed values.
33 static_assert(sizeof(T) <= sizeof(long long), // NOLINT [runtime/int] [4]
34 "T too large, must be smaller than long long");
35 return (sizeof(T) == sizeof(uint32_t))
36 ? __builtin_clz(x) // TODO: __builtin_clz[ll] has undefined behavior for x=0
37 : __builtin_clzll(x);
38}
39
40template<typename T>
41static constexpr int CTZ(T x) {
42 static_assert(std::is_integral<T>::value, "T must be integral");
43 // TODO: assert unsigned. There is currently many uses with signed values.
44 return (sizeof(T) == sizeof(uint32_t))
45 ? __builtin_ctz(x)
46 : __builtin_ctzll(x);
47}
48
49template<typename T>
50static constexpr int POPCOUNT(T x) {
51 return (sizeof(T) == sizeof(uint32_t))
52 ? __builtin_popcount(x)
53 : __builtin_popcountll(x);
54}
55
56// Find the bit position of the most significant bit (0-based), or -1 if there were no bits set.
57template <typename T>
58static constexpr ssize_t MostSignificantBit(T value) {
59 static_assert(std::is_integral<T>::value, "T must be integral");
60 static_assert(std::is_unsigned<T>::value, "T must be unsigned");
61 static_assert(std::numeric_limits<T>::radix == 2, "Unexpected radix!");
62 return (value == 0) ? -1 : std::numeric_limits<T>::digits - 1 - CLZ(value);
63}
64
65// Find the bit position of the least significant bit (0-based), or -1 if there were no bits set.
66template <typename T>
67static constexpr ssize_t LeastSignificantBit(T value) {
68 static_assert(std::is_integral<T>::value, "T must be integral");
69 static_assert(std::is_unsigned<T>::value, "T must be unsigned");
70 return (value == 0) ? -1 : CTZ(value);
71}
72
73// How many bits (minimally) does it take to store the constant 'value'? i.e. 1 for 1, 3 for 5, etc.
74template <typename T>
75static constexpr size_t MinimumBitsToStore(T value) {
76 return static_cast<size_t>(MostSignificantBit(value) + 1);
77}
78
79template <typename T>
80static constexpr inline T RoundUpToPowerOfTwo(T x) {
81 static_assert(std::is_integral<T>::value, "T must be integral");
82 static_assert(std::is_unsigned<T>::value, "T must be unsigned");
83 // NOTE: Undefined if x > (1 << (std::numeric_limits<T>::digits - 1)).
84 return (x < 2u) ? x : static_cast<T>(1u) << (std::numeric_limits<T>::digits - CLZ(x - 1u));
85}
86
87template<typename T>
88static constexpr bool IsPowerOfTwo(T x) {
89 static_assert(std::is_integral<T>::value, "T must be integral");
90 // TODO: assert unsigned. There is currently many uses with signed values.
91 return (x & (x - 1)) == 0;
92}
93
94template<typename T>
95static inline int WhichPowerOf2(T x) {
96 static_assert(std::is_integral<T>::value, "T must be integral");
97 // TODO: assert unsigned. There is currently many uses with signed values.
98 DCHECK((x != 0) && IsPowerOfTwo(x));
99 return CTZ(x);
100}
101
102// For rounding integers.
103// NOTE: In the absence of std::omit_from_type_deduction<T> or std::identity<T>, use std::decay<T>.
104template<typename T>
105static constexpr T RoundDown(T x, typename std::decay<T>::type n) WARN_UNUSED;
106
107template<typename T>
108static constexpr T RoundDown(T x, typename std::decay<T>::type n) {
109 return
110 DCHECK_CONSTEXPR(IsPowerOfTwo(n), , T(0))
111 (x & -n);
112}
113
114template<typename T>
115static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) WARN_UNUSED;
116
117template<typename T>
118static constexpr T RoundUp(T x, typename std::remove_reference<T>::type n) {
119 return RoundDown(x + n - 1, n);
120}
121
122// For aligning pointers.
123template<typename T>
124static inline T* AlignDown(T* x, uintptr_t n) WARN_UNUSED;
125
126template<typename T>
127static inline T* AlignDown(T* x, uintptr_t n) {
128 return reinterpret_cast<T*>(RoundDown(reinterpret_cast<uintptr_t>(x), n));
129}
130
131template<typename T>
132static inline T* AlignUp(T* x, uintptr_t n) WARN_UNUSED;
133
134template<typename T>
135static inline T* AlignUp(T* x, uintptr_t n) {
136 return reinterpret_cast<T*>(RoundUp(reinterpret_cast<uintptr_t>(x), n));
137}
138
139template<int n, typename T>
Nicolas Geoffray7bf2b4f2015-07-08 10:11:59 +0000140static constexpr bool IsAligned(T x) {
Vladimir Marko80afd022015-05-19 18:08:00 +0100141 static_assert((n & (n - 1)) == 0, "n is not a power of two");
142 return (x & (n - 1)) == 0;
143}
144
145template<int n, typename T>
146static inline bool IsAligned(T* x) {
147 return IsAligned<n>(reinterpret_cast<const uintptr_t>(x));
148}
149
150template<typename T>
151static inline bool IsAlignedParam(T x, int n) {
152 return (x & (n - 1)) == 0;
153}
154
155#define CHECK_ALIGNED(value, alignment) \
156 CHECK(::art::IsAligned<alignment>(value)) << reinterpret_cast<const void*>(value)
157
158#define DCHECK_ALIGNED(value, alignment) \
159 DCHECK(::art::IsAligned<alignment>(value)) << reinterpret_cast<const void*>(value)
160
Vladimir Markocf36d492015-08-12 19:27:26 +0100161#define CHECK_ALIGNED_PARAM(value, alignment) \
162 CHECK(::art::IsAlignedParam(value, alignment)) << reinterpret_cast<const void*>(value)
163
Vladimir Marko80afd022015-05-19 18:08:00 +0100164#define DCHECK_ALIGNED_PARAM(value, alignment) \
165 DCHECK(::art::IsAlignedParam(value, alignment)) << reinterpret_cast<const void*>(value)
166
167// Like sizeof, but count how many bits a type takes. Pass type explicitly.
168template <typename T>
169static constexpr size_t BitSizeOf() {
170 static_assert(std::is_integral<T>::value, "T must be integral");
171 typedef typename std::make_unsigned<T>::type unsigned_type;
172 static_assert(sizeof(T) == sizeof(unsigned_type), "Unexpected type size mismatch!");
173 static_assert(std::numeric_limits<unsigned_type>::radix == 2, "Unexpected radix!");
174 return std::numeric_limits<unsigned_type>::digits;
175}
176
177// Like sizeof, but count how many bits a type takes. Infers type from parameter.
178template <typename T>
179static constexpr size_t BitSizeOf(T /*x*/) {
180 return BitSizeOf<T>();
181}
182
183static inline uint16_t Low16Bits(uint32_t value) {
184 return static_cast<uint16_t>(value);
185}
186
187static inline uint16_t High16Bits(uint32_t value) {
188 return static_cast<uint16_t>(value >> 16);
189}
190
191static inline uint32_t Low32Bits(uint64_t value) {
192 return static_cast<uint32_t>(value);
193}
194
195static inline uint32_t High32Bits(uint64_t value) {
196 return static_cast<uint32_t>(value >> 32);
197}
198
199// Check whether an N-bit two's-complement representation can hold value.
200template <typename T>
201static inline bool IsInt(size_t N, T value) {
202 if (N == BitSizeOf<T>()) {
203 return true;
204 } else {
205 CHECK_LT(0u, N);
206 CHECK_LT(N, BitSizeOf<T>());
207 T limit = static_cast<T>(1) << (N - 1u);
208 return (-limit <= value) && (value < limit);
209 }
210}
211
212template <typename T>
213static constexpr T GetIntLimit(size_t bits) {
214 return
215 DCHECK_CONSTEXPR(bits > 0, "bits cannot be zero", 0)
216 DCHECK_CONSTEXPR(bits < BitSizeOf<T>(), "kBits must be < max.", 0)
217 static_cast<T>(1) << (bits - 1);
218}
219
220template <size_t kBits, typename T>
221static constexpr bool IsInt(T value) {
222 static_assert(kBits > 0, "kBits cannot be zero.");
223 static_assert(kBits <= BitSizeOf<T>(), "kBits must be <= max.");
224 static_assert(std::is_signed<T>::value, "Needs a signed type.");
225 // Corner case for "use all bits." Can't use the limits, as they would overflow, but it is
226 // trivially true.
227 return (kBits == BitSizeOf<T>()) ?
228 true :
229 (-GetIntLimit<T>(kBits) <= value) && (value < GetIntLimit<T>(kBits));
230}
231
232template <size_t kBits, typename T>
233static constexpr bool IsUint(T value) {
234 static_assert(kBits > 0, "kBits cannot be zero.");
235 static_assert(kBits <= BitSizeOf<T>(), "kBits must be <= max.");
236 static_assert(std::is_integral<T>::value, "Needs an integral type.");
237 // Corner case for "use all bits." Can't use the limits, as they would overflow, but it is
238 // trivially true.
239 // NOTE: To avoid triggering assertion in GetIntLimit(kBits+1) if kBits+1==BitSizeOf<T>(),
240 // use GetIntLimit(kBits)*2u. The unsigned arithmetic works well for us if it overflows.
241 return (0 <= value) &&
242 (kBits == BitSizeOf<T>() ||
243 (static_cast<typename std::make_unsigned<T>::type>(value) <=
244 GetIntLimit<typename std::make_unsigned<T>::type>(kBits) * 2u - 1u));
245}
246
247template <size_t kBits, typename T>
248static constexpr bool IsAbsoluteUint(T value) {
249 static_assert(kBits <= BitSizeOf<T>(), "kBits must be <= max.");
250 static_assert(std::is_integral<T>::value, "Needs an integral type.");
251 typedef typename std::make_unsigned<T>::type unsigned_type;
252 return (kBits == BitSizeOf<T>())
253 ? true
254 : IsUint<kBits>(value < 0
255 ? static_cast<unsigned_type>(-1 - value) + 1u // Avoid overflow.
256 : static_cast<unsigned_type>(value));
257}
258
259// Using the Curiously Recurring Template Pattern to implement everything shared
260// by LowToHighBitIterator and HighToLowBitIterator, i.e. everything but operator*().
261template <typename T, typename Iter>
262class BitIteratorBase
263 : public std::iterator<std::forward_iterator_tag, uint32_t, ptrdiff_t, void, void> {
264 static_assert(std::is_integral<T>::value, "T must be integral");
265 static_assert(std::is_unsigned<T>::value, "T must be unsigned");
266
267 static_assert(sizeof(T) == sizeof(uint32_t) || sizeof(T) == sizeof(uint64_t), "Unsupported size");
268
269 public:
270 BitIteratorBase() : bits_(0u) { }
271 explicit BitIteratorBase(T bits) : bits_(bits) { }
272
273 Iter& operator++() {
274 DCHECK_NE(bits_, 0u);
275 uint32_t bit = *static_cast<Iter&>(*this);
276 bits_ &= ~(static_cast<T>(1u) << bit);
277 return static_cast<Iter&>(*this);
278 }
279
280 Iter& operator++(int) {
281 Iter tmp(static_cast<Iter&>(*this));
282 ++*this;
283 return tmp;
284 }
285
286 protected:
287 T bits_;
288
289 template <typename U, typename I>
290 friend bool operator==(const BitIteratorBase<U, I>& lhs, const BitIteratorBase<U, I>& rhs);
291};
292
293template <typename T, typename Iter>
294bool operator==(const BitIteratorBase<T, Iter>& lhs, const BitIteratorBase<T, Iter>& rhs) {
295 return lhs.bits_ == rhs.bits_;
296}
297
298template <typename T, typename Iter>
299bool operator!=(const BitIteratorBase<T, Iter>& lhs, const BitIteratorBase<T, Iter>& rhs) {
300 return !(lhs == rhs);
301}
302
303template <typename T>
304class LowToHighBitIterator : public BitIteratorBase<T, LowToHighBitIterator<T>> {
305 public:
306 using BitIteratorBase<T, LowToHighBitIterator<T>>::BitIteratorBase;
307
308 uint32_t operator*() const {
309 DCHECK_NE(this->bits_, 0u);
310 return CTZ(this->bits_);
311 }
312};
313
314template <typename T>
315class HighToLowBitIterator : public BitIteratorBase<T, HighToLowBitIterator<T>> {
316 public:
317 using BitIteratorBase<T, HighToLowBitIterator<T>>::BitIteratorBase;
318
319 uint32_t operator*() const {
320 DCHECK_NE(this->bits_, 0u);
321 static_assert(std::numeric_limits<T>::radix == 2, "Unexpected radix!");
322 return std::numeric_limits<T>::digits - 1u - CLZ(this->bits_);
323 }
324};
325
326template <typename T>
327IterationRange<LowToHighBitIterator<T>> LowToHighBits(T bits) {
328 return IterationRange<LowToHighBitIterator<T>>(
329 LowToHighBitIterator<T>(bits), LowToHighBitIterator<T>());
330}
331
332template <typename T>
333IterationRange<HighToLowBitIterator<T>> HighToLowBits(T bits) {
334 return IterationRange<HighToLowBitIterator<T>>(
335 HighToLowBitIterator<T>(bits), HighToLowBitIterator<T>());
336}
337
338} // namespace art
339
340#endif // ART_RUNTIME_BASE_BIT_UTILS_H_