1 //===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains some functions that are useful for math stuff.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_MATHEXTRAS_H
15 #define LLVM_SUPPORT_MATHEXTRAS_H
17 #include "llvm/Support/Compiler.h"
18 #include "llvm/Support/SwapByteOrder.h"
21 #include <type_traits>
27 #ifdef __ANDROID_NDK__
28 #include <android/api-level.h>
32 /// \brief The behavior an operation has on an input of 0.
34 /// \brief The returned value is undefined.
36 /// \brief The returned value is numeric_limits<T>::max()
38 /// \brief The returned value is numeric_limits<T>::digits
43 template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
44 static std::size_t count(T Val, ZeroBehavior) {
46 return std::numeric_limits<T>::digits;
51 std::size_t ZeroBits = 0;
52 T Shift = std::numeric_limits<T>::digits >> 1;
53 T Mask = std::numeric_limits<T>::max() >> Shift;
55 if ((Val & Mask) == 0) {
66 #if __GNUC__ >= 4 || defined(_MSC_VER)
67 template <typename T> struct TrailingZerosCounter<T, 4> {
68 static std::size_t count(T Val, ZeroBehavior ZB) {
69 if (ZB != ZB_Undefined && Val == 0)
72 #if __has_builtin(__builtin_ctz) || LLVM_GNUC_PREREQ(4, 0, 0)
73 return __builtin_ctz(Val);
74 #elif defined(_MSC_VER)
76 _BitScanForward(&Index, Val);
82 #if !defined(_MSC_VER) || defined(_M_X64)
83 template <typename T> struct TrailingZerosCounter<T, 8> {
84 static std::size_t count(T Val, ZeroBehavior ZB) {
85 if (ZB != ZB_Undefined && Val == 0)
88 #if __has_builtin(__builtin_ctzll) || LLVM_GNUC_PREREQ(4, 0, 0)
89 return __builtin_ctzll(Val);
90 #elif defined(_MSC_VER)
92 _BitScanForward64(&Index, Val);
101 /// \brief Count number of 0's from the least significant bit to the most
102 /// stopping at the first 1.
104 /// Only unsigned integral types are allowed.
106 /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
108 template <typename T>
109 std::size_t countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
110 static_assert(std::numeric_limits<T>::is_integer &&
111 !std::numeric_limits<T>::is_signed,
112 "Only unsigned integral types are allowed.");
113 return detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
117 template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
118 static std::size_t count(T Val, ZeroBehavior) {
120 return std::numeric_limits<T>::digits;
123 std::size_t ZeroBits = 0;
124 for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
125 T Tmp = Val >> Shift;
135 #if __GNUC__ >= 4 || defined(_MSC_VER)
136 template <typename T> struct LeadingZerosCounter<T, 4> {
137 static std::size_t count(T Val, ZeroBehavior ZB) {
138 if (ZB != ZB_Undefined && Val == 0)
141 #if __has_builtin(__builtin_clz) || LLVM_GNUC_PREREQ(4, 0, 0)
142 return __builtin_clz(Val);
143 #elif defined(_MSC_VER)
145 _BitScanReverse(&Index, Val);
151 #if !defined(_MSC_VER) || defined(_M_X64)
152 template <typename T> struct LeadingZerosCounter<T, 8> {
153 static std::size_t count(T Val, ZeroBehavior ZB) {
154 if (ZB != ZB_Undefined && Val == 0)
157 #if __has_builtin(__builtin_clzll) || LLVM_GNUC_PREREQ(4, 0, 0)
158 return __builtin_clzll(Val);
159 #elif defined(_MSC_VER)
161 _BitScanReverse64(&Index, Val);
168 } // namespace detail
170 /// \brief Count number of 0's from the most significant bit to the least
171 /// stopping at the first 1.
173 /// Only unsigned integral types are allowed.
175 /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
177 template <typename T>
178 std::size_t countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
179 static_assert(std::numeric_limits<T>::is_integer &&
180 !std::numeric_limits<T>::is_signed,
181 "Only unsigned integral types are allowed.");
182 return detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
185 /// \brief Get the index of the first set bit starting from the least
188 /// Only unsigned integral types are allowed.
190 /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
192 template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
193 if (ZB == ZB_Max && Val == 0)
194 return std::numeric_limits<T>::max();
196 return countTrailingZeros(Val, ZB_Undefined);
199 /// \brief Get the index of the last set bit starting from the least
202 /// Only unsigned integral types are allowed.
204 /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
206 template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
207 if (ZB == ZB_Max && Val == 0)
208 return std::numeric_limits<T>::max();
210 // Use ^ instead of - because both gcc and llvm can remove the associated ^
211 // in the __builtin_clz intrinsic on x86.
212 return countLeadingZeros(Val, ZB_Undefined) ^
213 (std::numeric_limits<T>::digits - 1);
216 /// \brief Macro compressed bit reversal table for 256 bits.
218 /// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
219 static const unsigned char BitReverseTable256[256] = {
220 #define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
221 #define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
222 #define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
223 R6(0), R6(2), R6(1), R6(3)
229 /// \brief Reverse the bits in \p Val.
230 template <typename T>
231 T reverseBits(T Val) {
232 unsigned char in[sizeof(Val)];
233 unsigned char out[sizeof(Val)];
234 std::memcpy(in, &Val, sizeof(Val));
235 for (unsigned i = 0; i < sizeof(Val); ++i)
236 out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
237 std::memcpy(&Val, out, sizeof(Val));
241 // NOTE: The following support functions use the _32/_64 extensions instead of
242 // type overloading so that signed and unsigned integers can be used without
245 /// Hi_32 - This function returns the high 32 bits of a 64 bit value.
246 inline uint32_t Hi_32(uint64_t Value) {
247 return static_cast<uint32_t>(Value >> 32);
250 /// Lo_32 - This function returns the low 32 bits of a 64 bit value.
251 inline uint32_t Lo_32(uint64_t Value) {
252 return static_cast<uint32_t>(Value);
255 /// Make_64 - This functions makes a 64-bit integer from a high / low pair of
257 inline uint64_t Make_64(uint32_t High, uint32_t Low) {
258 return ((uint64_t)High << 32) | (uint64_t)Low;
261 /// isInt - Checks if an integer fits into the given bit width.
263 inline bool isInt(int64_t x) {
264 return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
266 // Template specializations to get better code for common cases.
268 inline bool isInt<8>(int64_t x) {
269 return static_cast<int8_t>(x) == x;
272 inline bool isInt<16>(int64_t x) {
273 return static_cast<int16_t>(x) == x;
276 inline bool isInt<32>(int64_t x) {
277 return static_cast<int32_t>(x) == x;
280 /// isShiftedInt<N,S> - Checks if a signed integer is an N bit number shifted
282 template<unsigned N, unsigned S>
283 inline bool isShiftedInt(int64_t x) {
284 return isInt<N+S>(x) && (x % (1<<S) == 0);
287 /// isUInt - Checks if an unsigned integer fits into the given bit width.
289 inline bool isUInt(uint64_t x) {
290 return N >= 64 || x < (UINT64_C(1)<<(N));
292 // Template specializations to get better code for common cases.
294 inline bool isUInt<8>(uint64_t x) {
295 return static_cast<uint8_t>(x) == x;
298 inline bool isUInt<16>(uint64_t x) {
299 return static_cast<uint16_t>(x) == x;
302 inline bool isUInt<32>(uint64_t x) {
303 return static_cast<uint32_t>(x) == x;
306 /// isShiftedUInt<N,S> - Checks if a unsigned integer is an N bit number shifted
308 template<unsigned N, unsigned S>
309 inline bool isShiftedUInt(uint64_t x) {
310 return isUInt<N+S>(x) && (x % (1<<S) == 0);
313 /// isUIntN - Checks if an unsigned integer fits into the given (dynamic)
315 inline bool isUIntN(unsigned N, uint64_t x) {
316 return N >= 64 || x < (UINT64_C(1)<<(N));
319 /// isIntN - Checks if an signed integer fits into the given (dynamic)
321 inline bool isIntN(unsigned N, int64_t x) {
322 return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
325 /// isMask_32 - This function returns true if the argument is a non-empty
326 /// sequence of ones starting at the least significant bit with the remainder
327 /// zero (32 bit version). Ex. isMask_32(0x0000FFFFU) == true.
328 inline bool isMask_32(uint32_t Value) {
329 return Value && ((Value + 1) & Value) == 0;
332 /// isMask_64 - This function returns true if the argument is a non-empty
333 /// sequence of ones starting at the least significant bit with the remainder
334 /// zero (64 bit version).
335 inline bool isMask_64(uint64_t Value) {
336 return Value && ((Value + 1) & Value) == 0;
339 /// isShiftedMask_32 - This function returns true if the argument contains a
340 /// non-empty sequence of ones with the remainder zero (32 bit version.)
341 /// Ex. isShiftedMask_32(0x0000FF00U) == true.
342 inline bool isShiftedMask_32(uint32_t Value) {
343 return Value && isMask_32((Value - 1) | Value);
346 /// isShiftedMask_64 - This function returns true if the argument contains a
347 /// non-empty sequence of ones with the remainder zero (64 bit version.)
348 inline bool isShiftedMask_64(uint64_t Value) {
349 return Value && isMask_64((Value - 1) | Value);
352 /// isPowerOf2_32 - This function returns true if the argument is a power of
353 /// two > 0. Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
354 inline bool isPowerOf2_32(uint32_t Value) {
355 return Value && !(Value & (Value - 1));
358 /// isPowerOf2_64 - This function returns true if the argument is a power of two
359 /// > 0 (64 bit edition.)
360 inline bool isPowerOf2_64(uint64_t Value) {
361 return Value && !(Value & (Value - int64_t(1L)));
364 /// ByteSwap_16 - This function returns a byte-swapped representation of the
365 /// 16-bit argument, Value.
366 inline uint16_t ByteSwap_16(uint16_t Value) {
367 return sys::SwapByteOrder_16(Value);
370 /// ByteSwap_32 - This function returns a byte-swapped representation of the
371 /// 32-bit argument, Value.
372 inline uint32_t ByteSwap_32(uint32_t Value) {
373 return sys::SwapByteOrder_32(Value);
376 /// ByteSwap_64 - This function returns a byte-swapped representation of the
377 /// 64-bit argument, Value.
378 inline uint64_t ByteSwap_64(uint64_t Value) {
379 return sys::SwapByteOrder_64(Value);
382 /// \brief Count the number of ones from the most significant bit to the first
385 /// Ex. CountLeadingOnes(0xFF0FFF00) == 8.
386 /// Only unsigned integral types are allowed.
388 /// \param ZB the behavior on an input of all ones. Only ZB_Width and
389 /// ZB_Undefined are valid arguments.
390 template <typename T>
391 std::size_t countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
392 static_assert(std::numeric_limits<T>::is_integer &&
393 !std::numeric_limits<T>::is_signed,
394 "Only unsigned integral types are allowed.");
395 return countLeadingZeros(~Value, ZB);
398 /// \brief Count the number of ones from the least significant bit to the first
401 /// Ex. countTrailingOnes(0x00FF00FF) == 8.
402 /// Only unsigned integral types are allowed.
404 /// \param ZB the behavior on an input of all ones. Only ZB_Width and
405 /// ZB_Undefined are valid arguments.
406 template <typename T>
407 std::size_t countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
408 static_assert(std::numeric_limits<T>::is_integer &&
409 !std::numeric_limits<T>::is_signed,
410 "Only unsigned integral types are allowed.");
411 return countTrailingZeros(~Value, ZB);
415 template <typename T, std::size_t SizeOfT> struct PopulationCounter {
416 static unsigned count(T Value) {
417 // Generic version, forward to 32 bits.
418 static_assert(SizeOfT <= 4, "Not implemented!");
420 return __builtin_popcount(Value);
423 v = v - ((v >> 1) & 0x55555555);
424 v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
425 return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
430 template <typename T> struct PopulationCounter<T, 8> {
431 static unsigned count(T Value) {
433 return __builtin_popcountll(Value);
436 v = v - ((v >> 1) & 0x5555555555555555ULL);
437 v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
438 v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
439 return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
443 } // namespace detail
445 /// \brief Count the number of set bits in a value.
446 /// Ex. countPopulation(0xF000F000) = 8
447 /// Returns 0 if the word is zero.
448 template <typename T>
449 inline unsigned countPopulation(T Value) {
450 static_assert(std::numeric_limits<T>::is_integer &&
451 !std::numeric_limits<T>::is_signed,
452 "Only unsigned integral types are allowed.");
453 return detail::PopulationCounter<T, sizeof(T)>::count(Value);
456 /// Log2 - This function returns the log base 2 of the specified value
457 inline double Log2(double Value) {
458 #if defined(__ANDROID_API__) && __ANDROID_API__ < 18
459 return __builtin_log(Value) / __builtin_log(2.0);
465 /// Log2_32 - This function returns the floor log base 2 of the specified value,
466 /// -1 if the value is zero. (32 bit edition.)
467 /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
468 inline unsigned Log2_32(uint32_t Value) {
469 return 31 - countLeadingZeros(Value);
472 /// Log2_64 - This function returns the floor log base 2 of the specified value,
473 /// -1 if the value is zero. (64 bit edition.)
474 inline unsigned Log2_64(uint64_t Value) {
475 return 63 - countLeadingZeros(Value);
478 /// Log2_32_Ceil - This function returns the ceil log base 2 of the specified
479 /// value, 32 if the value is zero. (32 bit edition).
480 /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
481 inline unsigned Log2_32_Ceil(uint32_t Value) {
482 return 32 - countLeadingZeros(Value - 1);
485 /// Log2_64_Ceil - This function returns the ceil log base 2 of the specified
486 /// value, 64 if the value is zero. (64 bit edition.)
487 inline unsigned Log2_64_Ceil(uint64_t Value) {
488 return 64 - countLeadingZeros(Value - 1);
491 /// GreatestCommonDivisor64 - Return the greatest common divisor of the two
492 /// values using Euclid's algorithm.
493 inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
502 /// BitsToDouble - This function takes a 64-bit integer and returns the bit
503 /// equivalent double.
504 inline double BitsToDouble(uint64_t Bits) {
513 /// BitsToFloat - This function takes a 32-bit integer and returns the bit
514 /// equivalent float.
515 inline float BitsToFloat(uint32_t Bits) {
524 /// DoubleToBits - This function takes a double and returns the bit
525 /// equivalent 64-bit integer. Note that copying doubles around
526 /// changes the bits of NaNs on some hosts, notably x86, so this
527 /// routine cannot be used if these bits are needed.
528 inline uint64_t DoubleToBits(double Double) {
537 /// FloatToBits - This function takes a float and returns the bit
538 /// equivalent 32-bit integer. Note that copying floats around
539 /// changes the bits of NaNs on some hosts, notably x86, so this
540 /// routine cannot be used if these bits are needed.
541 inline uint32_t FloatToBits(float Float) {
550 /// MinAlign - A and B are either alignments or offsets. Return the minimum
551 /// alignment that may be assumed after adding the two together.
552 inline uint64_t MinAlign(uint64_t A, uint64_t B) {
553 // The largest power of 2 that divides both A and B.
555 // Replace "-Value" by "1+~Value" in the following commented code to avoid
556 // MSVC warning C4146
557 // return (A | B) & -(A | B);
558 return (A | B) & (1 + ~(A | B));
561 /// \brief Aligns \c Addr to \c Alignment bytes, rounding up.
563 /// Alignment should be a power of two. This method rounds up, so
564 /// alignAddr(7, 4) == 8 and alignAddr(8, 4) == 8.
565 inline uintptr_t alignAddr(const void *Addr, size_t Alignment) {
566 assert(Alignment && isPowerOf2_64((uint64_t)Alignment) &&
567 "Alignment is not a power of two!");
569 assert((uintptr_t)Addr + Alignment - 1 >= (uintptr_t)Addr);
571 return (((uintptr_t)Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1));
574 /// \brief Returns the necessary adjustment for aligning \c Ptr to \c Alignment
575 /// bytes, rounding up.
576 inline size_t alignmentAdjustment(const void *Ptr, size_t Alignment) {
577 return alignAddr(Ptr, Alignment) - (uintptr_t)Ptr;
580 /// NextPowerOf2 - Returns the next power of two (in 64-bits)
581 /// that is strictly greater than A. Returns zero on overflow.
582 inline uint64_t NextPowerOf2(uint64_t A) {
592 /// Returns the power of two which is less than or equal to the given value.
593 /// Essentially, it is a floor operation across the domain of powers of two.
594 inline uint64_t PowerOf2Floor(uint64_t A) {
596 return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
599 /// Returns the next integer (mod 2**64) that is greater than or equal to
600 /// \p Value and is a multiple of \p Align. \p Align must be non-zero.
602 /// If non-zero \p Skew is specified, the return value will be a minimal
603 /// integer that is greater than or equal to \p Value and equal to
604 /// \p Align * N + \p Skew for some integer N. If \p Skew is larger than
605 /// \p Align, its value is adjusted to '\p Skew mod \p Align'.
609 /// RoundUpToAlignment(5, 8) = 8
610 /// RoundUpToAlignment(17, 8) = 24
611 /// RoundUpToAlignment(~0LL, 8) = 0
612 /// RoundUpToAlignment(321, 255) = 510
614 /// RoundUpToAlignment(5, 8, 7) = 7
615 /// RoundUpToAlignment(17, 8, 1) = 17
616 /// RoundUpToAlignment(~0LL, 8, 3) = 3
617 /// RoundUpToAlignment(321, 255, 42) = 552
619 inline uint64_t RoundUpToAlignment(uint64_t Value, uint64_t Align,
622 return (Value + Align - 1 - Skew) / Align * Align + Skew;
625 /// Returns the offset to the next integer (mod 2**64) that is greater than
626 /// or equal to \p Value and is a multiple of \p Align. \p Align must be
628 inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) {
629 return RoundUpToAlignment(Value, Align) - Value;
632 /// SignExtend32 - Sign extend B-bit number x to 32-bit int.
633 /// Usage int32_t r = SignExtend32<5>(x);
634 template <unsigned B> inline int32_t SignExtend32(uint32_t x) {
635 return int32_t(x << (32 - B)) >> (32 - B);
638 /// \brief Sign extend number in the bottom B bits of X to a 32-bit int.
639 /// Requires 0 < B <= 32.
640 inline int32_t SignExtend32(uint32_t X, unsigned B) {
641 return int32_t(X << (32 - B)) >> (32 - B);
644 /// SignExtend64 - Sign extend B-bit number x to 64-bit int.
645 /// Usage int64_t r = SignExtend64<5>(x);
646 template <unsigned B> inline int64_t SignExtend64(uint64_t x) {
647 return int64_t(x << (64 - B)) >> (64 - B);
650 /// \brief Sign extend number in the bottom B bits of X to a 64-bit int.
651 /// Requires 0 < B <= 64.
652 inline int64_t SignExtend64(uint64_t X, unsigned B) {
653 return int64_t(X << (64 - B)) >> (64 - B);
656 extern const float huge_valf;
657 } // End llvm namespace