xref: /freebsd/contrib/llvm-project/llvm/include/llvm/Support/MathExtras.h (revision 700637cbb5e582861067a11aaca4d053546871d2)
1 //===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file contains some functions that are useful for math stuff.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_SUPPORT_MATHEXTRAS_H
14 #define LLVM_SUPPORT_MATHEXTRAS_H
15 
16 #include "llvm/ADT/bit.h"
17 #include "llvm/Support/Compiler.h"
18 #include <cassert>
19 #include <climits>
20 #include <cstdint>
21 #include <cstring>
22 #include <limits>
23 #include <type_traits>
24 
25 namespace llvm {
26 /// Some template parameter helpers to optimize for bitwidth, for functions that
27 /// take multiple arguments.
28 
29 // We can't verify signedness, since callers rely on implicit coercions to
30 // signed/unsigned.
31 template <typename T, typename U>
32 using enableif_int =
33     std::enable_if_t<std::is_integral_v<T> && std::is_integral_v<U>>;
34 
35 // Use std::common_type_t to widen only up to the widest argument.
36 template <typename T, typename U, typename = enableif_int<T, U>>
37 using common_uint =
38     std::common_type_t<std::make_unsigned_t<T>, std::make_unsigned_t<U>>;
39 template <typename T, typename U, typename = enableif_int<T, U>>
40 using common_sint =
41     std::common_type_t<std::make_signed_t<T>, std::make_signed_t<U>>;
42 
43 /// Mathematical constants.
44 namespace numbers {
45 // TODO: Track C++20 std::numbers.
46 // clang-format off
47 constexpr double e          = 0x1.5bf0a8b145769P+1, // (2.7182818284590452354) https://oeis.org/A001113
48                  egamma     = 0x1.2788cfc6fb619P-1, // (.57721566490153286061) https://oeis.org/A001620
49                  ln2        = 0x1.62e42fefa39efP-1, // (.69314718055994530942) https://oeis.org/A002162
50                  ln10       = 0x1.26bb1bbb55516P+1, // (2.3025850929940456840) https://oeis.org/A002392
51                  log2e      = 0x1.71547652b82feP+0, // (1.4426950408889634074)
52                  log10e     = 0x1.bcb7b1526e50eP-2, // (.43429448190325182765)
53                  pi         = 0x1.921fb54442d18P+1, // (3.1415926535897932385) https://oeis.org/A000796
54                  inv_pi     = 0x1.45f306dc9c883P-2, // (.31830988618379067154) https://oeis.org/A049541
55                  sqrtpi     = 0x1.c5bf891b4ef6bP+0, // (1.7724538509055160273) https://oeis.org/A002161
56                  inv_sqrtpi = 0x1.20dd750429b6dP-1, // (.56418958354775628695) https://oeis.org/A087197
57                  sqrt2      = 0x1.6a09e667f3bcdP+0, // (1.4142135623730950488) https://oeis.org/A00219
58                  inv_sqrt2  = 0x1.6a09e667f3bcdP-1, // (.70710678118654752440)
59                  sqrt3      = 0x1.bb67ae8584caaP+0, // (1.7320508075688772935) https://oeis.org/A002194
60                  inv_sqrt3  = 0x1.279a74590331cP-1, // (.57735026918962576451)
61                  phi        = 0x1.9e3779b97f4a8P+0; // (1.6180339887498948482) https://oeis.org/A001622
62 constexpr float ef          = 0x1.5bf0a8P+1F, // (2.71828183) https://oeis.org/A001113
63                 egammaf     = 0x1.2788d0P-1F, // (.577215665) https://oeis.org/A001620
64                 ln2f        = 0x1.62e430P-1F, // (.693147181) https://oeis.org/A002162
65                 ln10f       = 0x1.26bb1cP+1F, // (2.30258509) https://oeis.org/A002392
66                 log2ef      = 0x1.715476P+0F, // (1.44269504)
67                 log10ef     = 0x1.bcb7b2P-2F, // (.434294482)
68                 pif         = 0x1.921fb6P+1F, // (3.14159265) https://oeis.org/A000796
69                 inv_pif     = 0x1.45f306P-2F, // (.318309886) https://oeis.org/A049541
70                 sqrtpif     = 0x1.c5bf8aP+0F, // (1.77245385) https://oeis.org/A002161
71                 inv_sqrtpif = 0x1.20dd76P-1F, // (.564189584) https://oeis.org/A087197
72                 sqrt2f      = 0x1.6a09e6P+0F, // (1.41421356) https://oeis.org/A002193
73                 inv_sqrt2f  = 0x1.6a09e6P-1F, // (.707106781)
74                 sqrt3f      = 0x1.bb67aeP+0F, // (1.73205081) https://oeis.org/A002194
75                 inv_sqrt3f  = 0x1.279a74P-1F, // (.577350269)
76                 phif        = 0x1.9e377aP+0F; // (1.61803399) https://oeis.org/A001622
77 // clang-format on
78 } // namespace numbers
79 
80 /// Create a bitmask with the N right-most bits set to 1, and all other
81 /// bits set to 0.  Only unsigned types are allowed.
maskTrailingOnes(unsigned N)82 template <typename T> constexpr T maskTrailingOnes(unsigned N) {
83   static_assert(std::is_unsigned_v<T>, "Invalid type!");
84   const unsigned Bits = CHAR_BIT * sizeof(T);
85   assert(N <= Bits && "Invalid bit index");
86   if (N == 0)
87     return 0;
88   return T(-1) >> (Bits - N);
89 }
90 
91 /// Create a bitmask with the N left-most bits set to 1, and all other
92 /// bits set to 0.  Only unsigned types are allowed.
maskLeadingOnes(unsigned N)93 template <typename T> constexpr T maskLeadingOnes(unsigned N) {
94   return ~maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
95 }
96 
97 /// Create a bitmask with the N right-most bits set to 0, and all other
98 /// bits set to 1.  Only unsigned types are allowed.
maskTrailingZeros(unsigned N)99 template <typename T> constexpr T maskTrailingZeros(unsigned N) {
100   return maskLeadingOnes<T>(CHAR_BIT * sizeof(T) - N);
101 }
102 
103 /// Create a bitmask with the N left-most bits set to 0, and all other
104 /// bits set to 1.  Only unsigned types are allowed.
maskLeadingZeros(unsigned N)105 template <typename T> constexpr T maskLeadingZeros(unsigned N) {
106   return maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
107 }
108 
109 /// Macro compressed bit reversal table for 256 bits.
110 ///
111 /// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
112 static const unsigned char BitReverseTable256[256] = {
113 #define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
114 #define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
115 #define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
116   R6(0), R6(2), R6(1), R6(3)
117 #undef R2
118 #undef R4
119 #undef R6
120 };
121 
122 /// Reverse the bits in \p Val.
reverseBits(T Val)123 template <typename T> constexpr T reverseBits(T Val) {
124 #if __has_builtin(__builtin_bitreverse8)
125   if constexpr (std::is_same_v<T, uint8_t>)
126     return __builtin_bitreverse8(Val);
127 #endif
128 #if __has_builtin(__builtin_bitreverse16)
129   if constexpr (std::is_same_v<T, uint16_t>)
130     return __builtin_bitreverse16(Val);
131 #endif
132 #if __has_builtin(__builtin_bitreverse32)
133   if constexpr (std::is_same_v<T, uint32_t>)
134     return __builtin_bitreverse32(Val);
135 #endif
136 #if __has_builtin(__builtin_bitreverse64)
137   if constexpr (std::is_same_v<T, uint64_t>)
138     return __builtin_bitreverse64(Val);
139 #endif
140 
141   unsigned char in[sizeof(Val)];
142   unsigned char out[sizeof(Val)];
143   std::memcpy(in, &Val, sizeof(Val));
144   for (unsigned i = 0; i < sizeof(Val); ++i)
145     out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
146   std::memcpy(&Val, out, sizeof(Val));
147   return Val;
148 }
149 
150 // NOTE: The following support functions use the _32/_64 extensions instead of
151 // type overloading so that signed and unsigned integers can be used without
152 // ambiguity.
153 
154 /// Return the high 32 bits of a 64 bit value.
Hi_32(uint64_t Value)155 constexpr uint32_t Hi_32(uint64_t Value) {
156   return static_cast<uint32_t>(Value >> 32);
157 }
158 
159 /// Return the low 32 bits of a 64 bit value.
Lo_32(uint64_t Value)160 constexpr uint32_t Lo_32(uint64_t Value) {
161   return static_cast<uint32_t>(Value);
162 }
163 
164 /// Make a 64-bit integer from a high / low pair of 32-bit integers.
Make_64(uint32_t High,uint32_t Low)165 constexpr uint64_t Make_64(uint32_t High, uint32_t Low) {
166   return ((uint64_t)High << 32) | (uint64_t)Low;
167 }
168 
169 /// Checks if an integer fits into the given bit width.
isInt(int64_t x)170 template <unsigned N> constexpr bool isInt(int64_t x) {
171   if constexpr (N == 0)
172     return 0 == x;
173   if constexpr (N == 8)
174     return static_cast<int8_t>(x) == x;
175   if constexpr (N == 16)
176     return static_cast<int16_t>(x) == x;
177   if constexpr (N == 32)
178     return static_cast<int32_t>(x) == x;
179   if constexpr (N < 64)
180     return -(INT64_C(1) << (N - 1)) <= x && x < (INT64_C(1) << (N - 1));
181   (void)x; // MSVC v19.25 warns that x is unused.
182   return true;
183 }
184 
185 /// Checks if a signed integer is an N bit number shifted left by S.
186 template <unsigned N, unsigned S>
isShiftedInt(int64_t x)187 constexpr bool isShiftedInt(int64_t x) {
188   static_assert(S < 64, "isShiftedInt<N, S> with S >= 64 is too much.");
189   static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
190   return isInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
191 }
192 
193 /// Checks if an unsigned integer fits into the given bit width.
isUInt(uint64_t x)194 template <unsigned N> constexpr bool isUInt(uint64_t x) {
195   if constexpr (N == 0)
196     return 0 == x;
197   if constexpr (N == 8)
198     return static_cast<uint8_t>(x) == x;
199   if constexpr (N == 16)
200     return static_cast<uint16_t>(x) == x;
201   if constexpr (N == 32)
202     return static_cast<uint32_t>(x) == x;
203   if constexpr (N < 64)
204     return x < (UINT64_C(1) << (N));
205   (void)x; // MSVC v19.25 warns that x is unused.
206   return true;
207 }
208 
209 /// Checks if a unsigned integer is an N bit number shifted left by S.
210 template <unsigned N, unsigned S>
isShiftedUInt(uint64_t x)211 constexpr bool isShiftedUInt(uint64_t x) {
212   static_assert(S < 64, "isShiftedUInt<N, S> with S >= 64 is too much.");
213   static_assert(N + S <= 64,
214                 "isShiftedUInt<N, S> with N + S > 64 is too wide.");
215   // S must be strictly less than 64. So 1 << S is not undefined behavior.
216   return isUInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
217 }
218 
219 /// Gets the maximum value for a N-bit unsigned integer.
maxUIntN(uint64_t N)220 inline constexpr uint64_t maxUIntN(uint64_t N) {
221   assert(N <= 64 && "integer width out of range");
222 
223   // uint64_t(1) << 64 is undefined behavior, so we can't do
224   //   (uint64_t(1) << N) - 1
225   // without checking first that N != 64.  But this works and doesn't have a
226   // branch for N != 0.
227   // Unfortunately, shifting a uint64_t right by 64 bit is undefined
228   // behavior, so the condition on N == 0 is necessary. Fortunately, most
229   // optimizers do not emit branches for this check.
230   if (N == 0)
231     return 0;
232   return UINT64_MAX >> (64 - N);
233 }
234 
235 /// Gets the minimum value for a N-bit signed integer.
minIntN(int64_t N)236 inline constexpr int64_t minIntN(int64_t N) {
237   assert(N <= 64 && "integer width out of range");
238 
239   if (N == 0)
240     return 0;
241   return UINT64_C(1) + ~(UINT64_C(1) << (N - 1));
242 }
243 
244 /// Gets the maximum value for a N-bit signed integer.
maxIntN(int64_t N)245 inline constexpr int64_t maxIntN(int64_t N) {
246   assert(N <= 64 && "integer width out of range");
247 
248   // This relies on two's complement wraparound when N == 64, so we convert to
249   // int64_t only at the very end to avoid UB.
250   if (N == 0)
251     return 0;
252   return (UINT64_C(1) << (N - 1)) - 1;
253 }
254 
255 /// Checks if an unsigned integer fits into the given (dynamic) bit width.
isUIntN(unsigned N,uint64_t x)256 inline constexpr bool isUIntN(unsigned N, uint64_t x) {
257   return N >= 64 || x <= maxUIntN(N);
258 }
259 
260 /// Checks if an signed integer fits into the given (dynamic) bit width.
isIntN(unsigned N,int64_t x)261 inline constexpr bool isIntN(unsigned N, int64_t x) {
262   return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
263 }
264 
265 /// Return true if the argument is a non-empty sequence of ones starting at the
266 /// least significant bit with the remainder zero (32 bit version).
267 /// Ex. isMask_32(0x0000FFFFU) == true.
isMask_32(uint32_t Value)268 constexpr bool isMask_32(uint32_t Value) {
269   return Value && ((Value + 1) & Value) == 0;
270 }
271 
272 /// Return true if the argument is a non-empty sequence of ones starting at the
273 /// least significant bit with the remainder zero (64 bit version).
isMask_64(uint64_t Value)274 constexpr bool isMask_64(uint64_t Value) {
275   return Value && ((Value + 1) & Value) == 0;
276 }
277 
278 /// Return true if the argument contains a non-empty sequence of ones with the
279 /// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
isShiftedMask_32(uint32_t Value)280 constexpr bool isShiftedMask_32(uint32_t Value) {
281   return Value && isMask_32((Value - 1) | Value);
282 }
283 
284 /// Return true if the argument contains a non-empty sequence of ones with the
285 /// remainder zero (64 bit version.)
isShiftedMask_64(uint64_t Value)286 constexpr bool isShiftedMask_64(uint64_t Value) {
287   return Value && isMask_64((Value - 1) | Value);
288 }
289 
290 /// Return true if the argument is a power of two > 0.
291 /// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
isPowerOf2_32(uint32_t Value)292 constexpr bool isPowerOf2_32(uint32_t Value) {
293   return llvm::has_single_bit(Value);
294 }
295 
296 /// Return true if the argument is a power of two > 0 (64 bit edition.)
isPowerOf2_64(uint64_t Value)297 constexpr bool isPowerOf2_64(uint64_t Value) {
298   return llvm::has_single_bit(Value);
299 }
300 
301 /// Return true if the argument contains a non-empty sequence of ones with the
302 /// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
303 /// If true, \p MaskIdx will specify the index of the lowest set bit and \p
304 /// MaskLen is updated to specify the length of the mask, else neither are
305 /// updated.
isShiftedMask_32(uint32_t Value,unsigned & MaskIdx,unsigned & MaskLen)306 inline bool isShiftedMask_32(uint32_t Value, unsigned &MaskIdx,
307                              unsigned &MaskLen) {
308   if (!isShiftedMask_32(Value))
309     return false;
310   MaskIdx = llvm::countr_zero(Value);
311   MaskLen = llvm::popcount(Value);
312   return true;
313 }
314 
315 /// Return true if the argument contains a non-empty sequence of ones with the
316 /// remainder zero (64 bit version.) If true, \p MaskIdx will specify the index
317 /// of the lowest set bit and \p MaskLen is updated to specify the length of the
318 /// mask, else neither are updated.
isShiftedMask_64(uint64_t Value,unsigned & MaskIdx,unsigned & MaskLen)319 inline bool isShiftedMask_64(uint64_t Value, unsigned &MaskIdx,
320                              unsigned &MaskLen) {
321   if (!isShiftedMask_64(Value))
322     return false;
323   MaskIdx = llvm::countr_zero(Value);
324   MaskLen = llvm::popcount(Value);
325   return true;
326 }
327 
328 /// Compile time Log2.
329 /// Valid only for positive powers of two.
CTLog2()330 template <size_t kValue> constexpr size_t CTLog2() {
331   static_assert(llvm::isPowerOf2_64(kValue), "Value is not a valid power of 2");
332   return 1 + CTLog2<kValue / 2>();
333 }
334 
335 template <> constexpr size_t CTLog2<1>() { return 0; }
336 
337 /// Return the floor log base 2 of the specified value, -1 if the value is zero.
338 /// (32 bit edition.)
339 /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
Log2_32(uint32_t Value)340 inline unsigned Log2_32(uint32_t Value) {
341   return 31 - llvm::countl_zero(Value);
342 }
343 
344 /// Return the floor log base 2 of the specified value, -1 if the value is zero.
345 /// (64 bit edition.)
Log2_64(uint64_t Value)346 inline unsigned Log2_64(uint64_t Value) {
347   return 63 - llvm::countl_zero(Value);
348 }
349 
350 /// Return the ceil log base 2 of the specified value, 32 if the value is zero.
351 /// (32 bit edition).
352 /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
Log2_32_Ceil(uint32_t Value)353 inline unsigned Log2_32_Ceil(uint32_t Value) {
354   return 32 - llvm::countl_zero(Value - 1);
355 }
356 
357 /// Return the ceil log base 2 of the specified value, 64 if the value is zero.
358 /// (64 bit edition.)
Log2_64_Ceil(uint64_t Value)359 inline unsigned Log2_64_Ceil(uint64_t Value) {
360   return 64 - llvm::countl_zero(Value - 1);
361 }
362 
363 /// A and B are either alignments or offsets. Return the minimum alignment that
364 /// may be assumed after adding the two together.
365 template <typename U, typename V, typename T = common_uint<U, V>>
MinAlign(U A,V B)366 constexpr T MinAlign(U A, V B) {
367   // The largest power of 2 that divides both A and B.
368   //
369   // Replace "-Value" by "1+~Value" in the following commented code to avoid
370   // MSVC warning C4146
371   //    return (A | B) & -(A | B);
372   return (A | B) & (1 + ~(A | B));
373 }
374 
375 /// Fallback when arguments aren't integral.
MinAlign(uint64_t A,uint64_t B)376 constexpr uint64_t MinAlign(uint64_t A, uint64_t B) {
377   return (A | B) & (1 + ~(A | B));
378 }
379 
380 /// Returns the next power of two (in 64-bits) that is strictly greater than A.
381 /// Returns zero on overflow.
NextPowerOf2(uint64_t A)382 constexpr uint64_t NextPowerOf2(uint64_t A) {
383   A |= (A >> 1);
384   A |= (A >> 2);
385   A |= (A >> 4);
386   A |= (A >> 8);
387   A |= (A >> 16);
388   A |= (A >> 32);
389   return A + 1;
390 }
391 
392 /// Returns the power of two which is greater than or equal to the given value.
393 /// Essentially, it is a ceil operation across the domain of powers of two.
PowerOf2Ceil(uint64_t A)394 inline uint64_t PowerOf2Ceil(uint64_t A) {
395   if (!A || A > UINT64_MAX / 2)
396     return 0;
397   return UINT64_C(1) << Log2_64_Ceil(A);
398 }
399 
400 /// Returns the integer ceil(Numerator / Denominator). Unsigned version.
401 /// Guaranteed to never overflow.
402 template <typename U, typename V, typename T = common_uint<U, V>>
divideCeil(U Numerator,V Denominator)403 constexpr T divideCeil(U Numerator, V Denominator) {
404   assert(Denominator && "Division by zero");
405   T Bias = (Numerator != 0);
406   return (Numerator - Bias) / Denominator + Bias;
407 }
408 
409 /// Fallback when arguments aren't integral.
divideCeil(uint64_t Numerator,uint64_t Denominator)410 constexpr uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
411   assert(Denominator && "Division by zero");
412   uint64_t Bias = (Numerator != 0);
413   return (Numerator - Bias) / Denominator + Bias;
414 }
415 
416 // Check whether divideCeilSigned or divideFloorSigned would overflow. This
417 // happens only when Numerator = INT_MIN and Denominator = -1.
418 template <typename U, typename V>
divideSignedWouldOverflow(U Numerator,V Denominator)419 constexpr bool divideSignedWouldOverflow(U Numerator, V Denominator) {
420   return Numerator == std::numeric_limits<U>::min() && Denominator == -1;
421 }
422 
423 /// Returns the integer ceil(Numerator / Denominator). Signed version.
424 /// Overflow is explicitly forbidden with an assert.
425 template <typename U, typename V, typename T = common_sint<U, V>>
divideCeilSigned(U Numerator,V Denominator)426 constexpr T divideCeilSigned(U Numerator, V Denominator) {
427   assert(Denominator && "Division by zero");
428   assert(!divideSignedWouldOverflow(Numerator, Denominator) &&
429          "Divide would overflow");
430   if (!Numerator)
431     return 0;
432   // C's integer division rounds towards 0.
433   T Bias = Denominator >= 0 ? 1 : -1;
434   bool SameSign = (Numerator >= 0) == (Denominator >= 0);
435   return SameSign ? (Numerator - Bias) / Denominator + 1
436                   : Numerator / Denominator;
437 }
438 
439 /// Returns the integer floor(Numerator / Denominator). Signed version.
440 /// Overflow is explicitly forbidden with an assert.
441 template <typename U, typename V, typename T = common_sint<U, V>>
divideFloorSigned(U Numerator,V Denominator)442 constexpr T divideFloorSigned(U Numerator, V Denominator) {
443   assert(Denominator && "Division by zero");
444   assert(!divideSignedWouldOverflow(Numerator, Denominator) &&
445          "Divide would overflow");
446   if (!Numerator)
447     return 0;
448   // C's integer division rounds towards 0.
449   T Bias = Denominator >= 0 ? -1 : 1;
450   bool SameSign = (Numerator >= 0) == (Denominator >= 0);
451   return SameSign ? Numerator / Denominator
452                   : (Numerator - Bias) / Denominator - 1;
453 }
454 
455 /// Returns the remainder of the Euclidean division of LHS by RHS. Result is
456 /// always non-negative.
457 template <typename U, typename V, typename T = common_sint<U, V>>
mod(U Numerator,V Denominator)458 constexpr T mod(U Numerator, V Denominator) {
459   assert(Denominator >= 1 && "Mod by non-positive number");
460   T Mod = Numerator % Denominator;
461   return Mod < 0 ? Mod + Denominator : Mod;
462 }
463 
464 /// Returns (Numerator / Denominator) rounded by round-half-up. Guaranteed to
465 /// never overflow.
466 template <typename U, typename V, typename T = common_uint<U, V>>
divideNearest(U Numerator,V Denominator)467 constexpr T divideNearest(U Numerator, V Denominator) {
468   assert(Denominator && "Division by zero");
469   T Mod = Numerator % Denominator;
470   return (Numerator / Denominator) +
471          (Mod > (static_cast<T>(Denominator) - 1) / 2);
472 }
473 
474 /// Returns the next integer (mod 2**nbits) that is greater than or equal to
475 /// \p Value and is a multiple of \p Align. \p Align must be non-zero.
476 ///
477 /// Examples:
478 /// \code
479 ///   alignTo(5, 8) = 8
480 ///   alignTo(17, 8) = 24
481 ///   alignTo(~0LL, 8) = 0
482 ///   alignTo(321, 255) = 510
483 /// \endcode
484 ///
485 /// Will overflow only if result is not representable in T.
486 template <typename U, typename V, typename T = common_uint<U, V>>
alignTo(U Value,V Align)487 constexpr T alignTo(U Value, V Align) {
488   assert(Align != 0u && "Align can't be 0.");
489   T CeilDiv = divideCeil(Value, Align);
490   return CeilDiv * Align;
491 }
492 
493 /// Fallback when arguments aren't integral.
alignTo(uint64_t Value,uint64_t Align)494 constexpr uint64_t alignTo(uint64_t Value, uint64_t Align) {
495   assert(Align != 0u && "Align can't be 0.");
496   uint64_t CeilDiv = divideCeil(Value, Align);
497   return CeilDiv * Align;
498 }
499 
500 /// Will overflow only if result is not representable in T.
501 template <typename U, typename V, typename T = common_uint<U, V>>
alignToPowerOf2(U Value,V Align)502 constexpr T alignToPowerOf2(U Value, V Align) {
503   assert(Align != 0 && (Align & (Align - 1)) == 0 &&
504          "Align must be a power of 2");
505   T NegAlign = static_cast<T>(0) - Align;
506   return (Value + (Align - 1)) & NegAlign;
507 }
508 
509 /// Fallback when arguments aren't integral.
alignToPowerOf2(uint64_t Value,uint64_t Align)510 constexpr uint64_t alignToPowerOf2(uint64_t Value, uint64_t Align) {
511   assert(Align != 0 && (Align & (Align - 1)) == 0 &&
512          "Align must be a power of 2");
513   uint64_t NegAlign = 0 - Align;
514   return (Value + (Align - 1)) & NegAlign;
515 }
516 
517 /// If non-zero \p Skew is specified, the return value will be a minimal integer
518 /// that is greater than or equal to \p Size and equal to \p A * N + \p Skew for
519 /// some integer N. If \p Skew is larger than \p A, its value is adjusted to '\p
520 /// Skew mod \p A'. \p Align must be non-zero.
521 ///
522 /// Examples:
523 /// \code
524 ///   alignTo(5, 8, 7) = 7
525 ///   alignTo(17, 8, 1) = 17
526 ///   alignTo(~0LL, 8, 3) = 3
527 ///   alignTo(321, 255, 42) = 552
528 /// \endcode
529 ///
530 /// May overflow.
531 template <typename U, typename V, typename W,
532           typename T = common_uint<common_uint<U, V>, W>>
alignTo(U Value,V Align,W Skew)533 constexpr T alignTo(U Value, V Align, W Skew) {
534   assert(Align != 0u && "Align can't be 0.");
535   Skew %= Align;
536   return alignTo(Value - Skew, Align) + Skew;
537 }
538 
539 /// Returns the next integer (mod 2**nbits) that is greater than or equal to
540 /// \p Value and is a multiple of \c Align. \c Align must be non-zero.
541 ///
542 /// Will overflow only if result is not representable in T.
543 template <auto Align, typename V, typename T = common_uint<decltype(Align), V>>
alignTo(V Value)544 constexpr T alignTo(V Value) {
545   static_assert(Align != 0u, "Align must be non-zero");
546   T CeilDiv = divideCeil(Value, Align);
547   return CeilDiv * Align;
548 }
549 
550 /// Returns the largest unsigned integer less than or equal to \p Value and is
551 /// \p Skew mod \p Align. \p Align must be non-zero. Guaranteed to never
552 /// overflow.
553 template <typename U, typename V, typename W = uint8_t,
554           typename T = common_uint<common_uint<U, V>, W>>
555 constexpr T alignDown(U Value, V Align, W Skew = 0) {
556   assert(Align != 0u && "Align can't be 0.");
557   Skew %= Align;
558   return (Value - Skew) / Align * Align + Skew;
559 }
560 
561 /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
562 /// Requires B <= 32.
SignExtend32(uint32_t X)563 template <unsigned B> constexpr int32_t SignExtend32(uint32_t X) {
564   static_assert(B <= 32, "Bit width out of range.");
565   if constexpr (B == 0)
566     return 0;
567   return int32_t(X << (32 - B)) >> (32 - B);
568 }
569 
570 /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
571 /// Requires B <= 32.
SignExtend32(uint32_t X,unsigned B)572 inline int32_t SignExtend32(uint32_t X, unsigned B) {
573   assert(B <= 32 && "Bit width out of range.");
574   if (B == 0)
575     return 0;
576   return int32_t(X << (32 - B)) >> (32 - B);
577 }
578 
579 /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
580 /// Requires B <= 64.
SignExtend64(uint64_t x)581 template <unsigned B> constexpr int64_t SignExtend64(uint64_t x) {
582   static_assert(B <= 64, "Bit width out of range.");
583   if constexpr (B == 0)
584     return 0;
585   return int64_t(x << (64 - B)) >> (64 - B);
586 }
587 
588 /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
589 /// Requires B <= 64.
SignExtend64(uint64_t X,unsigned B)590 inline int64_t SignExtend64(uint64_t X, unsigned B) {
591   assert(B <= 64 && "Bit width out of range.");
592   if (B == 0)
593     return 0;
594   return int64_t(X << (64 - B)) >> (64 - B);
595 }
596 
597 /// Return the absolute value of a signed integer, converted to the
598 /// corresponding unsigned integer type. Avoids undefined behavior in std::abs
599 /// when you pass it INT_MIN or similar.
600 template <typename T, typename U = std::make_unsigned_t<T>>
AbsoluteValue(T X)601 constexpr U AbsoluteValue(T X) {
602   // If X is negative, cast it to the unsigned type _before_ negating it.
603   return X < 0 ? -static_cast<U>(X) : X;
604 }
605 
606 /// Subtract two unsigned integers, X and Y, of type T and return the absolute
607 /// value of the result.
608 template <typename U, typename V, typename T = common_uint<U, V>>
AbsoluteDifference(U X,V Y)609 constexpr T AbsoluteDifference(U X, V Y) {
610   return X > Y ? (X - Y) : (Y - X);
611 }
612 
613 /// Add two unsigned integers, X and Y, of type T.  Clamp the result to the
614 /// maximum representable value of T on overflow.  ResultOverflowed indicates if
615 /// the result is larger than the maximum representable value of type T.
616 template <typename T>
617 std::enable_if_t<std::is_unsigned_v<T>, T>
618 SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
619   bool Dummy;
620   bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
621   // Hacker's Delight, p. 29
622   T Z = X + Y;
623   Overflowed = (Z < X || Z < Y);
624   if (Overflowed)
625     return std::numeric_limits<T>::max();
626   else
627     return Z;
628 }
629 
630 /// Add multiple unsigned integers of type T.  Clamp the result to the
631 /// maximum representable value of T on overflow.
632 template <class T, class... Ts>
SaturatingAdd(T X,T Y,T Z,Ts...Args)633 std::enable_if_t<std::is_unsigned_v<T>, T> SaturatingAdd(T X, T Y, T Z,
634                                                          Ts... Args) {
635   bool Overflowed = false;
636   T XY = SaturatingAdd(X, Y, &Overflowed);
637   if (Overflowed)
638     return SaturatingAdd(std::numeric_limits<T>::max(), T(1), Args...);
639   return SaturatingAdd(XY, Z, Args...);
640 }
641 
642 /// Multiply two unsigned integers, X and Y, of type T.  Clamp the result to the
643 /// maximum representable value of T on overflow.  ResultOverflowed indicates if
644 /// the result is larger than the maximum representable value of type T.
645 template <typename T>
646 std::enable_if_t<std::is_unsigned_v<T>, T>
647 SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
648   bool Dummy;
649   bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
650 
651   // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
652   // because it fails for uint16_t (where multiplication can have undefined
653   // behavior due to promotion to int), and requires a division in addition
654   // to the multiplication.
655 
656   Overflowed = false;
657 
658   // Log2(Z) would be either Log2Z or Log2Z + 1.
659   // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
660   // will necessarily be less than Log2Max as desired.
661   int Log2Z = Log2_64(X) + Log2_64(Y);
662   const T Max = std::numeric_limits<T>::max();
663   int Log2Max = Log2_64(Max);
664   if (Log2Z < Log2Max) {
665     return X * Y;
666   }
667   if (Log2Z > Log2Max) {
668     Overflowed = true;
669     return Max;
670   }
671 
672   // We're going to use the top bit, and maybe overflow one
673   // bit past it. Multiply all but the bottom bit then add
674   // that on at the end.
675   T Z = (X >> 1) * Y;
676   if (Z & ~(Max >> 1)) {
677     Overflowed = true;
678     return Max;
679   }
680   Z <<= 1;
681   if (X & 1)
682     return SaturatingAdd(Z, Y, ResultOverflowed);
683 
684   return Z;
685 }
686 
687 /// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
688 /// the product. Clamp the result to the maximum representable value of T on
689 /// overflow. ResultOverflowed indicates if the result is larger than the
690 /// maximum representable value of type T.
691 template <typename T>
692 std::enable_if_t<std::is_unsigned_v<T>, T>
693 SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
694   bool Dummy;
695   bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
696 
697   T Product = SaturatingMultiply(X, Y, &Overflowed);
698   if (Overflowed)
699     return Product;
700 
701   return SaturatingAdd(A, Product, &Overflowed);
702 }
703 
704 /// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
705 LLVM_ABI extern const float huge_valf;
706 
707 /// Add two signed integers, computing the two's complement truncated result,
708 /// returning true if overflow occurred.
709 template <typename T>
AddOverflow(T X,T Y,T & Result)710 std::enable_if_t<std::is_signed_v<T>, T> AddOverflow(T X, T Y, T &Result) {
711 #if __has_builtin(__builtin_add_overflow)
712   return __builtin_add_overflow(X, Y, &Result);
713 #else
714   // Perform the unsigned addition.
715   using U = std::make_unsigned_t<T>;
716   const U UX = static_cast<U>(X);
717   const U UY = static_cast<U>(Y);
718   const U UResult = UX + UY;
719 
720   // Convert to signed.
721   Result = static_cast<T>(UResult);
722 
723   // Adding two positive numbers should result in a positive number.
724   if (X > 0 && Y > 0)
725     return Result <= 0;
726   // Adding two negatives should result in a negative number.
727   if (X < 0 && Y < 0)
728     return Result >= 0;
729   return false;
730 #endif
731 }
732 
733 /// Subtract two signed integers, computing the two's complement truncated
734 /// result, returning true if an overflow occurred.
735 template <typename T>
SubOverflow(T X,T Y,T & Result)736 std::enable_if_t<std::is_signed_v<T>, T> SubOverflow(T X, T Y, T &Result) {
737 #if __has_builtin(__builtin_sub_overflow)
738   return __builtin_sub_overflow(X, Y, &Result);
739 #else
740   // Perform the unsigned addition.
741   using U = std::make_unsigned_t<T>;
742   const U UX = static_cast<U>(X);
743   const U UY = static_cast<U>(Y);
744   const U UResult = UX - UY;
745 
746   // Convert to signed.
747   Result = static_cast<T>(UResult);
748 
749   // Subtracting a positive number from a negative results in a negative number.
750   if (X <= 0 && Y > 0)
751     return Result >= 0;
752   // Subtracting a negative number from a positive results in a positive number.
753   if (X >= 0 && Y < 0)
754     return Result <= 0;
755   return false;
756 #endif
757 }
758 
759 /// Multiply two signed integers, computing the two's complement truncated
760 /// result, returning true if an overflow occurred.
761 template <typename T>
MulOverflow(T X,T Y,T & Result)762 std::enable_if_t<std::is_signed_v<T>, T> MulOverflow(T X, T Y, T &Result) {
763 #if __has_builtin(__builtin_mul_overflow)
764   return __builtin_mul_overflow(X, Y, &Result);
765 #else
766   // Perform the unsigned multiplication on absolute values.
767   using U = std::make_unsigned_t<T>;
768   const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
769   const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
770   const U UResult = UX * UY;
771 
772   // Convert to signed.
773   const bool IsNegative = (X < 0) ^ (Y < 0);
774   Result = IsNegative ? (0 - UResult) : UResult;
775 
776   // If any of the args was 0, result is 0 and no overflow occurs.
777   if (UX == 0 || UY == 0)
778     return false;
779 
780   // UX and UY are in [1, 2^n], where n is the number of digits.
781   // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
782   // positive) divided by an argument compares to the other.
783   if (IsNegative)
784     return UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY;
785   else
786     return UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
787 #endif
788 }
789 
790 /// Type to force float point values onto the stack, so that x86 doesn't add
791 /// hidden precision, avoiding rounding differences on various platforms.
792 #if defined(__i386__) || defined(_M_IX86)
793 using stack_float_t = volatile float;
794 #else
795 using stack_float_t = float;
796 #endif
797 
798 } // namespace llvm
799 
800 #endif
801