1193323Sed//===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===//
2193323Sed//
3353358Sdim// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim// See https://llvm.org/LICENSE.txt for license information.
5353358Sdim// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6193323Sed//
7193323Sed//===----------------------------------------------------------------------===//
8193323Sed//
9193323Sed// This file contains some functions that are useful for math stuff.
10193323Sed//
11193323Sed//===----------------------------------------------------------------------===//
12193323Sed
13193323Sed#ifndef LLVM_SUPPORT_MATHEXTRAS_H
14193323Sed#define LLVM_SUPPORT_MATHEXTRAS_H
15193323Sed
16261991Sdim#include "llvm/Support/Compiler.h"
17218893Sdim#include "llvm/Support/SwapByteOrder.h"
18309124Sdim#include <algorithm>
19276479Sdim#include <cassert>
20321369Sdim#include <climits>
21261991Sdim#include <cstring>
22321369Sdim#include <limits>
23276479Sdim#include <type_traits>
24261991Sdim
25288943Sdim#ifdef __ANDROID_NDK__
26288943Sdim#include <android/api-level.h>
27288943Sdim#endif
28288943Sdim
29341825Sdim#ifdef _MSC_VER
30341825Sdim// Declare these intrinsics manually rather including intrin.h. It's very
31341825Sdim// expensive, and MathExtras.h is popular.
32341825Sdim// #include <intrin.h>
33341825Sdimextern "C" {
34341825Sdimunsigned char _BitScanForward(unsigned long *_Index, unsigned long _Mask);
35341825Sdimunsigned char _BitScanForward64(unsigned long *_Index, unsigned __int64 _Mask);
36341825Sdimunsigned char _BitScanReverse(unsigned long *_Index, unsigned long _Mask);
37341825Sdimunsigned char _BitScanReverse64(unsigned long *_Index, unsigned __int64 _Mask);
38341825Sdim}
39341825Sdim#endif
40341825Sdim
41193323Sednamespace llvm {
42360784Sdim
43341825Sdim/// The behavior an operation has on an input of 0.
44261991Sdimenum ZeroBehavior {
45341825Sdim  /// The returned value is undefined.
46261991Sdim  ZB_Undefined,
47341825Sdim  /// The returned value is numeric_limits<T>::max()
48261991Sdim  ZB_Max,
49341825Sdim  /// The returned value is numeric_limits<T>::digits
50261991Sdim  ZB_Width
51261991Sdim};
52193323Sed
53360784Sdim/// Mathematical constants.
54360784Sdimnamespace numbers {
55360784Sdim// TODO: Track C++20 std::numbers.
56360784Sdim// TODO: Favor using the hexadecimal FP constants (requires C++17).
57360784Sdimconstexpr double e          = 2.7182818284590452354, // (0x1.5bf0a8b145749P+1) https://oeis.org/A001113
58360784Sdim                 egamma     = .57721566490153286061, // (0x1.2788cfc6fb619P-1) https://oeis.org/A001620
59360784Sdim                 ln2        = .69314718055994530942, // (0x1.62e42fefa39efP-1) https://oeis.org/A002162
60360784Sdim                 ln10       = 2.3025850929940456840, // (0x1.24bb1bbb55516P+1) https://oeis.org/A002392
61360784Sdim                 log2e      = 1.4426950408889634074, // (0x1.71547652b82feP+0)
62360784Sdim                 log10e     = .43429448190325182765, // (0x1.bcb7b1526e50eP-2)
63360784Sdim                 pi         = 3.1415926535897932385, // (0x1.921fb54442d18P+1) https://oeis.org/A000796
64360784Sdim                 inv_pi     = .31830988618379067154, // (0x1.45f306bc9c883P-2) https://oeis.org/A049541
65360784Sdim                 sqrtpi     = 1.7724538509055160273, // (0x1.c5bf891b4ef6bP+0) https://oeis.org/A002161
66360784Sdim                 inv_sqrtpi = .56418958354775628695, // (0x1.20dd750429b6dP-1) https://oeis.org/A087197
67360784Sdim                 sqrt2      = 1.4142135623730950488, // (0x1.6a09e667f3bcdP+0) https://oeis.org/A00219
68360784Sdim                 inv_sqrt2  = .70710678118654752440, // (0x1.6a09e667f3bcdP-1)
69360784Sdim                 sqrt3      = 1.7320508075688772935, // (0x1.bb67ae8584caaP+0) https://oeis.org/A002194
70360784Sdim                 inv_sqrt3  = .57735026918962576451, // (0x1.279a74590331cP-1)
71360784Sdim                 phi        = 1.6180339887498948482; // (0x1.9e3779b97f4a8P+0) https://oeis.org/A001622
72360784Sdimconstexpr float ef          = 2.71828183F, // (0x1.5bf0a8P+1) https://oeis.org/A001113
73360784Sdim                egammaf     = .577215665F, // (0x1.2788d0P-1) https://oeis.org/A001620
74360784Sdim                ln2f        = .693147181F, // (0x1.62e430P-1) https://oeis.org/A002162
75360784Sdim                ln10f       = 2.30258509F, // (0x1.26bb1cP+1) https://oeis.org/A002392
76360784Sdim                log2ef      = 1.44269504F, // (0x1.715476P+0)
77360784Sdim                log10ef     = .434294482F, // (0x1.bcb7b2P-2)
78360784Sdim                pif         = 3.14159265F, // (0x1.921fb6P+1) https://oeis.org/A000796
79360784Sdim                inv_pif     = .318309886F, // (0x1.45f306P-2) https://oeis.org/A049541
80360784Sdim                sqrtpif     = 1.77245385F, // (0x1.c5bf8aP+0) https://oeis.org/A002161
81360784Sdim                inv_sqrtpif = .564189584F, // (0x1.20dd76P-1) https://oeis.org/A087197
82360784Sdim                sqrt2f      = 1.41421356F, // (0x1.6a09e6P+0) https://oeis.org/A002193
83360784Sdim                inv_sqrt2f  = .707106781F, // (0x1.6a09e6P-1)
84360784Sdim                sqrt3f      = 1.73205081F, // (0x1.bb67aeP+0) https://oeis.org/A002194
85360784Sdim                inv_sqrt3f  = .577350269F, // (0x1.279a74P-1)
86360784Sdim                phif        = 1.61803399F; // (0x1.9e377aP+0) https://oeis.org/A001622
87360784Sdim} // namespace numbers
88360784Sdim
89288943Sdimnamespace detail {
90288943Sdimtemplate <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
91353358Sdim  static unsigned count(T Val, ZeroBehavior) {
92288943Sdim    if (!Val)
93288943Sdim      return std::numeric_limits<T>::digits;
94288943Sdim    if (Val & 0x1)
95288943Sdim      return 0;
96261991Sdim
97288943Sdim    // Bisection method.
98353358Sdim    unsigned ZeroBits = 0;
99288943Sdim    T Shift = std::numeric_limits<T>::digits >> 1;
100288943Sdim    T Mask = std::numeric_limits<T>::max() >> Shift;
101288943Sdim    while (Shift) {
102288943Sdim      if ((Val & Mask) == 0) {
103288943Sdim        Val >>= Shift;
104288943Sdim        ZeroBits |= Shift;
105288943Sdim      }
106288943Sdim      Shift >>= 1;
107288943Sdim      Mask >>= Shift;
108261991Sdim    }
109288943Sdim    return ZeroBits;
110261991Sdim  }
111288943Sdim};
112261991Sdim
113360784Sdim#if defined(__GNUC__) || defined(_MSC_VER)
114288943Sdimtemplate <typename T> struct TrailingZerosCounter<T, 4> {
115353358Sdim  static unsigned count(T Val, ZeroBehavior ZB) {
116288943Sdim    if (ZB != ZB_Undefined && Val == 0)
117288943Sdim      return 32;
118261991Sdim
119360784Sdim#if __has_builtin(__builtin_ctz) || defined(__GNUC__)
120288943Sdim    return __builtin_ctz(Val);
121296417Sdim#elif defined(_MSC_VER)
122288943Sdim    unsigned long Index;
123288943Sdim    _BitScanForward(&Index, Val);
124288943Sdim    return Index;
125261991Sdim#endif
126288943Sdim  }
127288943Sdim};
128261991Sdim
129261991Sdim#if !defined(_MSC_VER) || defined(_M_X64)
130288943Sdimtemplate <typename T> struct TrailingZerosCounter<T, 8> {
131353358Sdim  static unsigned count(T Val, ZeroBehavior ZB) {
132288943Sdim    if (ZB != ZB_Undefined && Val == 0)
133288943Sdim      return 64;
134261991Sdim
135360784Sdim#if __has_builtin(__builtin_ctzll) || defined(__GNUC__)
136288943Sdim    return __builtin_ctzll(Val);
137296417Sdim#elif defined(_MSC_VER)
138288943Sdim    unsigned long Index;
139288943Sdim    _BitScanForward64(&Index, Val);
140288943Sdim    return Index;
141261991Sdim#endif
142288943Sdim  }
143288943Sdim};
144261991Sdim#endif
145261991Sdim#endif
146288943Sdim} // namespace detail
147261991Sdim
148341825Sdim/// Count number of 0's from the least significant bit to the most
149261991Sdim///   stopping at the first 1.
150261991Sdim///
151261991Sdim/// Only unsigned integral types are allowed.
152261991Sdim///
153261991Sdim/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
154261991Sdim///   valid arguments.
155261991Sdimtemplate <typename T>
156353358Sdimunsigned countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
157288943Sdim  static_assert(std::numeric_limits<T>::is_integer &&
158288943Sdim                    !std::numeric_limits<T>::is_signed,
159288943Sdim                "Only unsigned integral types are allowed.");
160321369Sdim  return llvm::detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
161288943Sdim}
162261991Sdim
163288943Sdimnamespace detail {
164288943Sdimtemplate <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
165353358Sdim  static unsigned count(T Val, ZeroBehavior) {
166288943Sdim    if (!Val)
167288943Sdim      return std::numeric_limits<T>::digits;
168261991Sdim
169288943Sdim    // Bisection method.
170353358Sdim    unsigned ZeroBits = 0;
171288943Sdim    for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
172288943Sdim      T Tmp = Val >> Shift;
173288943Sdim      if (Tmp)
174288943Sdim        Val = Tmp;
175288943Sdim      else
176288943Sdim        ZeroBits |= Shift;
177288943Sdim    }
178288943Sdim    return ZeroBits;
179261991Sdim  }
180288943Sdim};
181261991Sdim
182360784Sdim#if defined(__GNUC__) || defined(_MSC_VER)
183288943Sdimtemplate <typename T> struct LeadingZerosCounter<T, 4> {
184353358Sdim  static unsigned count(T Val, ZeroBehavior ZB) {
185288943Sdim    if (ZB != ZB_Undefined && Val == 0)
186288943Sdim      return 32;
187261991Sdim
188360784Sdim#if __has_builtin(__builtin_clz) || defined(__GNUC__)
189288943Sdim    return __builtin_clz(Val);
190296417Sdim#elif defined(_MSC_VER)
191288943Sdim    unsigned long Index;
192288943Sdim    _BitScanReverse(&Index, Val);
193288943Sdim    return Index ^ 31;
194261991Sdim#endif
195288943Sdim  }
196288943Sdim};
197261991Sdim
198261991Sdim#if !defined(_MSC_VER) || defined(_M_X64)
199288943Sdimtemplate <typename T> struct LeadingZerosCounter<T, 8> {
200353358Sdim  static unsigned count(T Val, ZeroBehavior ZB) {
201288943Sdim    if (ZB != ZB_Undefined && Val == 0)
202288943Sdim      return 64;
203261991Sdim
204360784Sdim#if __has_builtin(__builtin_clzll) || defined(__GNUC__)
205288943Sdim    return __builtin_clzll(Val);
206296417Sdim#elif defined(_MSC_VER)
207288943Sdim    unsigned long Index;
208288943Sdim    _BitScanReverse64(&Index, Val);
209288943Sdim    return Index ^ 63;
210261991Sdim#endif
211288943Sdim  }
212288943Sdim};
213261991Sdim#endif
214261991Sdim#endif
215288943Sdim} // namespace detail
216261991Sdim
217341825Sdim/// Count number of 0's from the most significant bit to the least
218288943Sdim///   stopping at the first 1.
219288943Sdim///
220288943Sdim/// Only unsigned integral types are allowed.
221288943Sdim///
222288943Sdim/// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
223288943Sdim///   valid arguments.
224288943Sdimtemplate <typename T>
225353358Sdimunsigned countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
226288943Sdim  static_assert(std::numeric_limits<T>::is_integer &&
227288943Sdim                    !std::numeric_limits<T>::is_signed,
228288943Sdim                "Only unsigned integral types are allowed.");
229321369Sdim  return llvm::detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
230288943Sdim}
231288943Sdim
232341825Sdim/// Get the index of the first set bit starting from the least
233261991Sdim///   significant bit.
234261991Sdim///
235261991Sdim/// Only unsigned integral types are allowed.
236261991Sdim///
237261991Sdim/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
238261991Sdim///   valid arguments.
239288943Sdimtemplate <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
240261991Sdim  if (ZB == ZB_Max && Val == 0)
241261991Sdim    return std::numeric_limits<T>::max();
242261991Sdim
243261991Sdim  return countTrailingZeros(Val, ZB_Undefined);
244261991Sdim}
245261991Sdim
246341825Sdim/// Create a bitmask with the N right-most bits set to 1, and all other
247321369Sdim/// bits set to 0.  Only unsigned types are allowed.
248321369Sdimtemplate <typename T> T maskTrailingOnes(unsigned N) {
249321369Sdim  static_assert(std::is_unsigned<T>::value, "Invalid type!");
250321369Sdim  const unsigned Bits = CHAR_BIT * sizeof(T);
251321369Sdim  assert(N <= Bits && "Invalid bit index");
252321369Sdim  return N == 0 ? 0 : (T(-1) >> (Bits - N));
253321369Sdim}
254321369Sdim
255341825Sdim/// Create a bitmask with the N left-most bits set to 1, and all other
256321369Sdim/// bits set to 0.  Only unsigned types are allowed.
257321369Sdimtemplate <typename T> T maskLeadingOnes(unsigned N) {
258321369Sdim  return ~maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
259321369Sdim}
260321369Sdim
261341825Sdim/// Create a bitmask with the N right-most bits set to 0, and all other
262321369Sdim/// bits set to 1.  Only unsigned types are allowed.
263321369Sdimtemplate <typename T> T maskTrailingZeros(unsigned N) {
264321369Sdim  return maskLeadingOnes<T>(CHAR_BIT * sizeof(T) - N);
265321369Sdim}
266321369Sdim
267341825Sdim/// Create a bitmask with the N left-most bits set to 0, and all other
268321369Sdim/// bits set to 1.  Only unsigned types are allowed.
269321369Sdimtemplate <typename T> T maskLeadingZeros(unsigned N) {
270321369Sdim  return maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
271321369Sdim}
272321369Sdim
273341825Sdim/// Get the index of the last set bit starting from the least
274261991Sdim///   significant bit.
275261991Sdim///
276261991Sdim/// Only unsigned integral types are allowed.
277261991Sdim///
278261991Sdim/// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
279261991Sdim///   valid arguments.
280288943Sdimtemplate <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
281261991Sdim  if (ZB == ZB_Max && Val == 0)
282261991Sdim    return std::numeric_limits<T>::max();
283261991Sdim
284261991Sdim  // Use ^ instead of - because both gcc and llvm can remove the associated ^
285261991Sdim  // in the __builtin_clz intrinsic on x86.
286261991Sdim  return countLeadingZeros(Val, ZB_Undefined) ^
287261991Sdim         (std::numeric_limits<T>::digits - 1);
288261991Sdim}
289261991Sdim
290341825Sdim/// Macro compressed bit reversal table for 256 bits.
291261991Sdim///
292261991Sdim/// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
293261991Sdimstatic const unsigned char BitReverseTable256[256] = {
294261991Sdim#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
295261991Sdim#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
296261991Sdim#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
297261991Sdim  R6(0), R6(2), R6(1), R6(3)
298276479Sdim#undef R2
299276479Sdim#undef R4
300276479Sdim#undef R6
301261991Sdim};
302261991Sdim
303341825Sdim/// Reverse the bits in \p Val.
304261991Sdimtemplate <typename T>
305261991SdimT reverseBits(T Val) {
306261991Sdim  unsigned char in[sizeof(Val)];
307261991Sdim  unsigned char out[sizeof(Val)];
308261991Sdim  std::memcpy(in, &Val, sizeof(Val));
309261991Sdim  for (unsigned i = 0; i < sizeof(Val); ++i)
310261991Sdim    out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
311261991Sdim  std::memcpy(&Val, out, sizeof(Val));
312261991Sdim  return Val;
313261991Sdim}
314261991Sdim
315193323Sed// NOTE: The following support functions use the _32/_64 extensions instead of
316193323Sed// type overloading so that signed and unsigned integers can be used without
317193323Sed// ambiguity.
318193323Sed
319321369Sdim/// Return the high 32 bits of a 64 bit value.
320314564Sdimconstexpr inline uint32_t Hi_32(uint64_t Value) {
321193323Sed  return static_cast<uint32_t>(Value >> 32);
322193323Sed}
323193323Sed
324321369Sdim/// Return the low 32 bits of a 64 bit value.
325314564Sdimconstexpr inline uint32_t Lo_32(uint64_t Value) {
326193323Sed  return static_cast<uint32_t>(Value);
327193323Sed}
328193323Sed
329321369Sdim/// Make a 64-bit integer from a high / low pair of 32-bit integers.
330314564Sdimconstexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) {
331276479Sdim  return ((uint64_t)High << 32) | (uint64_t)Low;
332276479Sdim}
333276479Sdim
334321369Sdim/// Checks if an integer fits into the given bit width.
335314564Sdimtemplate <unsigned N> constexpr inline bool isInt(int64_t x) {
336206083Srdivacky  return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
337193323Sed}
338206083Srdivacky// Template specializations to get better code for common cases.
339314564Sdimtemplate <> constexpr inline bool isInt<8>(int64_t x) {
340206083Srdivacky  return static_cast<int8_t>(x) == x;
341193323Sed}
342314564Sdimtemplate <> constexpr inline bool isInt<16>(int64_t x) {
343206083Srdivacky  return static_cast<int16_t>(x) == x;
344193323Sed}
345314564Sdimtemplate <> constexpr inline bool isInt<32>(int64_t x) {
346206083Srdivacky  return static_cast<int32_t>(x) == x;
347193323Sed}
348193323Sed
349321369Sdim/// Checks if a signed integer is an N bit number shifted left by S.
350314564Sdimtemplate <unsigned N, unsigned S>
351314564Sdimconstexpr inline bool isShiftedInt(int64_t x) {
352309124Sdim  static_assert(
353309124Sdim      N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number.");
354309124Sdim  static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
355309124Sdim  return isInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
356234353Sdim}
357234353Sdim
358321369Sdim/// Checks if an unsigned integer fits into the given bit width.
359314564Sdim///
360314564Sdim/// This is written as two functions rather than as simply
361314564Sdim///
362314564Sdim///   return N >= 64 || X < (UINT64_C(1) << N);
363314564Sdim///
364314564Sdim/// to keep MSVC from (incorrectly) warning on isUInt<64> that we're shifting
365314564Sdim/// left too many places.
366314564Sdimtemplate <unsigned N>
367314564Sdimconstexpr inline typename std::enable_if<(N < 64), bool>::type
368314564SdimisUInt(uint64_t X) {
369314564Sdim  static_assert(N > 0, "isUInt<0> doesn't make sense");
370314564Sdim  return X < (UINT64_C(1) << (N));
371198090Srdivacky}
372314564Sdimtemplate <unsigned N>
373314564Sdimconstexpr inline typename std::enable_if<N >= 64, bool>::type
374314564SdimisUInt(uint64_t X) {
375314564Sdim  return true;
376314564Sdim}
377309124Sdim
378206083Srdivacky// Template specializations to get better code for common cases.
379314564Sdimtemplate <> constexpr inline bool isUInt<8>(uint64_t x) {
380206083Srdivacky  return static_cast<uint8_t>(x) == x;
381206083Srdivacky}
382314564Sdimtemplate <> constexpr inline bool isUInt<16>(uint64_t x) {
383206083Srdivacky  return static_cast<uint16_t>(x) == x;
384206083Srdivacky}
385314564Sdimtemplate <> constexpr inline bool isUInt<32>(uint64_t x) {
386206083Srdivacky  return static_cast<uint32_t>(x) == x;
387206083Srdivacky}
388198090Srdivacky
389309124Sdim/// Checks if a unsigned integer is an N bit number shifted left by S.
390314564Sdimtemplate <unsigned N, unsigned S>
391314564Sdimconstexpr inline bool isShiftedUInt(uint64_t x) {
392309124Sdim  static_assert(
393309124Sdim      N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)");
394309124Sdim  static_assert(N + S <= 64,
395309124Sdim                "isShiftedUInt<N, S> with N + S > 64 is too wide.");
396309124Sdim  // Per the two static_asserts above, S must be strictly less than 64.  So
397309124Sdim  // 1 << S is not undefined behavior.
398309124Sdim  return isUInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
399234353Sdim}
400234353Sdim
401309124Sdim/// Gets the maximum value for a N-bit unsigned integer.
402309124Sdiminline uint64_t maxUIntN(uint64_t N) {
403309124Sdim  assert(N > 0 && N <= 64 && "integer width out of range");
404309124Sdim
405309124Sdim  // uint64_t(1) << 64 is undefined behavior, so we can't do
406309124Sdim  //   (uint64_t(1) << N) - 1
407309124Sdim  // without checking first that N != 64.  But this works and doesn't have a
408309124Sdim  // branch.
409309124Sdim  return UINT64_MAX >> (64 - N);
410309124Sdim}
411309124Sdim
412309124Sdim/// Gets the minimum value for a N-bit signed integer.
413309124Sdiminline int64_t minIntN(int64_t N) {
414309124Sdim  assert(N > 0 && N <= 64 && "integer width out of range");
415309124Sdim
416309124Sdim  return -(UINT64_C(1)<<(N-1));
417309124Sdim}
418309124Sdim
419309124Sdim/// Gets the maximum value for a N-bit signed integer.
420309124Sdiminline int64_t maxIntN(int64_t N) {
421309124Sdim  assert(N > 0 && N <= 64 && "integer width out of range");
422309124Sdim
423309124Sdim  // This relies on two's complement wraparound when N == 64, so we convert to
424309124Sdim  // int64_t only at the very end to avoid UB.
425309124Sdim  return (UINT64_C(1) << (N - 1)) - 1;
426309124Sdim}
427309124Sdim
428321369Sdim/// Checks if an unsigned integer fits into the given (dynamic) bit width.
429218893Sdiminline bool isUIntN(unsigned N, uint64_t x) {
430309124Sdim  return N >= 64 || x <= maxUIntN(N);
431218893Sdim}
432218893Sdim
433321369Sdim/// Checks if an signed integer fits into the given (dynamic) bit width.
434218893Sdiminline bool isIntN(unsigned N, int64_t x) {
435309124Sdim  return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
436218893Sdim}
437218893Sdim
438321369Sdim/// Return true if the argument is a non-empty sequence of ones starting at the
439321369Sdim/// least significant bit with the remainder zero (32 bit version).
440321369Sdim/// Ex. isMask_32(0x0000FFFFU) == true.
441314564Sdimconstexpr inline bool isMask_32(uint32_t Value) {
442193323Sed  return Value && ((Value + 1) & Value) == 0;
443193323Sed}
444193323Sed
445321369Sdim/// Return true if the argument is a non-empty sequence of ones starting at the
446321369Sdim/// least significant bit with the remainder zero (64 bit version).
447314564Sdimconstexpr inline bool isMask_64(uint64_t Value) {
448193323Sed  return Value && ((Value + 1) & Value) == 0;
449193323Sed}
450193323Sed
451321369Sdim/// Return true if the argument contains a non-empty sequence of ones with the
452321369Sdim/// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
453314564Sdimconstexpr inline bool isShiftedMask_32(uint32_t Value) {
454288943Sdim  return Value && isMask_32((Value - 1) | Value);
455193323Sed}
456193323Sed
457321369Sdim/// Return true if the argument contains a non-empty sequence of ones with the
458321369Sdim/// remainder zero (64 bit version.)
459314564Sdimconstexpr inline bool isShiftedMask_64(uint64_t Value) {
460288943Sdim  return Value && isMask_64((Value - 1) | Value);
461193323Sed}
462193323Sed
463321369Sdim/// Return true if the argument is a power of two > 0.
464321369Sdim/// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
465314564Sdimconstexpr inline bool isPowerOf2_32(uint32_t Value) {
466193323Sed  return Value && !(Value & (Value - 1));
467193323Sed}
468193323Sed
469321369Sdim/// Return true if the argument is a power of two > 0 (64 bit edition.)
470314564Sdimconstexpr inline bool isPowerOf2_64(uint64_t Value) {
471327952Sdim  return Value && !(Value & (Value - 1));
472193323Sed}
473193323Sed
474321369Sdim/// Return a byte-swapped representation of the 16-bit argument.
475193323Sedinline uint16_t ByteSwap_16(uint16_t Value) {
476218893Sdim  return sys::SwapByteOrder_16(Value);
477193323Sed}
478193323Sed
479321369Sdim/// Return a byte-swapped representation of the 32-bit argument.
480193323Sedinline uint32_t ByteSwap_32(uint32_t Value) {
481218893Sdim  return sys::SwapByteOrder_32(Value);
482193323Sed}
483193323Sed
484321369Sdim/// Return a byte-swapped representation of the 64-bit argument.
485193323Sedinline uint64_t ByteSwap_64(uint64_t Value) {
486218893Sdim  return sys::SwapByteOrder_64(Value);
487193323Sed}
488193323Sed
489341825Sdim/// Count the number of ones from the most significant bit to the first
490288943Sdim/// zero bit.
491288943Sdim///
492321369Sdim/// Ex. countLeadingOnes(0xFF0FFF00) == 8.
493288943Sdim/// Only unsigned integral types are allowed.
494288943Sdim///
495288943Sdim/// \param ZB the behavior on an input of all ones. Only ZB_Width and
496288943Sdim/// ZB_Undefined are valid arguments.
497288943Sdimtemplate <typename T>
498353358Sdimunsigned countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
499288943Sdim  static_assert(std::numeric_limits<T>::is_integer &&
500288943Sdim                    !std::numeric_limits<T>::is_signed,
501288943Sdim                "Only unsigned integral types are allowed.");
502341825Sdim  return countLeadingZeros<T>(~Value, ZB);
503193323Sed}
504193323Sed
505341825Sdim/// Count the number of ones from the least significant bit to the first
506288943Sdim/// zero bit.
507288943Sdim///
508288943Sdim/// Ex. countTrailingOnes(0x00FF00FF) == 8.
509288943Sdim/// Only unsigned integral types are allowed.
510288943Sdim///
511288943Sdim/// \param ZB the behavior on an input of all ones. Only ZB_Width and
512288943Sdim/// ZB_Undefined are valid arguments.
513288943Sdimtemplate <typename T>
514353358Sdimunsigned countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
515288943Sdim  static_assert(std::numeric_limits<T>::is_integer &&
516288943Sdim                    !std::numeric_limits<T>::is_signed,
517288943Sdim                "Only unsigned integral types are allowed.");
518341825Sdim  return countTrailingZeros<T>(~Value, ZB);
519193323Sed}
520193323Sed
521288943Sdimnamespace detail {
522288943Sdimtemplate <typename T, std::size_t SizeOfT> struct PopulationCounter {
523288943Sdim  static unsigned count(T Value) {
524288943Sdim    // Generic version, forward to 32 bits.
525288943Sdim    static_assert(SizeOfT <= 4, "Not implemented!");
526360784Sdim#if defined(__GNUC__)
527288943Sdim    return __builtin_popcount(Value);
528288943Sdim#else
529288943Sdim    uint32_t v = Value;
530288943Sdim    v = v - ((v >> 1) & 0x55555555);
531288943Sdim    v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
532288943Sdim    return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
533288943Sdim#endif
534288943Sdim  }
535288943Sdim};
536193323Sed
537288943Sdimtemplate <typename T> struct PopulationCounter<T, 8> {
538288943Sdim  static unsigned count(T Value) {
539360784Sdim#if defined(__GNUC__)
540288943Sdim    return __builtin_popcountll(Value);
541193323Sed#else
542288943Sdim    uint64_t v = Value;
543288943Sdim    v = v - ((v >> 1) & 0x5555555555555555ULL);
544288943Sdim    v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
545288943Sdim    v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
546288943Sdim    return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
547193323Sed#endif
548288943Sdim  }
549288943Sdim};
550288943Sdim} // namespace detail
551288943Sdim
552341825Sdim/// Count the number of set bits in a value.
553288943Sdim/// Ex. countPopulation(0xF000F000) = 8
554288943Sdim/// Returns 0 if the word is zero.
555288943Sdimtemplate <typename T>
556288943Sdiminline unsigned countPopulation(T Value) {
557288943Sdim  static_assert(std::numeric_limits<T>::is_integer &&
558288943Sdim                    !std::numeric_limits<T>::is_signed,
559288943Sdim                "Only unsigned integral types are allowed.");
560288943Sdim  return detail::PopulationCounter<T, sizeof(T)>::count(Value);
561193323Sed}
562193323Sed
563360784Sdim/// Compile time Log2.
564360784Sdim/// Valid only for positive powers of two.
565360784Sdimtemplate <size_t kValue> constexpr inline size_t CTLog2() {
566360784Sdim  static_assert(kValue > 0 && llvm::isPowerOf2_64(kValue),
567360784Sdim                "Value is not a valid power of 2");
568360784Sdim  return 1 + CTLog2<kValue / 2>();
569360784Sdim}
570360784Sdim
571360784Sdimtemplate <> constexpr inline size_t CTLog2<1>() { return 0; }
572360784Sdim
573321369Sdim/// Return the log base 2 of the specified value.
574288943Sdiminline double Log2(double Value) {
575288943Sdim#if defined(__ANDROID_API__) && __ANDROID_API__ < 18
576288943Sdim  return __builtin_log(Value) / __builtin_log(2.0);
577193323Sed#else
578288943Sdim  return log2(Value);
579193323Sed#endif
580193323Sed}
581193323Sed
582321369Sdim/// Return the floor log base 2 of the specified value, -1 if the value is zero.
583321369Sdim/// (32 bit edition.)
584193323Sed/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
585193323Sedinline unsigned Log2_32(uint32_t Value) {
586261991Sdim  return 31 - countLeadingZeros(Value);
587193323Sed}
588193323Sed
589321369Sdim/// Return the floor log base 2 of the specified value, -1 if the value is zero.
590321369Sdim/// (64 bit edition.)
591193323Sedinline unsigned Log2_64(uint64_t Value) {
592261991Sdim  return 63 - countLeadingZeros(Value);
593193323Sed}
594193323Sed
595321369Sdim/// Return the ceil log base 2 of the specified value, 32 if the value is zero.
596321369Sdim/// (32 bit edition).
597193323Sed/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
598193323Sedinline unsigned Log2_32_Ceil(uint32_t Value) {
599261991Sdim  return 32 - countLeadingZeros(Value - 1);
600193323Sed}
601193323Sed
602321369Sdim/// Return the ceil log base 2 of the specified value, 64 if the value is zero.
603321369Sdim/// (64 bit edition.)
604193323Sedinline unsigned Log2_64_Ceil(uint64_t Value) {
605261991Sdim  return 64 - countLeadingZeros(Value - 1);
606193323Sed}
607193323Sed
608321369Sdim/// Return the greatest common divisor of the values using Euclid's algorithm.
609353358Sdimtemplate <typename T>
610353358Sdiminline T greatestCommonDivisor(T A, T B) {
611193323Sed  while (B) {
612353358Sdim    T Tmp = B;
613193323Sed    B = A % B;
614353358Sdim    A = Tmp;
615193323Sed  }
616193323Sed  return A;
617193323Sed}
618193323Sed
619353358Sdiminline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
620353358Sdim  return greatestCommonDivisor<uint64_t>(A, B);
621353358Sdim}
622353358Sdim
623321369Sdim/// This function takes a 64-bit integer and returns the bit equivalent double.
624193323Sedinline double BitsToDouble(uint64_t Bits) {
625314564Sdim  double D;
626314564Sdim  static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
627314564Sdim  memcpy(&D, &Bits, sizeof(Bits));
628314564Sdim  return D;
629193323Sed}
630193323Sed
631321369Sdim/// This function takes a 32-bit integer and returns the bit equivalent float.
632193323Sedinline float BitsToFloat(uint32_t Bits) {
633314564Sdim  float F;
634314564Sdim  static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
635314564Sdim  memcpy(&F, &Bits, sizeof(Bits));
636314564Sdim  return F;
637193323Sed}
638193323Sed
639321369Sdim/// This function takes a double and returns the bit equivalent 64-bit integer.
640321369Sdim/// Note that copying doubles around changes the bits of NaNs on some hosts,
641321369Sdim/// notably x86, so this routine cannot be used if these bits are needed.
642193323Sedinline uint64_t DoubleToBits(double Double) {
643314564Sdim  uint64_t Bits;
644314564Sdim  static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
645314564Sdim  memcpy(&Bits, &Double, sizeof(Double));
646314564Sdim  return Bits;
647193323Sed}
648193323Sed
649321369Sdim/// This function takes a float and returns the bit equivalent 32-bit integer.
650321369Sdim/// Note that copying floats around changes the bits of NaNs on some hosts,
651321369Sdim/// notably x86, so this routine cannot be used if these bits are needed.
652193323Sedinline uint32_t FloatToBits(float Float) {
653314564Sdim  uint32_t Bits;
654314564Sdim  static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
655314564Sdim  memcpy(&Bits, &Float, sizeof(Float));
656314564Sdim  return Bits;
657193323Sed}
658193323Sed
659321369Sdim/// A and B are either alignments or offsets. Return the minimum alignment that
660321369Sdim/// may be assumed after adding the two together.
661314564Sdimconstexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) {
662193323Sed  // The largest power of 2 that divides both A and B.
663249423Sdim  //
664296417Sdim  // Replace "-Value" by "1+~Value" in the following commented code to avoid
665249423Sdim  // MSVC warning C4146
666249423Sdim  //    return (A | B) & -(A | B);
667249423Sdim  return (A | B) & (1 + ~(A | B));
668193323Sed}
669193323Sed
670321369Sdim/// Returns the next power of two (in 64-bits) that is strictly greater than A.
671321369Sdim/// Returns zero on overflow.
672239462Sdiminline uint64_t NextPowerOf2(uint64_t A) {
673193323Sed  A |= (A >> 1);
674193323Sed  A |= (A >> 2);
675193323Sed  A |= (A >> 4);
676193323Sed  A |= (A >> 8);
677193323Sed  A |= (A >> 16);
678193323Sed  A |= (A >> 32);
679193323Sed  return A + 1;
680193323Sed}
681193323Sed
682276479Sdim/// Returns the power of two which is less than or equal to the given value.
683276479Sdim/// Essentially, it is a floor operation across the domain of powers of two.
684276479Sdiminline uint64_t PowerOf2Floor(uint64_t A) {
685276479Sdim  if (!A) return 0;
686276479Sdim  return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
687276479Sdim}
688276479Sdim
689314564Sdim/// Returns the power of two which is greater than or equal to the given value.
690314564Sdim/// Essentially, it is a ceil operation across the domain of powers of two.
691314564Sdiminline uint64_t PowerOf2Ceil(uint64_t A) {
692314564Sdim  if (!A)
693314564Sdim    return 0;
694314564Sdim  return NextPowerOf2(A - 1);
695314564Sdim}
696314564Sdim
697243830Sdim/// Returns the next integer (mod 2**64) that is greater than or equal to
698243830Sdim/// \p Value and is a multiple of \p Align. \p Align must be non-zero.
699193323Sed///
700296417Sdim/// If non-zero \p Skew is specified, the return value will be a minimal
701296417Sdim/// integer that is greater than or equal to \p Value and equal to
702296417Sdim/// \p Align * N + \p Skew for some integer N. If \p Skew is larger than
703296417Sdim/// \p Align, its value is adjusted to '\p Skew mod \p Align'.
704296417Sdim///
705193323Sed/// Examples:
706243830Sdim/// \code
707309124Sdim///   alignTo(5, 8) = 8
708309124Sdim///   alignTo(17, 8) = 24
709309124Sdim///   alignTo(~0LL, 8) = 0
710309124Sdim///   alignTo(321, 255) = 510
711296417Sdim///
712309124Sdim///   alignTo(5, 8, 7) = 7
713309124Sdim///   alignTo(17, 8, 1) = 17
714309124Sdim///   alignTo(~0LL, 8, 3) = 3
715309124Sdim///   alignTo(321, 255, 42) = 552
716243830Sdim/// \endcode
717309124Sdiminline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
718314564Sdim  assert(Align != 0u && "Align can't be 0.");
719296417Sdim  Skew %= Align;
720296417Sdim  return (Value + Align - 1 - Skew) / Align * Align + Skew;
721193323Sed}
722193323Sed
723314564Sdim/// Returns the next integer (mod 2**64) that is greater than or equal to
724314564Sdim/// \p Value and is a multiple of \c Align. \c Align must be non-zero.
725314564Sdimtemplate <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) {
726314564Sdim  static_assert(Align != 0u, "Align must be non-zero");
727314564Sdim  return (Value + Align - 1) / Align * Align;
728314564Sdim}
729314564Sdim
730327952Sdim/// Returns the integer ceil(Numerator / Denominator).
731327952Sdiminline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
732327952Sdim  return alignTo(Numerator, Denominator) / Denominator;
733327952Sdim}
734327952Sdim
735360784Sdim/// Returns the integer nearest(Numerator / Denominator).
736360784Sdiminline uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator) {
737360784Sdim  return (Numerator + (Denominator / 2)) / Denominator;
738360784Sdim}
739314564Sdim
740309124Sdim/// Returns the largest uint64_t less than or equal to \p Value and is
741309124Sdim/// \p Skew mod \p Align. \p Align must be non-zero
742309124Sdiminline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
743314564Sdim  assert(Align != 0u && "Align can't be 0.");
744309124Sdim  Skew %= Align;
745309124Sdim  return (Value - Skew) / Align * Align + Skew;
746309124Sdim}
747309124Sdim
748309124Sdim/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
749309124Sdim/// Requires 0 < B <= 32.
750314564Sdimtemplate <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) {
751309124Sdim  static_assert(B > 0, "Bit width can't be 0.");
752309124Sdim  static_assert(B <= 32, "Bit width out of range.");
753309124Sdim  return int32_t(X << (32 - B)) >> (32 - B);
754206124Srdivacky}
755206124Srdivacky
756309124Sdim/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
757309124Sdim/// Requires 0 < B < 32.
758243830Sdiminline int32_t SignExtend32(uint32_t X, unsigned B) {
759309124Sdim  assert(B > 0 && "Bit width can't be 0.");
760309124Sdim  assert(B <= 32 && "Bit width out of range.");
761243830Sdim  return int32_t(X << (32 - B)) >> (32 - B);
762243830Sdim}
763243830Sdim
764309124Sdim/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
765309124Sdim/// Requires 0 < B < 64.
766314564Sdimtemplate <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) {
767309124Sdim  static_assert(B > 0, "Bit width can't be 0.");
768309124Sdim  static_assert(B <= 64, "Bit width out of range.");
769206274Srdivacky  return int64_t(x << (64 - B)) >> (64 - B);
770206124Srdivacky}
771206124Srdivacky
772309124Sdim/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
773309124Sdim/// Requires 0 < B < 64.
774243830Sdiminline int64_t SignExtend64(uint64_t X, unsigned B) {
775309124Sdim  assert(B > 0 && "Bit width can't be 0.");
776309124Sdim  assert(B <= 64 && "Bit width out of range.");
777243830Sdim  return int64_t(X << (64 - B)) >> (64 - B);
778243830Sdim}
779243830Sdim
780309124Sdim/// Subtract two unsigned integers, X and Y, of type T and return the absolute
781309124Sdim/// value of the result.
782296417Sdimtemplate <typename T>
783296417Sdimtypename std::enable_if<std::is_unsigned<T>::value, T>::type
784309124SdimAbsoluteDifference(T X, T Y) {
785309124Sdim  return std::max(X, Y) - std::min(X, Y);
786309124Sdim}
787309124Sdim
788309124Sdim/// Add two unsigned integers, X and Y, of type T.  Clamp the result to the
789309124Sdim/// maximum representable value of T on overflow.  ResultOverflowed indicates if
790309124Sdim/// the result is larger than the maximum representable value of type T.
791309124Sdimtemplate <typename T>
792309124Sdimtypename std::enable_if<std::is_unsigned<T>::value, T>::type
793296417SdimSaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
794296417Sdim  bool Dummy;
795296417Sdim  bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
796296417Sdim  // Hacker's Delight, p. 29
797296417Sdim  T Z = X + Y;
798296417Sdim  Overflowed = (Z < X || Z < Y);
799296417Sdim  if (Overflowed)
800296417Sdim    return std::numeric_limits<T>::max();
801296417Sdim  else
802296417Sdim    return Z;
803296417Sdim}
804296417Sdim
805309124Sdim/// Multiply two unsigned integers, X and Y, of type T.  Clamp the result to the
806309124Sdim/// maximum representable value of T on overflow.  ResultOverflowed indicates if
807309124Sdim/// the result is larger than the maximum representable value of type T.
808296417Sdimtemplate <typename T>
809296417Sdimtypename std::enable_if<std::is_unsigned<T>::value, T>::type
810296417SdimSaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
811296417Sdim  bool Dummy;
812296417Sdim  bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
813296417Sdim
814296417Sdim  // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
815296417Sdim  // because it fails for uint16_t (where multiplication can have undefined
816296417Sdim  // behavior due to promotion to int), and requires a division in addition
817296417Sdim  // to the multiplication.
818296417Sdim
819296417Sdim  Overflowed = false;
820296417Sdim
821296417Sdim  // Log2(Z) would be either Log2Z or Log2Z + 1.
822296417Sdim  // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
823296417Sdim  // will necessarily be less than Log2Max as desired.
824296417Sdim  int Log2Z = Log2_64(X) + Log2_64(Y);
825296417Sdim  const T Max = std::numeric_limits<T>::max();
826296417Sdim  int Log2Max = Log2_64(Max);
827296417Sdim  if (Log2Z < Log2Max) {
828296417Sdim    return X * Y;
829296417Sdim  }
830296417Sdim  if (Log2Z > Log2Max) {
831296417Sdim    Overflowed = true;
832296417Sdim    return Max;
833296417Sdim  }
834296417Sdim
835296417Sdim  // We're going to use the top bit, and maybe overflow one
836296417Sdim  // bit past it. Multiply all but the bottom bit then add
837296417Sdim  // that on at the end.
838296417Sdim  T Z = (X >> 1) * Y;
839296417Sdim  if (Z & ~(Max >> 1)) {
840296417Sdim    Overflowed = true;
841296417Sdim    return Max;
842296417Sdim  }
843296417Sdim  Z <<= 1;
844296417Sdim  if (X & 1)
845296417Sdim    return SaturatingAdd(Z, Y, ResultOverflowed);
846296417Sdim
847296417Sdim  return Z;
848296417Sdim}
849296417Sdim
850309124Sdim/// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
851309124Sdim/// the product. Clamp the result to the maximum representable value of T on
852309124Sdim/// overflow. ResultOverflowed indicates if the result is larger than the
853309124Sdim/// maximum representable value of type T.
854296417Sdimtemplate <typename T>
855296417Sdimtypename std::enable_if<std::is_unsigned<T>::value, T>::type
856296417SdimSaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
857296417Sdim  bool Dummy;
858296417Sdim  bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
859296417Sdim
860296417Sdim  T Product = SaturatingMultiply(X, Y, &Overflowed);
861296417Sdim  if (Overflowed)
862296417Sdim    return Product;
863296417Sdim
864296417Sdim  return SaturatingAdd(A, Product, &Overflowed);
865296417Sdim}
866296417Sdim
867309124Sdim/// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
868280031Sdimextern const float huge_valf;
869360784Sdim
870360784Sdim
871360784Sdim/// Add two signed integers, computing the two's complement truncated result,
872360784Sdim/// returning true if overflow occured.
873360784Sdimtemplate <typename T>
874360784Sdimtypename std::enable_if<std::is_signed<T>::value, T>::type
875360784SdimAddOverflow(T X, T Y, T &Result) {
876360784Sdim#if __has_builtin(__builtin_add_overflow)
877360784Sdim  return __builtin_add_overflow(X, Y, &Result);
878360784Sdim#else
879360784Sdim  // Perform the unsigned addition.
880360784Sdim  using U = typename std::make_unsigned<T>::type;
881360784Sdim  const U UX = static_cast<U>(X);
882360784Sdim  const U UY = static_cast<U>(Y);
883360784Sdim  const U UResult = UX + UY;
884360784Sdim
885360784Sdim  // Convert to signed.
886360784Sdim  Result = static_cast<T>(UResult);
887360784Sdim
888360784Sdim  // Adding two positive numbers should result in a positive number.
889360784Sdim  if (X > 0 && Y > 0)
890360784Sdim    return Result <= 0;
891360784Sdim  // Adding two negatives should result in a negative number.
892360784Sdim  if (X < 0 && Y < 0)
893360784Sdim    return Result >= 0;
894360784Sdim  return false;
895360784Sdim#endif
896360784Sdim}
897360784Sdim
898360784Sdim/// Subtract two signed integers, computing the two's complement truncated
899360784Sdim/// result, returning true if an overflow ocurred.
900360784Sdimtemplate <typename T>
901360784Sdimtypename std::enable_if<std::is_signed<T>::value, T>::type
902360784SdimSubOverflow(T X, T Y, T &Result) {
903360784Sdim#if __has_builtin(__builtin_sub_overflow)
904360784Sdim  return __builtin_sub_overflow(X, Y, &Result);
905360784Sdim#else
906360784Sdim  // Perform the unsigned addition.
907360784Sdim  using U = typename std::make_unsigned<T>::type;
908360784Sdim  const U UX = static_cast<U>(X);
909360784Sdim  const U UY = static_cast<U>(Y);
910360784Sdim  const U UResult = UX - UY;
911360784Sdim
912360784Sdim  // Convert to signed.
913360784Sdim  Result = static_cast<T>(UResult);
914360784Sdim
915360784Sdim  // Subtracting a positive number from a negative results in a negative number.
916360784Sdim  if (X <= 0 && Y > 0)
917360784Sdim    return Result >= 0;
918360784Sdim  // Subtracting a negative number from a positive results in a positive number.
919360784Sdim  if (X >= 0 && Y < 0)
920360784Sdim    return Result <= 0;
921360784Sdim  return false;
922360784Sdim#endif
923360784Sdim}
924360784Sdim
925360784Sdim
926360784Sdim/// Multiply two signed integers, computing the two's complement truncated
927360784Sdim/// result, returning true if an overflow ocurred.
928360784Sdimtemplate <typename T>
929360784Sdimtypename std::enable_if<std::is_signed<T>::value, T>::type
930360784SdimMulOverflow(T X, T Y, T &Result) {
931360784Sdim  // Perform the unsigned multiplication on absolute values.
932360784Sdim  using U = typename std::make_unsigned<T>::type;
933360784Sdim  const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
934360784Sdim  const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
935360784Sdim  const U UResult = UX * UY;
936360784Sdim
937360784Sdim  // Convert to signed.
938360784Sdim  const bool IsNegative = (X < 0) ^ (Y < 0);
939360784Sdim  Result = IsNegative ? (0 - UResult) : UResult;
940360784Sdim
941360784Sdim  // If any of the args was 0, result is 0 and no overflow occurs.
942360784Sdim  if (UX == 0 || UY == 0)
943360784Sdim    return false;
944360784Sdim
945360784Sdim  // UX and UY are in [1, 2^n], where n is the number of digits.
946360784Sdim  // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
947360784Sdim  // positive) divided by an argument compares to the other.
948360784Sdim  if (IsNegative)
949360784Sdim    return UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY;
950360784Sdim  else
951360784Sdim    return UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
952360784Sdim}
953360784Sdim
954193323Sed} // End llvm namespace
955193323Sed
956193323Sed#endif
957