WPILibC++  2020.3.2
MathExtras.h
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 WPIUTIL_WPI_MATHEXTRAS_H
15 #define WPIUTIL_WPI_MATHEXTRAS_H
16 
17 #include "wpi/Compiler.h"
18 #include <cstdint>
19 #include <algorithm>
20 #include <cassert>
21 #include <climits>
22 #include <cmath>
23 #include <cstring>
24 #include <limits>
25 #include <type_traits>
26 
27 #ifdef _MSC_VER
28 // Declare these intrinsics manually rather including intrin.h. It's very
29 // expensive, and MathExtras.h is popular.
30 // #include <intrin.h>
31 extern "C" {
32 unsigned char _BitScanForward(unsigned long *_Index, unsigned long _Mask);
33 unsigned char _BitScanForward64(unsigned long *_Index, unsigned __int64 _Mask);
34 unsigned char _BitScanReverse(unsigned long *_Index, unsigned long _Mask);
35 unsigned char _BitScanReverse64(unsigned long *_Index, unsigned __int64 _Mask);
36 }
37 #endif
38 
39 namespace wpi {
48 };
49 
50 namespace detail {
51 template <typename T, std::size_t SizeOfT> struct TrailingZerosCounter {
52  static std::size_t count(T Val, ZeroBehavior) {
53  if (!Val)
54  return std::numeric_limits<T>::digits;
55  if (Val & 0x1)
56  return 0;
57 
58  // Bisection method.
59  std::size_t ZeroBits = 0;
60  T Shift = std::numeric_limits<T>::digits >> 1;
61  T Mask = (std::numeric_limits<T>::max)() >> Shift;
62  while (Shift) {
63  if ((Val & Mask) == 0) {
64  Val >>= Shift;
65  ZeroBits |= Shift;
66  }
67  Shift >>= 1;
68  Mask >>= Shift;
69  }
70  return ZeroBits;
71  }
72 };
73 
74 #if __GNUC__ >= 4 || defined(_MSC_VER)
75 template <typename T> struct TrailingZerosCounter<T, 4> {
76  static std::size_t count(T Val, ZeroBehavior ZB) {
77  if (ZB != ZB_Undefined && Val == 0)
78  return 32;
79 
80 #if __has_builtin(__builtin_ctz) || LLVM_GNUC_PREREQ(4, 0, 0)
81  return __builtin_ctz(Val);
82 #elif defined(_MSC_VER)
83  unsigned long Index;
84  _BitScanForward(&Index, Val);
85  return Index;
86 #endif
87  }
88 };
89 
90 #if !defined(_MSC_VER) || defined(_M_X64)
91 template <typename T> struct TrailingZerosCounter<T, 8> {
92  static std::size_t count(T Val, ZeroBehavior ZB) {
93  if (ZB != ZB_Undefined && Val == 0)
94  return 64;
95 
96 #if __has_builtin(__builtin_ctzll) || LLVM_GNUC_PREREQ(4, 0, 0)
97  return __builtin_ctzll(Val);
98 #elif defined(_MSC_VER)
99  unsigned long Index;
100  _BitScanForward64(&Index, Val);
101  return Index;
102 #endif
103  }
104 };
105 #endif
106 #endif
107 } // namespace detail
108 
116 template <typename T>
117 std::size_t countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
118  static_assert(std::numeric_limits<T>::is_integer &&
119  !std::numeric_limits<T>::is_signed,
120  "Only unsigned integral types are allowed.");
121  return wpi::detail::TrailingZerosCounter<T, sizeof(T)>::count(Val, ZB);
122 }
123 
124 namespace detail {
125 template <typename T, std::size_t SizeOfT> struct LeadingZerosCounter {
126  static std::size_t count(T Val, ZeroBehavior) {
127  if (!Val)
128  return std::numeric_limits<T>::digits;
129 
130  // Bisection method.
131  std::size_t ZeroBits = 0;
132  for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
133  T Tmp = Val >> Shift;
134  if (Tmp)
135  Val = Tmp;
136  else
137  ZeroBits |= Shift;
138  }
139  return ZeroBits;
140  }
141 };
142 
143 #if __GNUC__ >= 4 || defined(_MSC_VER)
144 template <typename T> struct LeadingZerosCounter<T, 4> {
145  static std::size_t count(T Val, ZeroBehavior ZB) {
146  if (ZB != ZB_Undefined && Val == 0)
147  return 32;
148 
149 #if __has_builtin(__builtin_clz) || LLVM_GNUC_PREREQ(4, 0, 0)
150  return __builtin_clz(Val);
151 #elif defined(_MSC_VER)
152  unsigned long Index;
153  _BitScanReverse(&Index, Val);
154  return Index ^ 31;
155 #endif
156  }
157 };
158 
159 #if !defined(_MSC_VER) || defined(_M_X64)
160 template <typename T> struct LeadingZerosCounter<T, 8> {
161  static std::size_t count(T Val, ZeroBehavior ZB) {
162  if (ZB != ZB_Undefined && Val == 0)
163  return 64;
164 
165 #if __has_builtin(__builtin_clzll) || LLVM_GNUC_PREREQ(4, 0, 0)
166  return __builtin_clzll(Val);
167 #elif defined(_MSC_VER)
168  unsigned long Index;
169  _BitScanReverse64(&Index, Val);
170  return Index ^ 63;
171 #endif
172  }
173 };
174 #endif
175 #endif
176 } // namespace detail
177 
185 template <typename T>
186 std::size_t countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
187  static_assert(std::numeric_limits<T>::is_integer &&
188  !std::numeric_limits<T>::is_signed,
189  "Only unsigned integral types are allowed.");
190  return wpi::detail::LeadingZerosCounter<T, sizeof(T)>::count(Val, ZB);
191 }
192 
200 template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
201  if (ZB == ZB_Max && Val == 0)
202  return (std::numeric_limits<T>::max)();
203 
204  return countTrailingZeros(Val, ZB_Undefined);
205 }
206 
209 template <typename T> T maskTrailingOnes(unsigned N) {
210  static_assert(std::is_unsigned<T>::value, "Invalid type!");
211  const unsigned Bits = CHAR_BIT * sizeof(T);
212  assert(N <= Bits && "Invalid bit index");
213  return N == 0 ? 0 : (T(-1) >> (Bits - N));
214 }
215 
218 template <typename T> T maskLeadingOnes(unsigned N) {
219  return ~maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
220 }
221 
224 template <typename T> T maskTrailingZeros(unsigned N) {
225  return maskLeadingOnes<T>(CHAR_BIT * sizeof(T) - N);
226 }
227 
230 template <typename T> T maskLeadingZeros(unsigned N) {
231  return maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
232 }
233 
241 template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
242  if (ZB == ZB_Max && Val == 0)
243  return (std::numeric_limits<T>::max)();
244 
245  // Use ^ instead of - because both gcc and llvm can remove the associated ^
246  // in the __builtin_clz intrinsic on x86.
247  return countLeadingZeros(Val, ZB_Undefined) ^
248  (std::numeric_limits<T>::digits - 1);
249 }
250 
254 static const unsigned char BitReverseTable256[256] = {
255 #define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
256 #define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
257 #define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
258  R6(0), R6(2), R6(1), R6(3)
259 #undef R2
260 #undef R4
261 #undef R6
262 };
263 
265 template <typename T>
266 T reverseBits(T Val) {
267  unsigned char in[sizeof(Val)];
268  unsigned char out[sizeof(Val)];
269  std::memcpy(in, &Val, sizeof(Val));
270  for (unsigned i = 0; i < sizeof(Val); ++i)
271  out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
272  std::memcpy(&Val, out, sizeof(Val));
273  return Val;
274 }
275 
276 // NOTE: The following support functions use the _32/_64 extensions instead of
277 // type overloading so that signed and unsigned integers can be used without
278 // ambiguity.
279 
281 constexpr inline uint32_t Hi_32(uint64_t Value) {
282  return static_cast<uint32_t>(Value >> 32);
283 }
284 
286 constexpr inline uint32_t Lo_32(uint64_t Value) {
287  return static_cast<uint32_t>(Value);
288 }
289 
291 constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) {
292  return ((uint64_t)High << 32) | (uint64_t)Low;
293 }
294 
296 template <unsigned N> constexpr inline bool isInt(int64_t x) {
297  return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
298 }
299 // Template specializations to get better code for common cases.
300 template <> constexpr inline bool isInt<8>(int64_t x) {
301  return static_cast<int8_t>(x) == x;
302 }
303 template <> constexpr inline bool isInt<16>(int64_t x) {
304  return static_cast<int16_t>(x) == x;
305 }
306 template <> constexpr inline bool isInt<32>(int64_t x) {
307  return static_cast<int32_t>(x) == x;
308 }
309 
311 template <unsigned N, unsigned S>
312 constexpr inline bool isShiftedInt(int64_t x) {
313  static_assert(
314  N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number.");
315  static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
316  return isInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
317 }
318 
327 template <unsigned N>
328 constexpr inline typename std::enable_if<(N < 64), bool>::type
329 isUInt(uint64_t X) {
330  static_assert(N > 0, "isUInt<0> doesn't make sense");
331  return X < (UINT64_C(1) << (N));
332 }
333 template <unsigned N>
334 constexpr inline typename std::enable_if<N >= 64, bool>::type
335 isUInt(uint64_t X) {
336  return true;
337 }
338 
339 // Template specializations to get better code for common cases.
340 template <> constexpr inline bool isUInt<8>(uint64_t x) {
341  return static_cast<uint8_t>(x) == x;
342 }
343 template <> constexpr inline bool isUInt<16>(uint64_t x) {
344  return static_cast<uint16_t>(x) == x;
345 }
346 template <> constexpr inline bool isUInt<32>(uint64_t x) {
347  return static_cast<uint32_t>(x) == x;
348 }
349 
351 template <unsigned N, unsigned S>
352 constexpr inline bool isShiftedUInt(uint64_t x) {
353  static_assert(
354  N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)");
355  static_assert(N + S <= 64,
356  "isShiftedUInt<N, S> with N + S > 64 is too wide.");
357  // Per the two static_asserts above, S must be strictly less than 64. So
358  // 1 << S is not undefined behavior.
359  return isUInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
360 }
361 
363 inline uint64_t maxUIntN(uint64_t N) {
364  assert(N > 0 && N <= 64 && "integer width out of range");
365 
366  // uint64_t(1) << 64 is undefined behavior, so we can't do
367  // (uint64_t(1) << N) - 1
368  // without checking first that N != 64. But this works and doesn't have a
369  // branch.
370  return UINT64_MAX >> (64 - N);
371 }
372 
373 #ifdef _WIN32
374 #pragma warning(push)
375 #pragma warning(disable : 4146)
376 #endif
377 
379 inline int64_t minIntN(int64_t N) {
380  assert(N > 0 && N <= 64 && "integer width out of range");
381 
382  return -(UINT64_C(1)<<(N-1));
383 }
384 
385 #ifdef _WIN32
386 #pragma warning(pop)
387 #endif
388 
390 inline int64_t maxIntN(int64_t N) {
391  assert(N > 0 && N <= 64 && "integer width out of range");
392 
393  // This relies on two's complement wraparound when N == 64, so we convert to
394  // int64_t only at the very end to avoid UB.
395  return (UINT64_C(1) << (N - 1)) - 1;
396 }
397 
399 inline bool isUIntN(unsigned N, uint64_t x) {
400  return N >= 64 || x <= maxUIntN(N);
401 }
402 
404 inline bool isIntN(unsigned N, int64_t x) {
405  return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
406 }
407 
411 constexpr inline bool isMask_32(uint32_t Value) {
412  return Value && ((Value + 1) & Value) == 0;
413 }
414 
417 constexpr inline bool isMask_64(uint64_t Value) {
418  return Value && ((Value + 1) & Value) == 0;
419 }
420 
423 constexpr inline bool isShiftedMask_32(uint32_t Value) {
424  return Value && isMask_32((Value - 1) | Value);
425 }
426 
429 constexpr inline bool isShiftedMask_64(uint64_t Value) {
430  return Value && isMask_64((Value - 1) | Value);
431 }
432 
435 constexpr inline bool isPowerOf2_32(uint32_t Value) {
436  return Value && !(Value & (Value - 1));
437 }
438 
440 constexpr inline bool isPowerOf2_64(uint64_t Value) {
441  return Value && !(Value & (Value - 1));
442 }
443 
452 template <typename T>
453 std::size_t countLeadingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
454  static_assert(std::numeric_limits<T>::is_integer &&
455  !std::numeric_limits<T>::is_signed,
456  "Only unsigned integral types are allowed.");
457  return countLeadingZeros<T>(~Value, ZB);
458 }
459 
468 template <typename T>
469 std::size_t countTrailingOnes(T Value, ZeroBehavior ZB = ZB_Width) {
470  static_assert(std::numeric_limits<T>::is_integer &&
471  !std::numeric_limits<T>::is_signed,
472  "Only unsigned integral types are allowed.");
473  return countTrailingZeros<T>(~Value, ZB);
474 }
475 
476 namespace detail {
477 template <typename T, std::size_t SizeOfT> struct PopulationCounter {
478  static unsigned count(T Value) {
479  // Generic version, forward to 32 bits.
480  static_assert(SizeOfT <= 4, "Not implemented!");
481 #if __GNUC__ >= 4
482  return __builtin_popcount(Value);
483 #else
484  uint32_t v = Value;
485  v = v - ((v >> 1) & 0x55555555);
486  v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
487  return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
488 #endif
489  }
490 };
491 
492 template <typename T> struct PopulationCounter<T, 8> {
493  static unsigned count(T Value) {
494 #if __GNUC__ >= 4
495  return __builtin_popcountll(Value);
496 #else
497  uint64_t v = Value;
498  v = v - ((v >> 1) & 0x5555555555555555ULL);
499  v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
500  v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
501  return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
502 #endif
503  }
504 };
505 } // namespace detail
506 
510 template <typename T>
511 inline unsigned countPopulation(T Value) {
512  static_assert(std::numeric_limits<T>::is_integer &&
513  !std::numeric_limits<T>::is_signed,
514  "Only unsigned integral types are allowed.");
515  return detail::PopulationCounter<T, sizeof(T)>::count(Value);
516 }
517 
519 inline double Log2(double Value) {
520 #if defined(__ANDROID_API__) && __ANDROID_API__ < 18
521  return __builtin_log(Value) / __builtin_log(2.0);
522 #else
523  return std::log2(Value);
524 #endif
525 }
526 
530 inline unsigned Log2_32(uint32_t Value) {
531  return static_cast<unsigned>(31 - countLeadingZeros(Value));
532 }
533 
536 inline unsigned Log2_64(uint64_t Value) {
537  return static_cast<unsigned>(63 - countLeadingZeros(Value));
538 }
539 
543 inline unsigned Log2_32_Ceil(uint32_t Value) {
544  return static_cast<unsigned>(32 - countLeadingZeros(Value - 1));
545 }
546 
549 inline unsigned Log2_64_Ceil(uint64_t Value) {
550  return static_cast<unsigned>(64 - countLeadingZeros(Value - 1));
551 }
552 
554 inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
555  while (B) {
556  uint64_t T = B;
557  B = A % B;
558  A = T;
559  }
560  return A;
561 }
562 
564 inline double BitsToDouble(uint64_t Bits) {
565  double D;
566  static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
567  memcpy(&D, &Bits, sizeof(Bits));
568  return D;
569 }
570 
572 inline float BitsToFloat(uint32_t Bits) {
573  float F;
574  static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
575  memcpy(&F, &Bits, sizeof(Bits));
576  return F;
577 }
578 
582 inline uint64_t DoubleToBits(double Double) {
583  uint64_t Bits;
584  static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
585  memcpy(&Bits, &Double, sizeof(Double));
586  return Bits;
587 }
588 
592 inline uint32_t FloatToBits(float Float) {
593  uint32_t Bits;
594  static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
595  memcpy(&Bits, &Float, sizeof(Float));
596  return Bits;
597 }
598 
601 constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) {
602  // The largest power of 2 that divides both A and B.
603  //
604  // Replace "-Value" by "1+~Value" in the following commented code to avoid
605  // MSVC warning C4146
606  // return (A | B) & -(A | B);
607  return (A | B) & (1 + ~(A | B));
608 }
609 
614 inline uintptr_t alignAddr(const void *Addr, size_t Alignment) {
615  assert(Alignment && isPowerOf2_64((uint64_t)Alignment) &&
616  "Alignment is not a power of two!");
617 
618  assert((uintptr_t)Addr + Alignment - 1 >= (uintptr_t)Addr);
619 
620  return (((uintptr_t)Addr + Alignment - 1) & ~(uintptr_t)(Alignment - 1));
621 }
622 
625 inline size_t alignmentAdjustment(const void *Ptr, size_t Alignment) {
626  return alignAddr(Ptr, Alignment) - (uintptr_t)Ptr;
627 }
628 
631 inline uint64_t NextPowerOf2(uint64_t A) {
632  A |= (A >> 1);
633  A |= (A >> 2);
634  A |= (A >> 4);
635  A |= (A >> 8);
636  A |= (A >> 16);
637  A |= (A >> 32);
638  return A + 1;
639 }
640 
643 inline uint64_t PowerOf2Floor(uint64_t A) {
644  if (!A) return 0;
645  return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
646 }
647 
650 inline uint64_t PowerOf2Ceil(uint64_t A) {
651  if (!A)
652  return 0;
653  return NextPowerOf2(A - 1);
654 }
655 
676 inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
677  assert(Align != 0u && "Align can't be 0.");
678  Skew %= Align;
679  return (Value + Align - 1 - Skew) / Align * Align + Skew;
680 }
681 
684 template <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) {
685  static_assert(Align != 0u, "Align must be non-zero");
686  return (Value + Align - 1) / Align * Align;
687 }
688 
690 inline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
691  return alignTo(Numerator, Denominator) / Denominator;
692 }
693 
698 template <uint64_t Align>
699 struct AlignTo {
700  static_assert(Align != 0u, "Align must be non-zero");
701  template <uint64_t Value>
702  struct from_value {
703  static const uint64_t value = (Value + Align - 1) / Align * Align;
704  };
705 };
706 
709 inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
710  assert(Align != 0u && "Align can't be 0.");
711  Skew %= Align;
712  return (Value - Skew) / Align * Align + Skew;
713 }
714 
718 inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) {
719  return alignTo(Value, Align) - Value;
720 }
721 
724 template <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) {
725  static_assert(B > 0, "Bit width can't be 0.");
726  static_assert(B <= 32, "Bit width out of range.");
727  return int32_t(X << (32 - B)) >> (32 - B);
728 }
729 
732 inline int32_t SignExtend32(uint32_t X, unsigned B) {
733  assert(B > 0 && "Bit width can't be 0.");
734  assert(B <= 32 && "Bit width out of range.");
735  return int32_t(X << (32 - B)) >> (32 - B);
736 }
737 
740 template <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) {
741  static_assert(B > 0, "Bit width can't be 0.");
742  static_assert(B <= 64, "Bit width out of range.");
743  return int64_t(x << (64 - B)) >> (64 - B);
744 }
745 
748 inline int64_t SignExtend64(uint64_t X, unsigned B) {
749  assert(B > 0 && "Bit width can't be 0.");
750  assert(B <= 64 && "Bit width out of range.");
751  return int64_t(X << (64 - B)) >> (64 - B);
752 }
753 
756 template <typename T>
757 typename std::enable_if<std::is_unsigned<T>::value, T>::type
759  return (std::max)(X, Y) - (std::min)(X, Y);
760 }
761 
765 template <typename T>
766 typename std::enable_if<std::is_unsigned<T>::value, T>::type
767 SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
768  bool Dummy;
769  bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
770  // Hacker's Delight, p. 29
771  T Z = X + Y;
772  Overflowed = (Z < X || Z < Y);
773  if (Overflowed)
774  return (std::numeric_limits<T>::max)();
775  else
776  return Z;
777 }
778 
782 template <typename T>
783 typename std::enable_if<std::is_unsigned<T>::value, T>::type
784 SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
785  bool Dummy;
786  bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
787 
788  // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
789  // because it fails for uint16_t (where multiplication can have undefined
790  // behavior due to promotion to int), and requires a division in addition
791  // to the multiplication.
792 
793  Overflowed = false;
794 
795  // Log2(Z) would be either Log2Z or Log2Z + 1.
796  // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
797  // will necessarily be less than Log2Max as desired.
798  int Log2Z = Log2_64(X) + Log2_64(Y);
799  const T Max = (std::numeric_limits<T>::max)();
800  int Log2Max = Log2_64(Max);
801  if (Log2Z < Log2Max) {
802  return X * Y;
803  }
804  if (Log2Z > Log2Max) {
805  Overflowed = true;
806  return Max;
807  }
808 
809  // We're going to use the top bit, and maybe overflow one
810  // bit past it. Multiply all but the bottom bit then add
811  // that on at the end.
812  T Z = (X >> 1) * Y;
813  if (Z & ~(Max >> 1)) {
814  Overflowed = true;
815  return Max;
816  }
817  Z <<= 1;
818  if (X & 1)
819  return SaturatingAdd(Z, Y, ResultOverflowed);
820 
821  return Z;
822 }
823 
828 template <typename T>
829 typename std::enable_if<std::is_unsigned<T>::value, T>::type
830 SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
831  bool Dummy;
832  bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
833 
834  T Product = SaturatingMultiply(X, Y, &Overflowed);
835  if (Overflowed)
836  return Product;
837 
838  return SaturatingAdd(A, Product, &Overflowed);
839 }
840 
841 // Typesafe implementation of the signum function.
842 // Returns -1 if negative, 1 if positive, 0 if 0.
843 template <typename T>
844 constexpr int sgn(T val) {
845  return (T(0) < val) - (val < T(0));
846 }
847 
848 } // namespace wpi
849 
850 #endif
wpi::isUIntN
bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:399
wpi::detail::TrailingZerosCounter
Definition: MathExtras.h:51
wpi::reverseBits
T reverseBits(T Val)
Reverse the bits in Val.
Definition: MathExtras.h:266
wpi::countLeadingZeros
std::size_t countLeadingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition: MathExtras.h:186
wpi::MinAlign
constexpr uint64_t MinAlign(uint64_t A, uint64_t B)
A and B are either alignments or offsets.
Definition: MathExtras.h:601
wpi::findFirstSet
T findFirstSet(T Val, ZeroBehavior ZB=ZB_Max)
Get the index of the first set bit starting from the least significant bit.
Definition: MathExtras.h:200
wpi::isShiftedMask_64
constexpr bool isShiftedMask_64(uint64_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (64 bit ver...
Definition: MathExtras.h:429
wpi::Log2_32_Ceil
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition: MathExtras.h:543
wpi::maxIntN
int64_t maxIntN(int64_t N)
Gets the maximum value for a N-bit signed integer.
Definition: MathExtras.h:390
wpi::alignDown
uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the largest uint64_t less than or equal to Value and is Skew mod Align.
Definition: MathExtras.h:709
wpi::SignExtend64
constexpr int64_t SignExtend64(uint64_t x)
Sign-extend the number in the bottom B bits of X to a 64-bit integer.
Definition: MathExtras.h:740
wpi::countTrailingZeros
std::size_t countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition: MathExtras.h:117
wpi::countLeadingOnes
std::size_t countLeadingOnes(T Value, ZeroBehavior ZB=ZB_Width)
Count the number of ones from the most significant bit to the first zero bit.
Definition: MathExtras.h:453
wpi::detail::LeadingZerosCounter
Definition: MathExtras.h:125
wpi::ZeroBehavior
ZeroBehavior
The behavior an operation has on an input of 0.
Definition: MathExtras.h:41
wpi::Log2
double Log2(double Value)
Return the log base 2 of the specified value.
Definition: MathExtras.h:519
wpi::isPowerOf2_32
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:435
wpi::SaturatingAdd
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition: MathExtras.h:767
wpi::isShiftedUInt
constexpr bool isShiftedUInt(uint64_t x)
Checks if a unsigned integer is an N bit number shifted left by S.
Definition: MathExtras.h:352
wpi::NextPowerOf2
uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition: MathExtras.h:631
wpi::isIntN
bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition: MathExtras.h:404
wpi::isMask_32
constexpr bool isMask_32(uint32_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition: MathExtras.h:411
wpi::AbsoluteDifference
std::enable_if< std::is_unsigned< T >::value, T >::type AbsoluteDifference(T X, T Y)
Subtract two unsigned integers, X and Y, of type T and return the absolute value of the result.
Definition: MathExtras.h:758
wpi::Log2_32
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:530
wpi::SaturatingMultiply
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
Definition: MathExtras.h:784
wpi::isShiftedInt
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition: MathExtras.h:312
wpi::maxUIntN
uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition: MathExtras.h:363
wpi::isMask_64
constexpr bool isMask_64(uint64_t Value)
Return true if the argument is a non-empty sequence of ones starting at the least significant bit wit...
Definition: MathExtras.h:417
wpi::maskTrailingZeros
T maskTrailingZeros(unsigned N)
Create a bitmask with the N right-most bits set to 0, and all other bits set to 1.
Definition: MathExtras.h:224
wpi::alignTo
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:676
wpi::AlignTo
alignTo for contexts where a constant expression is required.
Definition: MathExtras.h:699
wpi
WPILib C++ utilities (wpiutil) namespace.
Definition: EventLoopRunner.h:17
wpi::maskLeadingOnes
T maskLeadingOnes(unsigned N)
Create a bitmask with the N left-most bits set to 1, and all other bits set to 0.
Definition: MathExtras.h:218
wpi::maskTrailingOnes
T maskTrailingOnes(unsigned N)
Create a bitmask with the N right-most bits set to 1, and all other bits set to 0.
Definition: MathExtras.h:209
wpi::isUInt
constexpr std::enable_if<(N< 64), bool >::type isUInt(uint64_t X)
Checks if an unsigned integer fits into the given bit width.
Definition: MathExtras.h:329
wpi::PowerOf2Floor
uint64_t PowerOf2Floor(uint64_t A)
Returns the power of two which is less than or equal to the given value.
Definition: MathExtras.h:643
wpi::OffsetToAlignment
uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align)
Returns the offset to the next integer (mod 2**64) that is greater than or equal to Value and is a mu...
Definition: MathExtras.h:718
wpi::BitsToFloat
float BitsToFloat(uint32_t Bits)
This function takes a 32-bit integer and returns the bit equivalent float.
Definition: MathExtras.h:572
wpi::SignExtend32
constexpr int32_t SignExtend32(uint32_t X)
Sign-extend the number in the bottom B bits of X to a 32-bit integer.
Definition: MathExtras.h:724
wpi::Hi_32
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition: MathExtras.h:281
wpi::countTrailingOnes
std::size_t countTrailingOnes(T Value, ZeroBehavior ZB=ZB_Width)
Count the number of ones from the least significant bit to the first zero bit.
Definition: MathExtras.h:469
wpi::BitsToDouble
double BitsToDouble(uint64_t Bits)
This function takes a 64-bit integer and returns the bit equivalent double.
Definition: MathExtras.h:564
wpi::alignmentAdjustment
size_t alignmentAdjustment(const void *Ptr, size_t Alignment)
Returns the necessary adjustment for aligning Ptr to Alignment bytes, rounding up.
Definition: MathExtras.h:625
wpi::Make_64
constexpr uint64_t Make_64(uint32_t High, uint32_t Low)
Make a 64-bit integer from a high / low pair of 32-bit integers.
Definition: MathExtras.h:291
wpi::isInt
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition: MathExtras.h:296
wpi::Lo_32
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition: MathExtras.h:286
wpi::isPowerOf2_64
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition: MathExtras.h:440
wpi::PowerOf2Ceil
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition: MathExtras.h:650
wpi::SaturatingMultiplyAdd
std::enable_if< std::is_unsigned< T >::value, T >::type SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, and add the unsigned integer, A to the product.
Definition: MathExtras.h:830
wpi::ZB_Width
The returned value is numeric_limits<T>::digits.
Definition: MathExtras.h:47
wpi::ZB_Undefined
The returned value is undefined.
Definition: MathExtras.h:43
wpi::findLastSet
T findLastSet(T Val, ZeroBehavior ZB=ZB_Max)
Get the index of the last set bit starting from the least significant bit.
Definition: MathExtras.h:241
wpi::ZB_Max
The returned value is numeric_limits<T>::max()
Definition: MathExtras.h:45
wpi::Log2_64
unsigned Log2_64(uint64_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition: MathExtras.h:536
wpi::FloatToBits
uint32_t FloatToBits(float Float)
This function takes a float and returns the bit equivalent 32-bit integer.
Definition: MathExtras.h:592
wpi::minIntN
int64_t minIntN(int64_t N)
Gets the minimum value for a N-bit signed integer.
Definition: MathExtras.h:379
wpi::count
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:1092
wpi::DoubleToBits
uint64_t DoubleToBits(double Double)
This function takes a double and returns the bit equivalent 64-bit integer.
Definition: MathExtras.h:582
wpi::maskLeadingZeros
T maskLeadingZeros(unsigned N)
Create a bitmask with the N left-most bits set to 0, and all other bits set to 1.
Definition: MathExtras.h:230
wpi::BitReverseTable256
static const unsigned char BitReverseTable256[256]
Macro compressed bit reversal table for 256 bits.
Definition: MathExtras.h:254
wpi::divideCeil
uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition: MathExtras.h:690
wpi::alignAddr
uintptr_t alignAddr(const void *Addr, size_t Alignment)
Aligns Addr to Alignment bytes, rounding up.
Definition: MathExtras.h:614
wpi::detail::PopulationCounter
Definition: MathExtras.h:477
wpi::isShiftedMask_32
constexpr bool isShiftedMask_32(uint32_t Value)
Return true if the argument contains a non-empty sequence of ones with the remainder zero (32 bit ver...
Definition: MathExtras.h:423
wpi::AlignTo::from_value
Definition: MathExtras.h:702
wpi::countPopulation
unsigned countPopulation(T Value)
Count the number of set bits in a value.
Definition: MathExtras.h:511
wpi::Log2_64_Ceil
unsigned Log2_64_Ceil(uint64_t Value)
Return the ceil log base 2 of the specified value, 64 if the value is zero.
Definition: MathExtras.h:549
wpi::GreatestCommonDivisor64
uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B)
Return the greatest common divisor of the values using Euclid's algorithm.
Definition: MathExtras.h:554