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"
24 #include <type_traits>
30 #ifdef __ANDROID_NDK__
31 #include <android/api-level.h>
35 /// \brief The behavior an operation has on an input of 0.
37 /// \brief The returned value is undefined.
39 /// \brief The returned value is numeric_limits<T>::max()
41 /// \brief The returned value is numeric_limits<T>::digits
46 template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
47 static std::size_t count(T Val, ZeroBehavior) {
49 return std::numeric_limits<T>::digits;
54 std::size_t ZeroBits = 0;
55 T Shift = std::numeric_limits<T>::digits >> 1;
56 T Mask = std::numeric_limits<T>::max() >> Shift;
58 if ((Val & Mask) == 0) {
69 #if __GNUC__ >= 4 || defined(_MSC_VER)
70 template <typename T> struct TrailingZerosCounter<T, 4> {
71 static std::size_t count(T Val, ZeroBehavior ZB) {
72 if (ZB != ZB_Undefined && Val == 0)
75 #if __has_builtin(__builtin_ctz) || LLVM_GNUC_PREREQ(4, 0, 0)
76 return __builtin_ctz(Val);
77 #elif defined(_MSC_VER)
79 _BitScanForward(&Index, Val);
85 #if !defined(_MSC_VER) || defined(_M_X64)
86 template <typename T> struct TrailingZerosCounter<T, 8> {
87 static std::size_t count(T Val, ZeroBehavior ZB) {
88 if (ZB != ZB_Undefined && Val == 0)
91 #if __has_builtin(__builtin_ctzll) || LLVM_GNUC_PREREQ(4, 0, 0)
92 return __builtin_ctzll(Val);
93 #elif defined(_MSC_VER)
95 _BitScanForward64(&Index, Val);
102 } // namespace detail
104 /// \brief Count number of 0's from the least significant bit to the most
105 /// stopping at the first 1.
107 /// Only unsigned integral types are allowed.
109 /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
111 template <typename T>
112 std::size_t countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
113 static_assert(std::numeric_limits<T>::is_integer &&
114 !std::numeric_limits<T>::is_signed,
115 "Only unsigned integral types are allowed.");
116 return llvm::detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
120 template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
121 static std::size_t count(T Val, ZeroBehavior) {
123 return std::numeric_limits<T>::digits;
126 std::size_t ZeroBits = 0;
127 for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
128 T Tmp = Val >> Shift;
138 #if __GNUC__ >= 4 || defined(_MSC_VER)
139 template <typename T> struct LeadingZerosCounter<T, 4> {
140 static std::size_t count(T Val, ZeroBehavior ZB) {
141 if (ZB != ZB_Undefined && Val == 0)
144 #if __has_builtin(__builtin_clz) || LLVM_GNUC_PREREQ(4, 0, 0)
145 return __builtin_clz(Val);
146 #elif defined(_MSC_VER)
148 _BitScanReverse(&Index, Val);
154 #if !defined(_MSC_VER) || defined(_M_X64)
155 template <typename T> struct LeadingZerosCounter<T, 8> {
156 static std::size_t count(T Val, ZeroBehavior ZB) {
157 if (ZB != ZB_Undefined && Val == 0)
160 #if __has_builtin(__builtin_clzll) || LLVM_GNUC_PREREQ(4, 0, 0)
161 return __builtin_clzll(Val);
162 #elif defined(_MSC_VER)
164 _BitScanReverse64(&Index, Val);
171 } // namespace detail
173 /// \brief Count number of 0's from the most significant bit to the least
174 /// stopping at the first 1.
176 /// Only unsigned integral types are allowed.
178 /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
180 template <typename T>
181 std::size_t countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
182 static_assert(std::numeric_limits<T>::is_integer &&
183 !std::numeric_limits<T>::is_signed,
184 "Only unsigned integral types are allowed.");
185 return llvm::detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
188 /// \brief Get the index of the first set bit starting from the least
191 /// Only unsigned integral types are allowed.
193 /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
195 template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
196 if (ZB == ZB_Max && Val == 0)
197 return std::numeric_limits<T>::max();
199 return countTrailingZeros(Val, ZB_Undefined);
202 /// \brief Create a bitmask with the N right-most bits set to 1, and all other
203 /// bits set to 0. Only unsigned types are allowed.
204 template <typename T> T maskTrailingOnes(unsigned N) {
205 static_assert(std::is_unsigned<T>::value, "Invalid type!");
206 const unsigned Bits = CHAR_BIT * sizeof(T);
207 assert(N <= Bits && "Invalid bit index");
208 return N == 0 ? 0 : (T(-1) >> (Bits - N));
211 /// \brief Create a bitmask with the N left-most bits set to 1, and all other
212 /// bits set to 0. Only unsigned types are allowed.
213 template <typename T> T maskLeadingOnes(unsigned N) {
214 return ~maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
217 /// \brief Create a bitmask with the N right-most bits set to 0, and all other
218 /// bits set to 1. Only unsigned types are allowed.
219 template <typename T> T maskTrailingZeros(unsigned N) {
220 return maskLeadingOnes<T>(CHAR_BIT * sizeof(T) - N);
223 /// \brief Create a bitmask with the N left-most bits set to 0, and all other
224 /// bits set to 1. Only unsigned types are allowed.
225 template <typename T> T maskLeadingZeros(unsigned N) {
226 return maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
229 /// \brief Get the index of the last set bit starting from the least
232 /// Only unsigned integral types are allowed.
234 /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
236 template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
237 if (ZB == ZB_Max && Val == 0)
238 return std::numeric_limits<T>::max();
240 // Use ^ instead of - because both gcc and llvm can remove the associated ^
241 // in the __builtin_clz intrinsic on x86.
242 return countLeadingZeros(Val, ZB_Undefined) ^
243 (std::numeric_limits<T>::digits - 1);
246 /// \brief Macro compressed bit reversal table for 256 bits.
248 /// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
249 static const unsigned char BitReverseTable256[256] = {
250 #define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
251 #define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
252 #define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
253 R6(0), R6(2), R6(1), R6(3)
259 /// \brief Reverse the bits in \p Val.
260 template <typename T>
261 T reverseBits(T Val) {
262 unsigned char in[sizeof(Val)];
263 unsigned char out[sizeof(Val)];
264 std::memcpy(in, &Val, sizeof(Val));
265 for (unsigned i = 0; i < sizeof(Val); ++i)
266 out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
267 std::memcpy(&Val, out, sizeof(Val));
271 // NOTE: The following support functions use the _32/_64 extensions instead of
272 // type overloading so that signed and unsigned integers can be used without
275 /// Hi_32 - This function returns the high 32 bits of a 64 bit value.
276 constexpr inline uint32_t Hi_32(uint64_t Value) {
277 return static_cast<uint32_t>(Value >> 32);
280 /// Lo_32 - This function returns the low 32 bits of a 64 bit value.
281 constexpr inline uint32_t Lo_32(uint64_t Value) {
282 return static_cast<uint32_t>(Value);
285 /// Make_64 - This functions makes a 64-bit integer from a high / low pair of
287 constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) {
288 return ((uint64_t)High << 32) | (uint64_t)Low;
291 /// isInt - Checks if an integer fits into the given bit width.
292 template <unsigned N> constexpr inline bool isInt(int64_t x) {
293 return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
295 // Template specializations to get better code for common cases.
296 template <> constexpr inline bool isInt<8>(int64_t x) {
297 return static_cast<int8_t>(x) == x;
299 template <> constexpr inline bool isInt<16>(int64_t x) {
300 return static_cast<int16_t>(x) == x;
302 template <> constexpr inline bool isInt<32>(int64_t x) {
303 return static_cast<int32_t>(x) == x;
306 /// isShiftedInt<N,S> - Checks if a signed integer is an N bit number shifted
308 template <unsigned N, unsigned S>
309 constexpr inline bool isShiftedInt(int64_t x) {
311 N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number.");
312 static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
313 return isInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
316 /// isUInt - Checks if an unsigned integer fits into the given bit width.
318 /// This is written as two functions rather than as simply
320 /// return N >= 64 || X < (UINT64_C(1) << N);
322 /// to keep MSVC from (incorrectly) warning on isUInt<64> that we're shifting
323 /// left too many places.
324 template <unsigned N>
325 constexpr inline typename std::enable_if<(N < 64), bool>::type
327 static_assert(N > 0, "isUInt<0> doesn't make sense");
328 return X < (UINT64_C(1) << (N));
330 template <unsigned N>
331 constexpr inline typename std::enable_if<N >= 64, bool>::type
336 // Template specializations to get better code for common cases.
337 template <> constexpr inline bool isUInt<8>(uint64_t x) {
338 return static_cast<uint8_t>(x) == x;
340 template <> constexpr inline bool isUInt<16>(uint64_t x) {
341 return static_cast<uint16_t>(x) == x;
343 template <> constexpr inline bool isUInt<32>(uint64_t x) {
344 return static_cast<uint32_t>(x) == x;
347 /// Checks if a unsigned integer is an N bit number shifted left by S.
348 template <unsigned N, unsigned S>
349 constexpr inline bool isShiftedUInt(uint64_t x) {
351 N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)");
352 static_assert(N + S <= 64,
353 "isShiftedUInt<N, S> with N + S > 64 is too wide.");
354 // Per the two static_asserts above, S must be strictly less than 64. So
355 // 1 << S is not undefined behavior.
356 return isUInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
359 /// Gets the maximum value for a N-bit unsigned integer.
360 inline uint64_t maxUIntN(uint64_t N) {
361 assert(N > 0 && N <= 64 && "integer width out of range");
363 // uint64_t(1) << 64 is undefined behavior, so we can't do
364 // (uint64_t(1) << N) - 1
365 // without checking first that N != 64. But this works and doesn't have a
367 return UINT64_MAX >> (64 - N);
370 /// Gets the minimum value for a N-bit signed integer.
371 inline int64_t minIntN(int64_t N) {
372 assert(N > 0 && N <= 64 && "integer width out of range");
374 return -(UINT64_C(1)<<(N-1));
377 /// Gets the maximum value for a N-bit signed integer.
378 inline int64_t maxIntN(int64_t N) {
379 assert(N > 0 && N <= 64 && "integer width out of range");
381 // This relies on two's complement wraparound when N == 64, so we convert to
382 // int64_t only at the very end to avoid UB.
383 return (UINT64_C(1) << (N - 1)) - 1;
386 /// isUIntN - Checks if an unsigned integer fits into the given (dynamic)
388 inline bool isUIntN(unsigned N, uint64_t x) {
389 return N >= 64 || x <= maxUIntN(N);
392 /// isIntN - Checks if an signed integer fits into the given (dynamic)
394 inline bool isIntN(unsigned N, int64_t x) {
395 return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
398 /// isMask_32 - This function returns true if the argument is a non-empty
399 /// sequence of ones starting at the least significant bit with the remainder
400 /// zero (32 bit version). Ex. isMask_32(0x0000FFFFU) == true.
401 constexpr inline bool isMask_32(uint32_t Value) {
402 return Value && ((Value + 1) & Value) == 0;
405 /// isMask_64 - This function returns true if the argument is a non-empty
406 /// sequence of ones starting at the least significant bit with the remainder
407 /// zero (64 bit version).
408 constexpr inline bool isMask_64(uint64_t Value) {
409 return Value && ((Value + 1) & Value) == 0;
412 /// isShiftedMask_32 - This function returns true if the argument contains a
413 /// non-empty sequence of ones with the remainder zero (32 bit version.)
414 /// Ex. isShiftedMask_32(0x0000FF00U) == true.
415 constexpr inline bool isShiftedMask_32(uint32_t Value) {
416 return Value && isMask_32((Value - 1) | Value);
419 /// isShiftedMask_64 - This function returns true if the argument contains a
420 /// non-empty sequence of ones with the remainder zero (64 bit version.)
421 constexpr inline bool isShiftedMask_64(uint64_t Value) {
422 return Value && isMask_64((Value - 1) | Value);
425 /// isPowerOf2_32 - This function returns true if the argument is a power of
426 /// two > 0. Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
427 constexpr inline bool isPowerOf2_32(uint32_t Value) {
428 return Value && !(Value & (Value - 1));
431 /// isPowerOf2_64 - This function returns true if the argument is a power of two
432 /// > 0 (64 bit edition.)
433 constexpr inline bool isPowerOf2_64(uint64_t Value) {
434 return Value && !(Value & (Value - int64_t(1L)));
437 /// ByteSwap_16 - This function returns a byte-swapped representation of the
438 /// 16-bit argument, Value.
439 inline uint16_t ByteSwap_16(uint16_t Value) {
440 return sys::SwapByteOrder_16(Value);
443 /// ByteSwap_32 - This function returns a byte-swapped representation of the
444 /// 32-bit argument, Value.
445 inline uint32_t ByteSwap_32(uint32_t Value) {
446 return sys::SwapByteOrder_32(Value);
449 /// ByteSwap_64 - This function returns a byte-swapped representation of the
450 /// 64-bit argument, Value.
451 inline uint64_t ByteSwap_64(uint64_t Value) {
452 return sys::SwapByteOrder_64(Value);
455 /// \brief Count the number of ones from the most significant bit to the first
458 /// Ex. CountLeadingOnes(0xFF0FFF00) == 8.
459 /// Only unsigned integral types are allowed.
461 /// \param ZB the behavior on an input of all ones. Only ZB_Width and
462 /// ZB_Undefined are valid arguments.
463 template <typename T>
464 std::size_t countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
465 static_assert(std::numeric_limits<T>::is_integer &&
466 !std::numeric_limits<T>::is_signed,
467 "Only unsigned integral types are allowed.");
468 return countLeadingZeros(~Value, ZB);
471 /// \brief Count the number of ones from the least significant bit to the first
474 /// Ex. countTrailingOnes(0x00FF00FF) == 8.
475 /// Only unsigned integral types are allowed.
477 /// \param ZB the behavior on an input of all ones. Only ZB_Width and
478 /// ZB_Undefined are valid arguments.
479 template <typename T>
480 std::size_t countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
481 static_assert(std::numeric_limits<T>::is_integer &&
482 !std::numeric_limits<T>::is_signed,
483 "Only unsigned integral types are allowed.");
484 return countTrailingZeros(~Value, ZB);
488 template <typename T, std::size_t SizeOfT> struct PopulationCounter {
489 static unsigned count(T Value) {
490 // Generic version, forward to 32 bits.
491 static_assert(SizeOfT <= 4, "Not implemented!");
493 return __builtin_popcount(Value);
496 v = v - ((v >> 1) & 0x55555555);
497 v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
498 return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
503 template <typename T> struct PopulationCounter<T, 8> {
504 static unsigned count(T Value) {
506 return __builtin_popcountll(Value);
509 v = v - ((v >> 1) & 0x5555555555555555ULL);
510 v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
511 v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
512 return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
516 } // namespace detail
518 /// \brief Count the number of set bits in a value.
519 /// Ex. countPopulation(0xF000F000) = 8
520 /// Returns 0 if the word is zero.
521 template <typename T>
522 inline unsigned countPopulation(T Value) {
523 static_assert(std::numeric_limits<T>::is_integer &&
524 !std::numeric_limits<T>::is_signed,
525 "Only unsigned integral types are allowed.");
526 return detail::PopulationCounter<T, sizeof(T)>::count(Value);
529 /// Log2 - This function returns the log base 2 of the specified value
530 inline double Log2(double Value) {
531 #if defined(__ANDROID_API__) && __ANDROID_API__ < 18
532 return __builtin_log(Value) / __builtin_log(2.0);
538 /// Log2_32 - This function returns the floor log base 2 of the specified value,
539 /// -1 if the value is zero. (32 bit edition.)
540 /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
541 inline unsigned Log2_32(uint32_t Value) {
542 return 31 - countLeadingZeros(Value);
545 /// Log2_64 - This function returns the floor log base 2 of the specified value,
546 /// -1 if the value is zero. (64 bit edition.)
547 inline unsigned Log2_64(uint64_t Value) {
548 return 63 - countLeadingZeros(Value);
551 /// Log2_32_Ceil - This function returns the ceil log base 2 of the specified
552 /// value, 32 if the value is zero. (32 bit edition).
553 /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
554 inline unsigned Log2_32_Ceil(uint32_t Value) {
555 return 32 - countLeadingZeros(Value - 1);
558 /// Log2_64_Ceil - This function returns the ceil log base 2 of the specified
559 /// value, 64 if the value is zero. (64 bit edition.)
560 inline unsigned Log2_64_Ceil(uint64_t Value) {
561 return 64 - countLeadingZeros(Value - 1);
564 /// GreatestCommonDivisor64 - Return the greatest common divisor of the two
565 /// values using Euclid's algorithm.
566 inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
575 /// BitsToDouble - This function takes a 64-bit integer and returns the bit
576 /// equivalent double.
577 inline double BitsToDouble(uint64_t Bits) {
579 static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
580 memcpy(&D, &Bits, sizeof(Bits));
584 /// BitsToFloat - This function takes a 32-bit integer and returns the bit
585 /// equivalent float.
586 inline float BitsToFloat(uint32_t Bits) {
588 static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
589 memcpy(&F, &Bits, sizeof(Bits));
593 /// DoubleToBits - This function takes a double and returns the bit
594 /// equivalent 64-bit integer. Note that copying doubles around
595 /// changes the bits of NaNs on some hosts, notably x86, so this
596 /// routine cannot be used if these bits are needed.
597 inline uint64_t DoubleToBits(double Double) {
599 static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
600 memcpy(&Bits, &Double, sizeof(Double));
604 /// FloatToBits - This function takes a float and returns the bit
605 /// equivalent 32-bit integer. Note that copying floats around
606 /// changes the bits of NaNs on some hosts, notably x86, so this
607 /// routine cannot be used if these bits are needed.
608 inline uint32_t FloatToBits(float Float) {
610 static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
611 memcpy(&Bits, &Float, sizeof(Float));
615 /// MinAlign - A and B are either alignments or offsets. Return the minimum
616 /// alignment that may be assumed after adding the two together.
617 constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) {
618 // The largest power of 2 that divides both A and B.
620 // Replace "-Value" by "1+~Value" in the following commented code to avoid
621 // MSVC warning C4146
622 // return (A | B) & -(A | B);
623 return (A | B) & (1 + ~(A | B));
626 /// \brief Aligns \c Addr to \c Alignment bytes, rounding up.
628 /// Alignment should be a power of two. This method rounds up, so
629 /// alignAddr(7, 4) == 8 and alignAddr(8, 4) == 8.
630 inline uintptr_t alignAddr(const void *Addr, size_t Alignment) {
631 assert(Alignment && isPowerOf2_64((uint64_t)Alignment) &&
632 "Alignment is not a power of two!");
634 assert((uintptr_t)Addr + Alignment - 1 >= (uintptr_t)Addr);
636 return (((uintptr_t)Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1));
639 /// \brief Returns the necessary adjustment for aligning \c Ptr to \c Alignment
640 /// bytes, rounding up.
641 inline size_t alignmentAdjustment(const void *Ptr, size_t Alignment) {
642 return alignAddr(Ptr, Alignment) - (uintptr_t)Ptr;
645 /// NextPowerOf2 - Returns the next power of two (in 64-bits)
646 /// that is strictly greater than A. Returns zero on overflow.
647 inline uint64_t NextPowerOf2(uint64_t A) {
657 /// Returns the power of two which is less than or equal to the given value.
658 /// Essentially, it is a floor operation across the domain of powers of two.
659 inline uint64_t PowerOf2Floor(uint64_t A) {
661 return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
664 /// Returns the power of two which is greater than or equal to the given value.
665 /// Essentially, it is a ceil operation across the domain of powers of two.
666 inline uint64_t PowerOf2Ceil(uint64_t A) {
669 return NextPowerOf2(A - 1);
672 /// Returns the next integer (mod 2**64) that is greater than or equal to
673 /// \p Value and is a multiple of \p Align. \p Align must be non-zero.
675 /// If non-zero \p Skew is specified, the return value will be a minimal
676 /// integer that is greater than or equal to \p Value and equal to
677 /// \p Align * N + \p Skew for some integer N. If \p Skew is larger than
678 /// \p Align, its value is adjusted to '\p Skew mod \p Align'.
682 /// alignTo(5, 8) = 8
683 /// alignTo(17, 8) = 24
684 /// alignTo(~0LL, 8) = 0
685 /// alignTo(321, 255) = 510
687 /// alignTo(5, 8, 7) = 7
688 /// alignTo(17, 8, 1) = 17
689 /// alignTo(~0LL, 8, 3) = 3
690 /// alignTo(321, 255, 42) = 552
692 inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
693 assert(Align != 0u && "Align can't be 0.");
695 return (Value + Align - 1 - Skew) / Align * Align + Skew;
698 /// Returns the next integer (mod 2**64) that is greater than or equal to
699 /// \p Value and is a multiple of \c Align. \c Align must be non-zero.
700 template <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) {
701 static_assert(Align != 0u, "Align must be non-zero");
702 return (Value + Align - 1) / Align * Align;
705 /// \c alignTo for contexts where a constant expression is required.
708 /// \todo FIXME: remove when \c constexpr becomes really \c constexpr
709 template <uint64_t Align>
711 static_assert(Align != 0u, "Align must be non-zero");
712 template <uint64_t Value>
714 static const uint64_t value = (Value + Align - 1) / Align * Align;
718 /// Returns the largest uint64_t less than or equal to \p Value and is
719 /// \p Skew mod \p Align. \p Align must be non-zero
720 inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
721 assert(Align != 0u && "Align can't be 0.");
723 return (Value - Skew) / Align * Align + Skew;
726 /// Returns the offset to the next integer (mod 2**64) that is greater than
727 /// or equal to \p Value and is a multiple of \p Align. \p Align must be
729 inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) {
730 return alignTo(Value, Align) - Value;
733 /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
734 /// Requires 0 < B <= 32.
735 template <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) {
736 static_assert(B > 0, "Bit width can't be 0.");
737 static_assert(B <= 32, "Bit width out of range.");
738 return int32_t(X << (32 - B)) >> (32 - B);
741 /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
742 /// Requires 0 < B < 32.
743 inline int32_t SignExtend32(uint32_t X, unsigned B) {
744 assert(B > 0 && "Bit width can't be 0.");
745 assert(B <= 32 && "Bit width out of range.");
746 return int32_t(X << (32 - B)) >> (32 - B);
749 /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
750 /// Requires 0 < B < 64.
751 template <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) {
752 static_assert(B > 0, "Bit width can't be 0.");
753 static_assert(B <= 64, "Bit width out of range.");
754 return int64_t(x << (64 - B)) >> (64 - B);
757 /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
758 /// Requires 0 < B < 64.
759 inline int64_t SignExtend64(uint64_t X, unsigned B) {
760 assert(B > 0 && "Bit width can't be 0.");
761 assert(B <= 64 && "Bit width out of range.");
762 return int64_t(X << (64 - B)) >> (64 - B);
765 /// Subtract two unsigned integers, X and Y, of type T and return the absolute
766 /// value of the result.
767 template <typename T>
768 typename std::enable_if<std::is_unsigned<T>::value, T>::type
769 AbsoluteDifference(T X, T Y) {
770 return std::max(X, Y) - std::min(X, Y);
773 /// Add two unsigned integers, X and Y, of type T. Clamp the result to the
774 /// maximum representable value of T on overflow. ResultOverflowed indicates if
775 /// the result is larger than the maximum representable value of type T.
776 template <typename T>
777 typename std::enable_if<std::is_unsigned<T>::value, T>::type
778 SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
780 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
781 // Hacker's Delight, p. 29
783 Overflowed = (Z < X || Z < Y);
785 return std::numeric_limits<T>::max();
790 /// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the
791 /// maximum representable value of T on overflow. ResultOverflowed indicates if
792 /// the result is larger than the maximum representable value of type T.
793 template <typename T>
794 typename std::enable_if<std::is_unsigned<T>::value, T>::type
795 SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
797 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
799 // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
800 // because it fails for uint16_t (where multiplication can have undefined
801 // behavior due to promotion to int), and requires a division in addition
802 // to the multiplication.
806 // Log2(Z) would be either Log2Z or Log2Z + 1.
807 // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
808 // will necessarily be less than Log2Max as desired.
809 int Log2Z = Log2_64(X) + Log2_64(Y);
810 const T Max = std::numeric_limits<T>::max();
811 int Log2Max = Log2_64(Max);
812 if (Log2Z < Log2Max) {
815 if (Log2Z > Log2Max) {
820 // We're going to use the top bit, and maybe overflow one
821 // bit past it. Multiply all but the bottom bit then add
822 // that on at the end.
824 if (Z & ~(Max >> 1)) {
830 return SaturatingAdd(Z, Y, ResultOverflowed);
835 /// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
836 /// the product. Clamp the result to the maximum representable value of T on
837 /// overflow. ResultOverflowed indicates if the result is larger than the
838 /// maximum representable value of type T.
839 template <typename T>
840 typename std::enable_if<std::is_unsigned<T>::value, T>::type
841 SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
843 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
845 T Product = SaturatingMultiply(X, Y, &Overflowed);
849 return SaturatingAdd(A, Product, &Overflowed);
852 /// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
853 extern const float huge_valf;
854 } // End llvm namespace