• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <cassert>
20 #include <cstring>
21 #include <type_traits>
22 
23 #ifdef _MSC_VER
24 #include <intrin.h>
25 #include <limits>
26 #endif
27 
28 namespace llvm {
29 /// \brief The behavior an operation has on an input of 0.
30 enum ZeroBehavior {
31   /// \brief The returned value is undefined.
32   ZB_Undefined,
33   /// \brief The returned value is numeric_limits<T>::max()
34   ZB_Max,
35   /// \brief The returned value is numeric_limits<T>::digits
36   ZB_Width
37 };
38 
39 /// \brief Count number of 0's from the least significant bit to the most
40 ///   stopping at the first 1.
41 ///
42 /// Only unsigned integral types are allowed.
43 ///
44 /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
45 ///   valid arguments.
46 template <typename T>
47 typename std::enable_if<std::numeric_limits<T>::is_integer &&
48                         !std::numeric_limits<T>::is_signed, std::size_t>::type
49 countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
50   (void)ZB;
51 
52   if (!Val)
53     return std::numeric_limits<T>::digits;
54   if (Val & 0x1)
55     return 0;
56 
57   // Bisection method.
58   std::size_t ZeroBits = 0;
59   T Shift = std::numeric_limits<T>::digits >> 1;
60   T Mask = std::numeric_limits<T>::max() >> Shift;
61   while (Shift) {
62     if ((Val & Mask) == 0) {
63       Val >>= Shift;
64       ZeroBits |= Shift;
65     }
66     Shift >>= 1;
67     Mask >>= Shift;
68   }
69   return ZeroBits;
70 }
71 
72 // Disable signed.
73 template <typename T>
74 typename std::enable_if<std::numeric_limits<T>::is_integer &&
75                         std::numeric_limits<T>::is_signed, std::size_t>::type
76 countTrailingZeros(T Val, ZeroBehavior ZB = ZB_Width) LLVM_DELETED_FUNCTION;
77 
78 #if __GNUC__ >= 4 || _MSC_VER
79 template <>
80 inline std::size_t countTrailingZeros<uint32_t>(uint32_t Val, ZeroBehavior ZB) {
81   if (ZB != ZB_Undefined && Val == 0)
82     return 32;
83 
84 #if __has_builtin(__builtin_ctz) || __GNUC_PREREQ(4, 0)
85   return __builtin_ctz(Val);
86 #elif _MSC_VER
87   unsigned long Index;
88   _BitScanForward(&Index, Val);
89   return Index;
90 #endif
91 }
92 
93 #if !defined(_MSC_VER) || defined(_M_X64)
94 template <>
95 inline std::size_t countTrailingZeros<uint64_t>(uint64_t Val, ZeroBehavior ZB) {
96   if (ZB != ZB_Undefined && Val == 0)
97     return 64;
98 
99 #if __has_builtin(__builtin_ctzll) || __GNUC_PREREQ(4, 0)
100   return __builtin_ctzll(Val);
101 #elif _MSC_VER
102   unsigned long Index;
103   _BitScanForward64(&Index, Val);
104   return Index;
105 #endif
106 }
107 #endif
108 #endif
109 
110 /// \brief Count number of 0's from the most significant bit to the least
111 ///   stopping at the first 1.
112 ///
113 /// Only unsigned integral types are allowed.
114 ///
115 /// \param ZB the behavior on an input of 0. Only ZB_Width and ZB_Undefined are
116 ///   valid arguments.
117 template <typename T>
118 typename std::enable_if<std::numeric_limits<T>::is_integer &&
119                         !std::numeric_limits<T>::is_signed, std::size_t>::type
120 countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) {
121   (void)ZB;
122 
123   if (!Val)
124     return std::numeric_limits<T>::digits;
125 
126   // Bisection method.
127   std::size_t ZeroBits = 0;
128   for (T Shift = std::numeric_limits<T>::digits >> 1; Shift; Shift >>= 1) {
129     T Tmp = Val >> Shift;
130     if (Tmp)
131       Val = Tmp;
132     else
133       ZeroBits |= Shift;
134   }
135   return ZeroBits;
136 }
137 
138 // Disable signed.
139 template <typename T>
140 typename std::enable_if<std::numeric_limits<T>::is_integer &&
141                         std::numeric_limits<T>::is_signed, std::size_t>::type
142 countLeadingZeros(T Val, ZeroBehavior ZB = ZB_Width) LLVM_DELETED_FUNCTION;
143 
144 #if __GNUC__ >= 4 || _MSC_VER
145 template <>
146 inline std::size_t countLeadingZeros<uint32_t>(uint32_t Val, ZeroBehavior ZB) {
147   if (ZB != ZB_Undefined && Val == 0)
148     return 32;
149 
150 #if __has_builtin(__builtin_clz) || __GNUC_PREREQ(4, 0)
151   return __builtin_clz(Val);
152 #elif _MSC_VER
153   unsigned long Index;
154   _BitScanReverse(&Index, Val);
155   return Index ^ 31;
156 #endif
157 }
158 
159 #if !defined(_MSC_VER) || defined(_M_X64)
160 template <>
161 inline std::size_t countLeadingZeros<uint64_t>(uint64_t Val, ZeroBehavior ZB) {
162   if (ZB != ZB_Undefined && Val == 0)
163     return 64;
164 
165 #if __has_builtin(__builtin_clzll) || __GNUC_PREREQ(4, 0)
166   return __builtin_clzll(Val);
167 #elif _MSC_VER
168   unsigned long Index;
169   _BitScanReverse64(&Index, Val);
170   return Index ^ 63;
171 #endif
172 }
173 #endif
174 #endif
175 
176 /// \brief Get the index of the first set bit starting from the least
177 ///   significant bit.
178 ///
179 /// Only unsigned integral types are allowed.
180 ///
181 /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
182 ///   valid arguments.
183 template <typename T>
184 typename std::enable_if<std::numeric_limits<T>::is_integer &&
185                        !std::numeric_limits<T>::is_signed, T>::type
186 findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
187   if (ZB == ZB_Max && Val == 0)
188     return std::numeric_limits<T>::max();
189 
190   return countTrailingZeros(Val, ZB_Undefined);
191 }
192 
193 // Disable signed.
194 template <typename T>
195 typename std::enable_if<std::numeric_limits<T>::is_integer &&
196                         std::numeric_limits<T>::is_signed, T>::type
197 findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) LLVM_DELETED_FUNCTION;
198 
199 /// \brief Get the index of the last set bit starting from the least
200 ///   significant bit.
201 ///
202 /// Only unsigned integral types are allowed.
203 ///
204 /// \param ZB the behavior on an input of 0. Only ZB_Max and ZB_Undefined are
205 ///   valid arguments.
206 template <typename T>
207 typename std::enable_if<std::numeric_limits<T>::is_integer &&
208                         !std::numeric_limits<T>::is_signed, T>::type
209 findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
210   if (ZB == ZB_Max && Val == 0)
211     return std::numeric_limits<T>::max();
212 
213   // Use ^ instead of - because both gcc and llvm can remove the associated ^
214   // in the __builtin_clz intrinsic on x86.
215   return countLeadingZeros(Val, ZB_Undefined) ^
216          (std::numeric_limits<T>::digits - 1);
217 }
218 
219 // Disable signed.
220 template <typename T>
221 typename std::enable_if<std::numeric_limits<T>::is_integer &&
222                         std::numeric_limits<T>::is_signed, T>::type
223 findLastSet(T Val, ZeroBehavior ZB = ZB_Max) LLVM_DELETED_FUNCTION;
224 
225 /// \brief Macro compressed bit reversal table for 256 bits.
226 ///
227 /// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
228 static const unsigned char BitReverseTable256[256] = {
229 #define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
230 #define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
231 #define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
232   R6(0), R6(2), R6(1), R6(3)
233 #undef R2
234 #undef R4
235 #undef R6
236 };
237 
238 /// \brief Reverse the bits in \p Val.
239 template <typename T>
reverseBits(T Val)240 T reverseBits(T Val) {
241   unsigned char in[sizeof(Val)];
242   unsigned char out[sizeof(Val)];
243   std::memcpy(in, &Val, sizeof(Val));
244   for (unsigned i = 0; i < sizeof(Val); ++i)
245     out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
246   std::memcpy(&Val, out, sizeof(Val));
247   return Val;
248 }
249 
250 // NOTE: The following support functions use the _32/_64 extensions instead of
251 // type overloading so that signed and unsigned integers can be used without
252 // ambiguity.
253 
254 /// Hi_32 - This function returns the high 32 bits of a 64 bit value.
Hi_32(uint64_t Value)255 inline uint32_t Hi_32(uint64_t Value) {
256   return static_cast<uint32_t>(Value >> 32);
257 }
258 
259 /// Lo_32 - This function returns the low 32 bits of a 64 bit value.
Lo_32(uint64_t Value)260 inline uint32_t Lo_32(uint64_t Value) {
261   return static_cast<uint32_t>(Value);
262 }
263 
264 /// Make_64 - This functions makes a 64-bit integer from a high / low pair of
265 ///           32-bit integers.
Make_64(uint32_t High,uint32_t Low)266 inline uint64_t Make_64(uint32_t High, uint32_t Low) {
267   return ((uint64_t)High << 32) | (uint64_t)Low;
268 }
269 
270 /// isInt - Checks if an integer fits into the given bit width.
271 template<unsigned N>
isInt(int64_t x)272 inline bool isInt(int64_t x) {
273   return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
274 }
275 // Template specializations to get better code for common cases.
276 template<>
277 inline bool isInt<8>(int64_t x) {
278   return static_cast<int8_t>(x) == x;
279 }
280 template<>
281 inline bool isInt<16>(int64_t x) {
282   return static_cast<int16_t>(x) == x;
283 }
284 template<>
285 inline bool isInt<32>(int64_t x) {
286   return static_cast<int32_t>(x) == x;
287 }
288 
289 /// isShiftedInt<N,S> - Checks if a signed integer is an N bit number shifted
290 ///                     left by S.
291 template<unsigned N, unsigned S>
isShiftedInt(int64_t x)292 inline bool isShiftedInt(int64_t x) {
293   return isInt<N+S>(x) && (x % (1<<S) == 0);
294 }
295 
296 /// isUInt - Checks if an unsigned integer fits into the given bit width.
297 template<unsigned N>
isUInt(uint64_t x)298 inline bool isUInt(uint64_t x) {
299   return N >= 64 || x < (UINT64_C(1)<<(N));
300 }
301 // Template specializations to get better code for common cases.
302 template<>
303 inline bool isUInt<8>(uint64_t x) {
304   return static_cast<uint8_t>(x) == x;
305 }
306 template<>
307 inline bool isUInt<16>(uint64_t x) {
308   return static_cast<uint16_t>(x) == x;
309 }
310 template<>
311 inline bool isUInt<32>(uint64_t x) {
312   return static_cast<uint32_t>(x) == x;
313 }
314 
315 /// isShiftedUInt<N,S> - Checks if a unsigned integer is an N bit number shifted
316 ///                     left by S.
317 template<unsigned N, unsigned S>
isShiftedUInt(uint64_t x)318 inline bool isShiftedUInt(uint64_t x) {
319   return isUInt<N+S>(x) && (x % (1<<S) == 0);
320 }
321 
322 /// isUIntN - Checks if an unsigned integer fits into the given (dynamic)
323 /// bit width.
isUIntN(unsigned N,uint64_t x)324 inline bool isUIntN(unsigned N, uint64_t x) {
325   return x == (x & (~0ULL >> (64 - N)));
326 }
327 
328 /// isIntN - Checks if an signed integer fits into the given (dynamic)
329 /// bit width.
isIntN(unsigned N,int64_t x)330 inline bool isIntN(unsigned N, int64_t x) {
331   return N >= 64 || (-(INT64_C(1)<<(N-1)) <= x && x < (INT64_C(1)<<(N-1)));
332 }
333 
334 /// isMask_32 - This function returns true if the argument is a sequence of ones
335 /// starting at the least significant bit with the remainder zero (32 bit
336 /// version).   Ex. isMask_32(0x0000FFFFU) == true.
isMask_32(uint32_t Value)337 inline bool isMask_32(uint32_t Value) {
338   return Value && ((Value + 1) & Value) == 0;
339 }
340 
341 /// isMask_64 - This function returns true if the argument is a sequence of ones
342 /// starting at the least significant bit with the remainder zero (64 bit
343 /// version).
isMask_64(uint64_t Value)344 inline bool isMask_64(uint64_t Value) {
345   return Value && ((Value + 1) & Value) == 0;
346 }
347 
348 /// isShiftedMask_32 - This function returns true if the argument contains a
349 /// sequence of ones with the remainder zero (32 bit version.)
350 /// Ex. isShiftedMask_32(0x0000FF00U) == true.
isShiftedMask_32(uint32_t Value)351 inline bool isShiftedMask_32(uint32_t Value) {
352   return isMask_32((Value - 1) | Value);
353 }
354 
355 /// isShiftedMask_64 - This function returns true if the argument contains a
356 /// sequence of ones with the remainder zero (64 bit version.)
isShiftedMask_64(uint64_t Value)357 inline bool isShiftedMask_64(uint64_t Value) {
358   return isMask_64((Value - 1) | Value);
359 }
360 
361 /// isPowerOf2_32 - This function returns true if the argument is a power of
362 /// two > 0. Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
isPowerOf2_32(uint32_t Value)363 inline bool isPowerOf2_32(uint32_t Value) {
364   return Value && !(Value & (Value - 1));
365 }
366 
367 /// isPowerOf2_64 - This function returns true if the argument is a power of two
368 /// > 0 (64 bit edition.)
isPowerOf2_64(uint64_t Value)369 inline bool isPowerOf2_64(uint64_t Value) {
370   return Value && !(Value & (Value - int64_t(1L)));
371 }
372 
373 /// ByteSwap_16 - This function returns a byte-swapped representation of the
374 /// 16-bit argument, Value.
ByteSwap_16(uint16_t Value)375 inline uint16_t ByteSwap_16(uint16_t Value) {
376   return sys::SwapByteOrder_16(Value);
377 }
378 
379 /// ByteSwap_32 - This function returns a byte-swapped representation of the
380 /// 32-bit argument, Value.
ByteSwap_32(uint32_t Value)381 inline uint32_t ByteSwap_32(uint32_t Value) {
382   return sys::SwapByteOrder_32(Value);
383 }
384 
385 /// ByteSwap_64 - This function returns a byte-swapped representation of the
386 /// 64-bit argument, Value.
ByteSwap_64(uint64_t Value)387 inline uint64_t ByteSwap_64(uint64_t Value) {
388   return sys::SwapByteOrder_64(Value);
389 }
390 
391 /// CountLeadingOnes_32 - this function performs the operation of
392 /// counting the number of ones from the most significant bit to the first zero
393 /// bit.  Ex. CountLeadingOnes_32(0xFF0FFF00) == 8.
394 /// Returns 32 if the word is all ones.
CountLeadingOnes_32(uint32_t Value)395 inline unsigned CountLeadingOnes_32(uint32_t Value) {
396   return countLeadingZeros(~Value);
397 }
398 
399 /// CountLeadingOnes_64 - This function performs the operation
400 /// of counting the number of ones from the most significant bit to the first
401 /// zero bit (64 bit edition.)
402 /// Returns 64 if the word is all ones.
CountLeadingOnes_64(uint64_t Value)403 inline unsigned CountLeadingOnes_64(uint64_t Value) {
404   return countLeadingZeros(~Value);
405 }
406 
407 /// CountTrailingOnes_32 - this function performs the operation of
408 /// counting the number of ones from the least significant bit to the first zero
409 /// bit.  Ex. CountTrailingOnes_32(0x00FF00FF) == 8.
410 /// Returns 32 if the word is all ones.
CountTrailingOnes_32(uint32_t Value)411 inline unsigned CountTrailingOnes_32(uint32_t Value) {
412   return countTrailingZeros(~Value);
413 }
414 
415 /// CountTrailingOnes_64 - This function performs the operation
416 /// of counting the number of ones from the least significant bit to the first
417 /// zero bit (64 bit edition.)
418 /// Returns 64 if the word is all ones.
CountTrailingOnes_64(uint64_t Value)419 inline unsigned CountTrailingOnes_64(uint64_t Value) {
420   return countTrailingZeros(~Value);
421 }
422 
423 /// CountPopulation_32 - this function counts the number of set bits in a value.
424 /// Ex. CountPopulation(0xF000F000) = 8
425 /// Returns 0 if the word is zero.
CountPopulation_32(uint32_t Value)426 inline unsigned CountPopulation_32(uint32_t Value) {
427 #if __GNUC__ >= 4
428   return __builtin_popcount(Value);
429 #else
430   uint32_t v = Value - ((Value >> 1) & 0x55555555);
431   v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
432   return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
433 #endif
434 }
435 
436 /// CountPopulation_64 - this function counts the number of set bits in a value,
437 /// (64 bit edition.)
CountPopulation_64(uint64_t Value)438 inline unsigned CountPopulation_64(uint64_t Value) {
439 #if __GNUC__ >= 4
440   return __builtin_popcountll(Value);
441 #else
442   uint64_t v = Value - ((Value >> 1) & 0x5555555555555555ULL);
443   v = (v & 0x3333333333333333ULL) + ((v >> 2) & 0x3333333333333333ULL);
444   v = (v + (v >> 4)) & 0x0F0F0F0F0F0F0F0FULL;
445   return unsigned((uint64_t)(v * 0x0101010101010101ULL) >> 56);
446 #endif
447 }
448 
449 /// Log2_32 - This function returns the floor log base 2 of the specified value,
450 /// -1 if the value is zero. (32 bit edition.)
451 /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
Log2_32(uint32_t Value)452 inline unsigned Log2_32(uint32_t Value) {
453   return 31 - countLeadingZeros(Value);
454 }
455 
456 /// Log2_64 - This function returns the floor log base 2 of the specified value,
457 /// -1 if the value is zero. (64 bit edition.)
Log2_64(uint64_t Value)458 inline unsigned Log2_64(uint64_t Value) {
459   return 63 - countLeadingZeros(Value);
460 }
461 
462 /// Log2_32_Ceil - This function returns the ceil log base 2 of the specified
463 /// value, 32 if the value is zero. (32 bit edition).
464 /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
Log2_32_Ceil(uint32_t Value)465 inline unsigned Log2_32_Ceil(uint32_t Value) {
466   return 32 - countLeadingZeros(Value - 1);
467 }
468 
469 /// Log2_64_Ceil - This function returns the ceil log base 2 of the specified
470 /// value, 64 if the value is zero. (64 bit edition.)
Log2_64_Ceil(uint64_t Value)471 inline unsigned Log2_64_Ceil(uint64_t Value) {
472   return 64 - countLeadingZeros(Value - 1);
473 }
474 
475 /// GreatestCommonDivisor64 - Return the greatest common divisor of the two
476 /// values using Euclid's algorithm.
GreatestCommonDivisor64(uint64_t A,uint64_t B)477 inline uint64_t GreatestCommonDivisor64(uint64_t A, uint64_t B) {
478   while (B) {
479     uint64_t T = B;
480     B = A % B;
481     A = T;
482   }
483   return A;
484 }
485 
486 /// BitsToDouble - This function takes a 64-bit integer and returns the bit
487 /// equivalent double.
BitsToDouble(uint64_t Bits)488 inline double BitsToDouble(uint64_t Bits) {
489   union {
490     uint64_t L;
491     double D;
492   } T;
493   T.L = Bits;
494   return T.D;
495 }
496 
497 /// BitsToFloat - This function takes a 32-bit integer and returns the bit
498 /// equivalent float.
BitsToFloat(uint32_t Bits)499 inline float BitsToFloat(uint32_t Bits) {
500   union {
501     uint32_t I;
502     float F;
503   } T;
504   T.I = Bits;
505   return T.F;
506 }
507 
508 /// DoubleToBits - This function takes a double and returns the bit
509 /// equivalent 64-bit integer.  Note that copying doubles around
510 /// changes the bits of NaNs on some hosts, notably x86, so this
511 /// routine cannot be used if these bits are needed.
DoubleToBits(double Double)512 inline uint64_t DoubleToBits(double Double) {
513   union {
514     uint64_t L;
515     double D;
516   } T;
517   T.D = Double;
518   return T.L;
519 }
520 
521 /// FloatToBits - This function takes a float and returns the bit
522 /// equivalent 32-bit integer.  Note that copying floats around
523 /// changes the bits of NaNs on some hosts, notably x86, so this
524 /// routine cannot be used if these bits are needed.
FloatToBits(float Float)525 inline uint32_t FloatToBits(float Float) {
526   union {
527     uint32_t I;
528     float F;
529   } T;
530   T.F = Float;
531   return T.I;
532 }
533 
534 /// Platform-independent wrappers for the C99 isnan() function.
535 int IsNAN(float f);
536 int IsNAN(double d);
537 
538 /// Platform-independent wrappers for the C99 isinf() function.
539 int IsInf(float f);
540 int IsInf(double d);
541 
542 /// MinAlign - A and B are either alignments or offsets.  Return the minimum
543 /// alignment that may be assumed after adding the two together.
MinAlign(uint64_t A,uint64_t B)544 inline uint64_t MinAlign(uint64_t A, uint64_t B) {
545   // The largest power of 2 that divides both A and B.
546   //
547   // Replace "-Value" by "1+~Value" in the following commented code to avoid
548   // MSVC warning C4146
549   //    return (A | B) & -(A | B);
550   return (A | B) & (1 + ~(A | B));
551 }
552 
553 /// \brief Aligns \c Ptr to \c Alignment bytes, rounding up.
554 ///
555 /// Alignment should be a power of two.  This method rounds up, so
556 /// AlignPtr(7, 4) == 8 and AlignPtr(8, 4) == 8.
alignPtr(char * Ptr,size_t Alignment)557 inline char *alignPtr(char *Ptr, size_t Alignment) {
558   assert(Alignment && isPowerOf2_64((uint64_t)Alignment) &&
559          "Alignment is not a power of two!");
560 
561   return (char *)(((uintptr_t)Ptr + Alignment - 1) &
562                   ~(uintptr_t)(Alignment - 1));
563 }
564 
565 /// NextPowerOf2 - Returns the next power of two (in 64-bits)
566 /// that is strictly greater than A.  Returns zero on overflow.
NextPowerOf2(uint64_t A)567 inline uint64_t NextPowerOf2(uint64_t A) {
568   A |= (A >> 1);
569   A |= (A >> 2);
570   A |= (A >> 4);
571   A |= (A >> 8);
572   A |= (A >> 16);
573   A |= (A >> 32);
574   return A + 1;
575 }
576 
577 /// Returns the power of two which is less than or equal to the given value.
578 /// Essentially, it is a floor operation across the domain of powers of two.
PowerOf2Floor(uint64_t A)579 inline uint64_t PowerOf2Floor(uint64_t A) {
580   if (!A) return 0;
581   return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
582 }
583 
584 /// Returns the next integer (mod 2**64) that is greater than or equal to
585 /// \p Value and is a multiple of \p Align. \p Align must be non-zero.
586 ///
587 /// Examples:
588 /// \code
589 ///   RoundUpToAlignment(5, 8) = 8
590 ///   RoundUpToAlignment(17, 8) = 24
591 ///   RoundUpToAlignment(~0LL, 8) = 0
592 /// \endcode
RoundUpToAlignment(uint64_t Value,uint64_t Align)593 inline uint64_t RoundUpToAlignment(uint64_t Value, uint64_t Align) {
594   return ((Value + Align - 1) / Align) * Align;
595 }
596 
597 /// Returns the offset to the next integer (mod 2**64) that is greater than
598 /// or equal to \p Value and is a multiple of \p Align. \p Align must be
599 /// non-zero.
OffsetToAlignment(uint64_t Value,uint64_t Align)600 inline uint64_t OffsetToAlignment(uint64_t Value, uint64_t Align) {
601   return RoundUpToAlignment(Value, Align) - Value;
602 }
603 
604 /// abs64 - absolute value of a 64-bit int.  Not all environments support
605 /// "abs" on whatever their name for the 64-bit int type is.  The absolute
606 /// value of the largest negative number is undefined, as with "abs".
abs64(int64_t x)607 inline int64_t abs64(int64_t x) {
608   return (x < 0) ? -x : x;
609 }
610 
611 /// SignExtend32 - Sign extend B-bit number x to 32-bit int.
612 /// Usage int32_t r = SignExtend32<5>(x);
SignExtend32(uint32_t x)613 template <unsigned B> inline int32_t SignExtend32(uint32_t x) {
614   return int32_t(x << (32 - B)) >> (32 - B);
615 }
616 
617 /// \brief Sign extend number in the bottom B bits of X to a 32-bit int.
618 /// Requires 0 < B <= 32.
SignExtend32(uint32_t X,unsigned B)619 inline int32_t SignExtend32(uint32_t X, unsigned B) {
620   return int32_t(X << (32 - B)) >> (32 - B);
621 }
622 
623 /// SignExtend64 - Sign extend B-bit number x to 64-bit int.
624 /// Usage int64_t r = SignExtend64<5>(x);
SignExtend64(uint64_t x)625 template <unsigned B> inline int64_t SignExtend64(uint64_t x) {
626   return int64_t(x << (64 - B)) >> (64 - B);
627 }
628 
629 /// \brief Sign extend number in the bottom B bits of X to a 64-bit int.
630 /// Requires 0 < B <= 64.
SignExtend64(uint64_t X,unsigned B)631 inline int64_t SignExtend64(uint64_t X, unsigned B) {
632   return int64_t(X << (64 - B)) >> (64 - B);
633 }
634 
635 #if defined(_MSC_VER)
636   // Visual Studio defines the HUGE_VAL class of macros using purposeful
637   // constant arithmetic overflow, which it then warns on when encountered.
638   const float huge_valf = std::numeric_limits<float>::infinity();
639 #else
640   const float huge_valf = HUGE_VALF;
641 #endif
642 } // End llvm namespace
643 
644 #endif
645