Home | History | Annotate | Download | only in Support
      1 //===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This file contains some functions that are useful for math stuff.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_SUPPORT_MATHEXTRAS_H
     15 #define LLVM_SUPPORT_MATHEXTRAS_H
     16 
     17 #include "llvm/Support/Compiler.h"
     18 #include "llvm/Support/SwapByteOrder.h"
     19 #include <algorithm>
     20 #include <cassert>
     21 #include <cstring>
     22 #include <type_traits>
     23 #include <limits>
     24 
     25 #ifdef _MSC_VER
     26 #include <intrin.h>
     27 #endif
     28 
     29 #ifdef __ANDROID_NDK__
     30 #include <android/api-level.h>
     31 #endif
     32 
     33 namespace llvm {
     34 /// \brief The behavior an operation has on an input of 0.
     35 enum ZeroBehavior {
     36   /// \brief The returned value is undefined.
     37   ZB_Undefined,
     38   /// \brief The returned value is numeric_limits<T>::max()
     39   ZB_Max,
     40   /// \brief The returned value is numeric_limits<T>::digits
     41   ZB_Width
     42 };
     43 
     44 namespace detail {
     45 template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
     46   static std::size_t count(T Val, ZeroBehavior) {
     47     if (!Val)
     48       return std::numeric_limits<T>::digits;
     49     if (Val & 0x1)
     50       return 0;
     51 
     52     // Bisection method.
     53     std::size_t ZeroBits = 0;
     54     T Shift = std::numeric_limits<T>::digits >> 1;
     55     T Mask = std::numeric_limits<T>::max() >> Shift;
     56     while (Shift) {
     57       if ((Val & Mask) == 0) {
     58         Val >>= Shift;
     59         ZeroBits |= Shift;
     60       }
     61       Shift >>= 1;
     62       Mask >>= Shift;
     63     }
     64     return ZeroBits;
     65   }
     66 };
     67 
     68 #if __GNUC__ >= 4 || defined(_MSC_VER)
     69 template <typename T> struct TrailingZerosCounter<T, 4> {
     70   static std::size_t count(T Val, ZeroBehavior ZB) {
     71     if (ZB != ZB_Undefined && Val == 0)
     72       return 32;
     73 
     74 #if __has_builtin(__builtin_ctz) || LLVM_GNUC_PREREQ(4, 0, 0)
     75     return __builtin_ctz(Val);
     76 #elif defined(_MSC_VER)
     77     unsigned long Index;
     78     _BitScanForward(&Index, Val);
     79     return Index;
     80 #endif
     81   }
     82 };
     83 
     84 #if !defined(_MSC_VER) || defined(_M_X64)
     85 template <typename T> struct TrailingZerosCounter<T, 8> {
     86   static std::size_t count(T Val, ZeroBehavior ZB) {
     87     if (ZB != ZB_Undefined && Val == 0)
     88       return 64;
     89 
     90 #if __has_builtin(__builtin_ctzll) || LLVM_GNUC_PREREQ(4, 0, 0)
     91     return __builtin_ctzll(Val);
     92 #elif defined(_MSC_VER)
     93     unsigned long Index;
     94     _BitScanForward64(&Index, Val);
     95     return Index;
     96 #endif
     97   }
     98 };
     99 #endif
    100 #endif
    101 } // namespace detail
    102 
    103 /// \brief Count number of 0's from the least significant bit to the most
    104 ///   stopping at the first 1.
    105 ///
    106 /// Only unsigned integral types are allowed.
    107 ///
    108 /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
    109 ///   valid arguments.
    110 template <typename T>
    111 std::size_t countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
    112   static_assert(std::numeric_limits<T>::is_integer &&
    113                     !std::numeric_limits<T>::is_signed,
    114                 "Only unsigned integral types are allowed.");
    115   return detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
    116 }
    117 
    118 namespace detail {
    119 template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
    120   static std::size_t count(T Val, ZeroBehavior) {
    121     if (!Val)
    122       return std::numeric_limits<T>::digits;
    123 
    124     // Bisection method.
    125     std::size_t ZeroBits = 0;
    126     for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
    127       T Tmp = Val >> Shift;
    128       if (Tmp)
    129         Val = Tmp;
    130       else
    131         ZeroBits |= Shift;
    132     }
    133     return ZeroBits;
    134   }
    135 };
    136 
    137 #if __GNUC__ >= 4 || defined(_MSC_VER)
    138 template <typename T> struct LeadingZerosCounter<T, 4> {
    139   static std::size_t count(T Val, ZeroBehavior ZB) {
    140     if (ZB != ZB_Undefined && Val == 0)
    141       return 32;
    142 
    143 #if __has_builtin(__builtin_clz) || LLVM_GNUC_PREREQ(4, 0, 0)
    144     return __builtin_clz(Val);
    145 #elif defined(_MSC_VER)
    146     unsigned long Index;
    147     _BitScanReverse(&Index, Val);
    148     return Index ^ 31;
    149 #endif
    150   }
    151 };
    152 
    153 #if !defined(_MSC_VER) || defined(_M_X64)
    154 template <typename T> struct LeadingZerosCounter<T, 8> {
    155   static std::size_t count(T Val, ZeroBehavior ZB) {
    156     if (ZB != ZB_Undefined && Val == 0)
    157       return 64;
    158 
    159 #if __has_builtin(__builtin_clzll) || LLVM_GNUC_PREREQ(4, 0, 0)
    160     return __builtin_clzll(Val);
    161 #elif defined(_MSC_VER)
    162     unsigned long Index;
    163     _BitScanReverse64(&Index, Val);
    164     return Index ^ 63;
    165 #endif
    166   }
    167 };
    168 #endif
    169 #endif
    170 } // namespace detail
    171 
    172 /// \brief Count number of 0's from the most significant bit to the least
    173 ///   stopping at the first 1.
    174 ///
    175 /// Only unsigned integral types are allowed.
    176 ///
    177 /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
    178 ///   valid arguments.
    179 template <typename T>
    180 std::size_t countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
    181   static_assert(std::numeric_limits<T>::is_integer &&
    182                     !std::numeric_limits<T>::is_signed,
    183                 "Only unsigned integral types are allowed.");
    184   return detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
    185 }
    186 
    187 /// \brief Get the index of the first set bit starting from the least
    188 ///   significant bit.
    189 ///
    190 /// Only unsigned integral types are allowed.
    191 ///
    192 /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
    193 ///   valid arguments.
    194 template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
    195   if (ZB == ZB_Max && Val == 0)
    196     return std::numeric_limits<T>::max();
    197 
    198   return countTrailingZeros(Val, ZB_Undefined);
    199 }
    200 
    201 /// \brief Get the index of the last set bit starting from the least
    202 ///   significant bit.
    203 ///
    204 /// Only unsigned integral types are allowed.
    205 ///
    206 /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
    207 ///   valid arguments.
    208 template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
    209   if (ZB == ZB_Max && Val == 0)
    210     return std::numeric_limits<T>::max();
    211 
    212   // Use ^ instead of - because both gcc and llvm can remove the associated ^
    213   // in the __builtin_clz intrinsic on x86.
    214   return countLeadingZeros(Val, ZB_Undefined) ^
    215          (std::numeric_limits<T>::digits - 1);
    216 }
    217 
    218 /// \brief Macro compressed bit reversal table for 256 bits.
    219 ///
    220 /// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
    221 static const unsigned char BitReverseTable256[256] = {
    222 #define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
    223 #define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
    224 #define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
    225   R6(0), R6(2), R6(1), R6(3)
    226 #undef R2
    227 #undef R4
    228 #undef R6
    229 };
    230 
    231 /// \brief Reverse the bits in \p Val.
    232 template <typename T>
    233 T reverseBits(T Val) {
    234   unsigned char in[sizeof(Val)];
    235   unsigned char out[sizeof(Val)];
    236   std::memcpy(in, &Val, sizeof(Val));
    237   for (unsigned i = 0; i < sizeof(Val); ++i)
    238     out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
    239   std::memcpy(&Val, out, sizeof(Val));
    240   return Val;
    241 }
    242 
    243 // NOTE: The following support functions use the _32/_64 extensions instead of
    244 // type overloading so that signed and unsigned integers can be used without
    245 // ambiguity.
    246 
    247 /// Hi_32 - This function returns the high 32 bits of a 64 bit value.
    248 constexpr inline uint32_t Hi_32(uint64_t Value) {
    249   return static_cast<uint32_t>(Value >> 32);
    250 }
    251 
    252 /// Lo_32 - This function returns the low 32 bits of a 64 bit value.
    253 constexpr inline uint32_t Lo_32(uint64_t Value) {
    254   return static_cast<uint32_t>(Value);
    255 }
    256 
    257 /// Make_64 - This functions makes a 64-bit integer from a high / low pair of
    258 ///           32-bit integers.
    259 constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) {
    260   return ((uint64_t)High << 32) | (uint64_t)Low;
    261 }
    262 
    263 /// isInt - Checks if an integer fits into the given bit width.
    264 template <unsigned N> constexpr inline bool isInt(int64_t x) {
    265   return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
    266 }
    267 // Template specializations to get better code for common cases.
    268 template <> constexpr inline bool isInt<8>(int64_t x) {
    269   return static_cast<int8_t>(x) == x;
    270 }
    271 template <> constexpr inline bool isInt<16>(int64_t x) {
    272   return static_cast<int16_t>(x) == x;
    273 }
    274 template <> constexpr inline bool isInt<32>(int64_t x) {
    275   return static_cast<int32_t>(x) == x;
    276 }
    277 
    278 /// isShiftedInt<N,S> - Checks if a signed integer is an N bit number shifted
    279 ///                     left by S.
    280 template <unsigned N, unsigned S>
    281 constexpr inline bool isShiftedInt(int64_t x) {
    282   static_assert(
    283       N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number.");
    284   static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
    285   return isInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
    286 }
    287 
    288 /// isUInt - Checks if an unsigned integer fits into the given bit width.
    289 ///
    290 /// This is written as two functions rather than as simply
    291 ///
    292 ///   return N >= 64 || X < (UINT64_C(1) << N);
    293 ///
    294 /// to keep MSVC from (incorrectly) warning on isUInt<64> that we're shifting
    295 /// left too many places.
    296 template <unsigned N>
    297 constexpr inline typename std::enable_if<(N < 64), bool>::type
    298 isUInt(uint64_t X) {
    299   static_assert(N > 0, "isUInt<0> doesn't make sense");
    300   return X < (UINT64_C(1) << (N));
    301 }
    302 template <unsigned N>
    303 constexpr inline typename std::enable_if<N >= 64, bool>::type
    304 isUInt(uint64_t X) {
    305   return true;
    306 }
    307 
    308 // Template specializations to get better code for common cases.
    309 template <> constexpr inline bool isUInt<8>(uint64_t x) {
    310   return static_cast<uint8_t>(x) == x;
    311 }
    312 template <> constexpr inline bool isUInt<16>(uint64_t x) {
    313   return static_cast<uint16_t>(x) == x;
    314 }
    315 template <> constexpr inline bool isUInt<32>(uint64_t x) {
    316   return static_cast<uint32_t>(x) == x;
    317 }
    318 
    319 /// Checks if a unsigned integer is an N bit number shifted left by S.
    320 template <unsigned N, unsigned S>
    321 constexpr inline bool isShiftedUInt(uint64_t x) {
    322   static_assert(
    323       N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)");
    324   static_assert(N + S <= 64,
    325                 "isShiftedUInt<N, S> with N + S > 64 is too wide.");
    326   // Per the two static_asserts above, S must be strictly less than 64.  So
    327   // 1 << S is not undefined behavior.
    328   return isUInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
    329 }
    330 
    331 /// Gets the maximum value for a N-bit unsigned integer.
    332 inline uint64_t maxUIntN(uint64_t N) {
    333   assert(N > 0 && N <= 64 && "integer width out of range");
    334 
    335   // uint64_t(1) << 64 is undefined behavior, so we can't do
    336   //   (uint64_t(1) << N) - 1
    337   // without checking first that N != 64.  But this works and doesn't have a
    338   // branch.
    339   return UINT64_MAX >> (64 - N);
    340 }
    341 
    342 /// Gets the minimum value for a N-bit signed integer.
    343 inline int64_t minIntN(int64_t N) {
    344   assert(N > 0 && N <= 64 && "integer width out of range");
    345 
    346   return -(UINT64_C(1)<<(N-1));
    347 }
    348 
    349 /// Gets the maximum value for a N-bit signed integer.
    350 inline int64_t maxIntN(int64_t N) {
    351   assert(N > 0 && N <= 64 && "integer width out of range");
    352 
    353   // This relies on two's complement wraparound when N == 64, so we convert to
    354   // int64_t only at the very end to avoid UB.
    355   return (UINT64_C(1) << (N - 1)) - 1;
    356 }
    357 
    358 /// isUIntN - Checks if an unsigned integer fits into the given (dynamic)
    359 /// bit width.
    360 inline bool isUIntN(unsigned N, uint64_t x) {
    361   return N >= 64 || x <= maxUIntN(N);
    362 }
    363 
    364 /// isIntN - Checks if an signed integer fits into the given (dynamic)
    365 /// bit width.
    366 inline bool isIntN(unsigned N, int64_t x) {
    367   return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
    368 }
    369 
    370 /// isMask_32 - This function returns true if the argument is a non-empty
    371 /// sequence of ones starting at the least significant bit with the remainder
    372 /// zero (32 bit version).  Ex. isMask_32(0x0000FFFFU) == true.
    373 constexpr inline bool isMask_32(uint32_t Value) {
    374   return Value && ((Value + 1) & Value) == 0;
    375 }
    376 
    377 /// isMask_64 - This function returns true if the argument is a non-empty
    378 /// sequence of ones starting at the least significant bit with the remainder
    379 /// zero (64 bit version).
    380 constexpr inline bool isMask_64(uint64_t Value) {
    381   return Value && ((Value + 1) & Value) == 0;
    382 }
    383 
    384 /// isShiftedMask_32 - This function returns true if the argument contains a
    385 /// non-empty sequence of ones with the remainder zero (32 bit version.)
    386 /// Ex. isShiftedMask_32(0x0000FF00U) == true.
    387 constexpr inline bool isShiftedMask_32(uint32_t Value) {
    388   return Value && isMask_32((Value - 1) | Value);
    389 }
    390 
    391 /// isShiftedMask_64 - This function returns true if the argument contains a
    392 /// non-empty sequence of ones with the remainder zero (64 bit version.)
    393 constexpr inline bool isShiftedMask_64(uint64_t Value) {
    394   return Value && isMask_64((Value - 1) | Value);
    395 }
    396 
    397 /// isPowerOf2_32 - This function returns true if the argument is a power of
    398 /// two > 0. Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
    399 constexpr inline bool isPowerOf2_32(uint32_t Value) {
    400   return Value && !(Value & (Value - 1));
    401 }
    402 
    403 /// isPowerOf2_64 - This function returns true if the argument is a power of two
    404 /// > 0 (64 bit edition.)
    405 constexpr inline bool isPowerOf2_64(uint64_t Value) {
    406   return Value && !(Value & (Value - int64_t(1L)));
    407 }
    408 
    409 /// ByteSwap_16 - This function returns a byte-swapped representation of the
    410 /// 16-bit argument, Value.
    411 inline uint16_t ByteSwap_16(uint16_t Value) {
    412   return sys::SwapByteOrder_16(Value);
    413 }
    414 
    415 /// ByteSwap_32 - This function returns a byte-swapped representation of the
    416 /// 32-bit argument, Value.
    417 inline uint32_t ByteSwap_32(uint32_t Value) {
    418   return sys::SwapByteOrder_32(Value);
    419 }
    420 
    421 /// ByteSwap_64 - This function returns a byte-swapped representation of the
    422 /// 64-bit argument, Value.
    423 inline uint64_t ByteSwap_64(uint64_t Value) {
    424   return sys::SwapByteOrder_64(Value);
    425 }
    426 
    427 /// \brief Count the number of ones from the most significant bit to the first
    428 /// zero bit.
    429 ///
    430 /// Ex. CountLeadingOnes(0xFF0FFF00) == 8.
    431 /// Only unsigned integral types are allowed.
    432 ///
    433 /// \param ZB the behavior on an input of all ones. Only ZB_Width and
    434 /// ZB_Undefined are valid arguments.
    435 template <typename T>
    436 std::size_t countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
    437   static_assert(std::numeric_limits<T>::is_integer &&
    438                     !std::numeric_limits<T>::is_signed,
    439                 "Only unsigned integral types are allowed.");
    440   return countLeadingZeros(~Value, ZB);
    441 }
    442 
    443 /// \brief Count the number of ones from the least significant bit to the first
    444 /// zero bit.
    445 ///
    446 /// Ex. countTrailingOnes(0x00FF00FF) == 8.
    447 /// Only unsigned integral types are allowed.
    448 ///
    449 /// \param ZB the behavior on an input of all ones. Only ZB_Width and
    450 /// ZB_Undefined are valid arguments.
    451 template <typename T>
    452 std::size_t countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
    453   static_assert(std::numeric_limits<T>::is_integer &&
    454                     !std::numeric_limits<T>::is_signed,
    455                 "Only unsigned integral types are allowed.");
    456   return countTrailingZeros(~Value, ZB);
    457 }
    458 
    459 namespace detail {
    460 template <typename T, std::size_t SizeOfT> struct PopulationCounter {
    461   static unsigned count(T Value) {
    462     // Generic version, forward to 32 bits.
    463     static_assert(SizeOfT <= 4, "Not implemented!");
    464 #if __GNUC__ >= 4
    465     return __builtin_popcount(Value);
    466 #else
    467     uint32_t v = Value;
    468     v = v - ((v >> 1) & 0x55555555);
    469     v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
    470     return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
    471 #endif
    472   }
    473 };
    474 
    475 template <typename T> struct PopulationCounter<T, 8> {
    476   static unsigned count(T Value) {
    477 #if __GNUC__ >= 4
    478     return __builtin_popcountll(Value);
    479 #else
    480     uint64_t v = Value;
    481     v = v - ((v >> 1) & 0x5555555555555555ULL);
    482     v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
    483     v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
    484     return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
    485 #endif
    486   }
    487 };
    488 } // namespace detail
    489 
    490 /// \brief Count the number of set bits in a value.
    491 /// Ex. countPopulation(0xF000F000) = 8
    492 /// Returns 0 if the word is zero.
    493 template <typename T>
    494 inline unsigned countPopulation(T Value) {
    495   static_assert(std::numeric_limits<T>::is_integer &&
    496                     !std::numeric_limits<T>::is_signed,
    497                 "Only unsigned integral types are allowed.");
    498   return detail::PopulationCounter<T, sizeof(T)>::count(Value);
    499 }
    500 
    501 /// Log2 - This function returns the log base 2 of the specified value
    502 inline double Log2(double Value) {
    503 #if defined(__ANDROID_API__) && __ANDROID_API__ < 18
    504   return __builtin_log(Value) / __builtin_log(2.0);
    505 #else
    506   return log2(Value);
    507 #endif
    508 }
    509 
    510 /// Log2_32 - This function returns the floor log base 2 of the specified value,
    511 /// -1 if the value is zero. (32 bit edition.)
    512 /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
    513 inline unsigned Log2_32(uint32_t Value) {
    514   return 31 - countLeadingZeros(Value);
    515 }
    516 
    517 /// Log2_64 - This function returns the floor log base 2 of the specified value,
    518 /// -1 if the value is zero. (64 bit edition.)
    519 inline unsigned Log2_64(uint64_t Value) {
    520   return 63 - countLeadingZeros(Value);
    521 }
    522 
    523 /// Log2_32_Ceil - This function returns the ceil log base 2 of the specified
    524 /// value, 32 if the value is zero. (32 bit edition).
    525 /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
    526 inline unsigned Log2_32_Ceil(uint32_t Value) {
    527   return 32 - countLeadingZeros(Value - 1);
    528 }
    529 
    530 /// Log2_64_Ceil - This function returns the ceil log base 2 of the specified
    531 /// value, 64 if the value is zero. (64 bit edition.)
    532 inline unsigned Log2_64_Ceil(uint64_t Value) {
    533   return 64 - countLeadingZeros(Value - 1);
    534 }
    535 
    536 /// GreatestCommonDivisor64 - Return the greatest common divisor of the two
    537 /// values using Euclid's algorithm.
    538 inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
    539   while (B) {
    540     uint64_t T = B;
    541     B = A % B;
    542     A = T;
    543   }
    544   return A;
    545 }
    546 
    547 /// BitsToDouble - This function takes a 64-bit integer and returns the bit
    548 /// equivalent double.
    549 inline double BitsToDouble(uint64_t Bits) {
    550   union {
    551     uint64_t L;
    552     double D;
    553   } T;
    554   T.L = Bits;
    555   return T.D;
    556 }
    557 
    558 /// BitsToFloat - This function takes a 32-bit integer and returns the bit
    559 /// equivalent float.
    560 inline float BitsToFloat(uint32_t Bits) {
    561   union {
    562     uint32_t I;
    563     float F;
    564   } T;
    565   T.I = Bits;
    566   return T.F;
    567 }
    568 
    569 /// DoubleToBits - This function takes a double and returns the bit
    570 /// equivalent 64-bit integer.  Note that copying doubles around
    571 /// changes the bits of NaNs on some hosts, notably x86, so this
    572 /// routine cannot be used if these bits are needed.
    573 inline uint64_t DoubleToBits(double Double) {
    574   union {
    575     uint64_t L;
    576     double D;
    577   } T;
    578   T.D = Double;
    579   return T.L;
    580 }
    581 
    582 /// FloatToBits - This function takes a float and returns the bit
    583 /// equivalent 32-bit integer.  Note that copying floats around
    584 /// changes the bits of NaNs on some hosts, notably x86, so this
    585 /// routine cannot be used if these bits are needed.
    586 inline uint32_t FloatToBits(float Float) {
    587   union {
    588     uint32_t I;
    589     float F;
    590   } T;
    591   T.F = Float;
    592   return T.I;
    593 }
    594 
    595 /// MinAlign - A and B are either alignments or offsets.  Return the minimum
    596 /// alignment that may be assumed after adding the two together.
    597 constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) {
    598   // The largest power of 2 that divides both A and B.
    599   //
    600   // Replace "-Value" by "1+~Value" in the following commented code to avoid
    601   // MSVC warning C4146
    602   //    return (A | B) & -(A | B);
    603   return (A | B) & (1 + ~(A | B));
    604 }
    605 
    606 /// \brief Aligns \c Addr to \c Alignment bytes, rounding up.
    607 ///
    608 /// Alignment should be a power of two.  This method rounds up, so
    609 /// alignAddr(7, 4) == 8 and alignAddr(8, 4) == 8.
    610 inline uintptr_t alignAddr(const void *Addr, size_t Alignment) {
    611   assert(Alignment && isPowerOf2_64((uint64_t)Alignment) &&
    612          "Alignment is not a power of two!");
    613 
    614   assert((uintptr_t)Addr + Alignment - 1 >= (uintptr_t)Addr);
    615 
    616   return (((uintptr_t)Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1));
    617 }
    618 
    619 /// \brief Returns the necessary adjustment for aligning \c Ptr to \c Alignment
    620 /// bytes, rounding up.
    621 inline size_t alignmentAdjustment(const void *Ptr, size_t Alignment) {
    622   return alignAddr(Ptr, Alignment) - (uintptr_t)Ptr;
    623 }
    624 
    625 /// NextPowerOf2 - Returns the next power of two (in 64-bits)
    626 /// that is strictly greater than A.  Returns zero on overflow.
    627 inline uint64_t NextPowerOf2(uint64_t A) {
    628   A |= (A >> 1);
    629   A |= (A >> 2);
    630   A |= (A >> 4);
    631   A |= (A >> 8);
    632   A |= (A >> 16);
    633   A |= (A >> 32);
    634   return A + 1;
    635 }
    636 
    637 /// Returns the power of two which is less than or equal to the given value.
    638 /// Essentially, it is a floor operation across the domain of powers of two.
    639 inline uint64_t PowerOf2Floor(uint64_t A) {
    640   if (!A) return 0;
    641   return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
    642 }
    643 
    644 /// Returns the power of two which is greater than or equal to the given value.
    645 /// Essentially, it is a ceil operation across the domain of powers of two.
    646 inline uint64_t PowerOf2Ceil(uint64_t A) {
    647   if (!A)
    648     return 0;
    649   return NextPowerOf2(A - 1);
    650 }
    651 
    652 /// Returns the next integer (mod 2**64) that is greater than or equal to
    653 /// \p Value and is a multiple of \p Align. \p Align must be non-zero.
    654 ///
    655 /// If non-zero \p Skew is specified, the return value will be a minimal
    656 /// integer that is greater than or equal to \p Value and equal to
    657 /// \p Align * N + \p Skew for some integer N. If \p Skew is larger than
    658 /// \p Align, its value is adjusted to '\p Skew mod \p Align'.
    659 ///
    660 /// Examples:
    661 /// \code
    662 ///   alignTo(5, 8) = 8
    663 ///   alignTo(17, 8) = 24
    664 ///   alignTo(~0LL, 8) = 0
    665 ///   alignTo(321, 255) = 510
    666 ///
    667 ///   alignTo(5, 8, 7) = 7
    668 ///   alignTo(17, 8, 1) = 17
    669 ///   alignTo(~0LL, 8, 3) = 3
    670 ///   alignTo(321, 255, 42) = 552
    671 /// \endcode
    672 inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
    673   assert(Align != 0u && "Align can't be 0.");
    674   Skew %= Align;
    675   return (Value + Align - 1 - Skew) / Align * Align + Skew;
    676 }
    677 
    678 /// Returns the next integer (mod 2**64) that is greater than or equal to
    679 /// \p Value and is a multiple of \c Align. \c Align must be non-zero.
    680 template <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) {
    681   static_assert(Align != 0u, "Align must be non-zero");
    682   return (Value + Align - 1) / Align * Align;
    683 }
    684 
    685 /// \c alignTo for contexts where a constant expression is required.
    686 /// \sa alignTo
    687 ///
    688 /// \todo FIXME: remove when \c constexpr becomes really \c constexpr
    689 template <uint64_t Align>
    690 struct AlignTo {
    691   static_assert(Align != 0u, "Align must be non-zero");
    692   template <uint64_t Value>
    693   struct from_value {
    694     static const uint64_t value = (Value + Align - 1) / Align * Align;
    695   };
    696 };
    697 
    698 /// Returns the largest uint64_t less than or equal to \p Value and is
    699 /// \p Skew mod \p Align. \p Align must be non-zero
    700 inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
    701   assert(Align != 0u && "Align can't be 0.");
    702   Skew %= Align;
    703   return (Value - Skew) / Align * Align + Skew;
    704 }
    705 
    706 /// Returns the offset to the next integer (mod 2**64) that is greater than
    707 /// or equal to \p Value and is a multiple of \p Align. \p Align must be
    708 /// non-zero.
    709 inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) {
    710   return alignTo(Value, Align) - Value;
    711 }
    712 
    713 /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
    714 /// Requires 0 < B <= 32.
    715 template <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) {
    716   static_assert(B > 0, "Bit width can't be 0.");
    717   static_assert(B <= 32, "Bit width out of range.");
    718   return int32_t(X << (32 - B)) >> (32 - B);
    719 }
    720 
    721 /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
    722 /// Requires 0 < B < 32.
    723 inline int32_t SignExtend32(uint32_t X, unsigned B) {
    724   assert(B > 0 && "Bit width can't be 0.");
    725   assert(B <= 32 && "Bit width out of range.");
    726   return int32_t(X << (32 - B)) >> (32 - B);
    727 }
    728 
    729 /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
    730 /// Requires 0 < B < 64.
    731 template <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) {
    732   static_assert(B > 0, "Bit width can't be 0.");
    733   static_assert(B <= 64, "Bit width out of range.");
    734   return int64_t(x << (64 - B)) >> (64 - B);
    735 }
    736 
    737 /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
    738 /// Requires 0 < B < 64.
    739 inline int64_t SignExtend64(uint64_t X, unsigned B) {
    740   assert(B > 0 && "Bit width can't be 0.");
    741   assert(B <= 64 && "Bit width out of range.");
    742   return int64_t(X << (64 - B)) >> (64 - B);
    743 }
    744 
    745 /// Subtract two unsigned integers, X and Y, of type T and return the absolute
    746 /// value of the result.
    747 template <typename T>
    748 typename std::enable_if<std::is_unsigned<T>::value, T>::type
    749 AbsoluteDifference(T X, T Y) {
    750   return std::max(X, Y) - std::min(X, Y);
    751 }
    752 
    753 /// Add two unsigned integers, X and Y, of type T.  Clamp the result to the
    754 /// maximum representable value of T on overflow.  ResultOverflowed indicates if
    755 /// the result is larger than the maximum representable value of type T.
    756 template <typename T>
    757 typename std::enable_if<std::is_unsigned<T>::value, T>::type
    758 SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
    759   bool Dummy;
    760   bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
    761   // Hacker's Delight, p. 29
    762   T Z = X + Y;
    763   Overflowed = (Z < X || Z < Y);
    764   if (Overflowed)
    765     return std::numeric_limits<T>::max();
    766   else
    767     return Z;
    768 }
    769 
    770 /// Multiply two unsigned integers, X and Y, of type T.  Clamp the result to the
    771 /// maximum representable value of T on overflow.  ResultOverflowed indicates if
    772 /// the result is larger than the maximum representable value of type T.
    773 template <typename T>
    774 typename std::enable_if<std::is_unsigned<T>::value, T>::type
    775 SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
    776   bool Dummy;
    777   bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
    778 
    779   // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
    780   // because it fails for uint16_t (where multiplication can have undefined
    781   // behavior due to promotion to int), and requires a division in addition
    782   // to the multiplication.
    783 
    784   Overflowed = false;
    785 
    786   // Log2(Z) would be either Log2Z or Log2Z + 1.
    787   // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
    788   // will necessarily be less than Log2Max as desired.
    789   int Log2Z = Log2_64(X) + Log2_64(Y);
    790   const T Max = std::numeric_limits<T>::max();
    791   int Log2Max = Log2_64(Max);
    792   if (Log2Z < Log2Max) {
    793     return X * Y;
    794   }
    795   if (Log2Z > Log2Max) {
    796     Overflowed = true;
    797     return Max;
    798   }
    799 
    800   // We're going to use the top bit, and maybe overflow one
    801   // bit past it. Multiply all but the bottom bit then add
    802   // that on at the end.
    803   T Z = (X >> 1) * Y;
    804   if (Z & ~(Max >> 1)) {
    805     Overflowed = true;
    806     return Max;
    807   }
    808   Z <<= 1;
    809   if (X & 1)
    810     return SaturatingAdd(Z, Y, ResultOverflowed);
    811 
    812   return Z;
    813 }
    814 
    815 /// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
    816 /// the product. Clamp the result to the maximum representable value of T on
    817 /// overflow. ResultOverflowed indicates if the result is larger than the
    818 /// maximum representable value of type T.
    819 template <typename T>
    820 typename std::enable_if<std::is_unsigned<T>::value, T>::type
    821 SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
    822   bool Dummy;
    823   bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
    824 
    825   T Product = SaturatingMultiply(X, Y, &Overflowed);
    826   if (Overflowed)
    827     return Product;
    828 
    829   return SaturatingAdd(A, Product, &Overflowed);
    830 }
    831 
    832 /// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
    833 extern const float huge_valf;
    834 } // End llvm namespace
    835 
    836 #endif
    837