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