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