LLVM 24.0.0git
MathExtras.h
Go to the documentation of this file.
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
17#include "llvm/ADT/bit.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>
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>>
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>>
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(in, &Val, sizeof(Val));
140 for (unsigned i = 0; i < sizeof(Val); ++i)
141 out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
142 std::memcpy(&Val, out, 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.
152 return static_cast<uint32_t>(Value >> 32);
153}
154
155/// Return the low 32 bits of a 64 bit 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.
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.
269 return Value && isMask_32((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.)
275 return Value && isMask_64((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) {
282}
283
284/// Return true if the argument is a power of two > 0 (64 bit edition.)
285constexpr bool isPowerOf2_64(uint64_t 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) {
297 return false;
298 MaskIdx = llvm::countr_zero(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) {
310 return false;
311 MaskIdx = llvm::countr_zero(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(kValue), "Value is not a valid power of 2");
320 return llvm::countr_zero_constexpr(kValue);
321}
322
323/// Return the floor log base 2 of the specified value, -1 if the value is zero.
324/// (32 bit edition.)
325/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
326inline unsigned Log2_32(uint32_t Value) {
327 return 31 - llvm::countl_zero(Value);
328}
329
330/// Return the floor log base 2 of the specified value, -1 if the value is zero.
331/// (64 bit edition.)
332inline unsigned Log2_64(uint64_t Value) {
333 return 63 - llvm::countl_zero(Value);
334}
335
336/// Return the ceil log base 2 of the specified value, 32 if the value is zero.
337/// (32 bit edition).
338/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
339inline unsigned Log2_32_Ceil(uint32_t Value) {
340 return 32 - llvm::countl_zero(Value - 1);
341}
342
343/// Return the ceil log base 2 of the specified value, 64 if the value is zero.
344/// (64 bit edition.)
345inline unsigned Log2_64_Ceil(uint64_t Value) {
346 return 64 - llvm::countl_zero(Value - 1);
347}
348
349/// A and B are either alignments or offsets. Return the minimum alignment that
350/// may be assumed after adding the two together.
351template <typename U, typename V, typename T = common_uint<U, V>>
352constexpr T MinAlign(U A, V B) {
353 // The largest power of 2 that divides both A and B.
354 //
355 // Replace "-Value" by "1+~Value" in the following commented code to avoid
356 // MSVC warning C4146
357 // return (A | B) & -(A | B);
358 return (A | B) & (1 + ~(A | B));
359}
360
361/// Fallback when arguments aren't integral.
363 return (A | B) & (1 + ~(A | B));
364}
365
366/// Returns the next power of two (in 64-bits) that is strictly greater than A.
367/// Returns zero on overflow.
369 A |= (A >> 1);
370 A |= (A >> 2);
371 A |= (A >> 4);
372 A |= (A >> 8);
373 A |= (A >> 16);
374 A |= (A >> 32);
375 return A + 1;
376}
377
378/// Returns the power of two which is greater than or equal to the given value.
379/// Essentially, it is a ceil operation across the domain of powers of two.
381 if (!A || A > UINT64_MAX / 2)
382 return 0;
383 return UINT64_C(1) << Log2_64_Ceil(A);
384}
385
386/// Returns the integer ceil(Numerator / Denominator). Unsigned version.
387/// Guaranteed to never overflow.
388template <typename U, typename V, typename T = common_uint<U, V>>
389constexpr T divideCeil(U Numerator, V Denominator) {
390 assert(Denominator && "Division by zero");
391 T Bias = (Numerator != 0);
392 return (Numerator - Bias) / Denominator + Bias;
393}
394
395/// Fallback when arguments aren't integral.
396constexpr uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
397 assert(Denominator && "Division by zero");
398 uint64_t Bias = (Numerator != 0);
399 return (Numerator - Bias) / Denominator + Bias;
400}
401
402// Check whether divideCeilSigned or divideFloorSigned would overflow. This
403// happens only when Numerator = INT_MIN and Denominator = -1.
404template <typename U, typename V>
405constexpr bool divideSignedWouldOverflow(U Numerator, V Denominator) {
406 return Numerator == std::numeric_limits<U>::min() && Denominator == -1;
407}
408
409/// Returns the integer ceil(Numerator / Denominator). Signed version.
410/// Overflow is explicitly forbidden with an assert.
411template <typename U, typename V, typename T = common_sint<U, V>>
412constexpr T divideCeilSigned(U Numerator, V Denominator) {
413 assert(Denominator && "Division by zero");
414 assert(!divideSignedWouldOverflow(Numerator, Denominator) &&
415 "Divide would overflow");
416 if (!Numerator)
417 return 0;
418 // C's integer division rounds towards 0.
419 T Bias = Denominator >= 0 ? 1 : -1;
420 bool SameSign = (Numerator >= 0) == (Denominator >= 0);
421 return SameSign ? (Numerator - Bias) / Denominator + 1
422 : Numerator / Denominator;
423}
424
425/// Returns the integer floor(Numerator / Denominator). Signed version.
426/// Overflow is explicitly forbidden with an assert.
427template <typename U, typename V, typename T = common_sint<U, V>>
428constexpr T divideFloorSigned(U Numerator, V Denominator) {
429 assert(Denominator && "Division by zero");
430 assert(!divideSignedWouldOverflow(Numerator, Denominator) &&
431 "Divide would overflow");
432 if (!Numerator)
433 return 0;
434 // C's integer division rounds towards 0.
435 T Bias = Denominator >= 0 ? -1 : 1;
436 bool SameSign = (Numerator >= 0) == (Denominator >= 0);
437 return SameSign ? Numerator / Denominator
438 : (Numerator - Bias) / Denominator - 1;
439}
440
441/// Returns the remainder of the Euclidean division of LHS by RHS. Result is
442/// always non-negative.
443template <typename U, typename V, typename T = common_sint<U, V>>
444constexpr T mod(U Numerator, V Denominator) {
445 assert(Denominator >= 1 && "Mod by non-positive number");
446 T Mod = Numerator % Denominator;
447 return Mod < 0 ? Mod + Denominator : Mod;
448}
449
450/// Returns (Numerator / Denominator) rounded by round-half-up. Guaranteed to
451/// never overflow.
452template <typename U, typename V, typename T = common_uint<U, V>>
453constexpr T divideNearest(U Numerator, V Denominator) {
454 assert(Denominator && "Division by zero");
455 T Mod = Numerator % Denominator;
456 return (Numerator / Denominator) +
457 (Mod > (static_cast<T>(Denominator) - 1) / 2);
458}
459
460/// Returns the next integer (mod 2**nbits) that is greater than or equal to
461/// \p Value and is a multiple of \p Align. \p Align must be non-zero.
462///
463/// Examples:
464/// \code
465/// alignTo(5, 8) = 8
466/// alignTo(17, 8) = 24
467/// alignTo(~0LL, 8) = 0
468/// alignTo(321, 255) = 510
469/// \endcode
470///
471/// Will overflow only if result is not representable in T.
472template <typename U, typename V, typename T = common_uint<U, V>>
473constexpr T alignTo(U Value, V Align) {
474 assert(Align != 0u && "Align can't be 0.");
475 T CeilDiv = divideCeil(Value, Align);
476 return CeilDiv * Align;
477}
478
479/// Fallback when arguments aren't integral.
481 assert(Align != 0u && "Align can't be 0.");
482 uint64_t CeilDiv = divideCeil(Value, Align);
483 return CeilDiv * Align;
484}
485
486/// Will overflow only if result is not representable in T.
487template <typename U, typename V, typename T = common_uint<U, V>>
488constexpr T alignToPowerOf2(U Value, V Align) {
489 assert(Align != 0 && (Align & (Align - 1)) == 0 &&
490 "Align must be a power of 2");
491 T NegAlign = static_cast<T>(0) - Align;
492 return (Value + (Align - 1)) & NegAlign;
493}
494
495/// Fallback when arguments aren't integral.
497 assert(Align != 0 && (Align & (Align - 1)) == 0 &&
498 "Align must be a power of 2");
499 uint64_t NegAlign = 0 - Align;
500 return (Value + (Align - 1)) & NegAlign;
501}
502
503/// If non-zero \p Skew is specified, the return value will be a minimal integer
504/// that is greater than or equal to \p Size and equal to \p A * N + \p Skew for
505/// some integer N. If \p Skew is larger than \p A, its value is adjusted to '\p
506/// Skew mod \p A'. \p Align must be non-zero.
507///
508/// Examples:
509/// \code
510/// alignTo(5, 8, 7) = 7
511/// alignTo(17, 8, 1) = 17
512/// alignTo(~0LL, 8, 3) = 3
513/// alignTo(321, 255, 42) = 552
514/// \endcode
515///
516/// May overflow.
517template <typename U, typename V, typename W,
518 typename T = common_uint<common_uint<U, V>, W>>
519constexpr T alignTo(U Value, V Align, W Skew) {
520 assert(Align != 0u && "Align can't be 0.");
521 Skew %= Align;
522 return alignTo(Value - Skew, Align) + Skew;
523}
524
525/// Returns the next integer (mod 2**nbits) that is greater than or equal to
526/// \p Value and is a multiple of \c Align. \c Align must be non-zero.
527///
528/// Will overflow only if result is not representable in T.
529template <auto Align, typename V, typename T = common_uint<decltype(Align), V>>
530constexpr T alignTo(V Value) {
531 static_assert(Align != 0u, "Align must be non-zero");
532 T CeilDiv = divideCeil(Value, Align);
533 return CeilDiv * Align;
534}
535
536/// Returns the largest unsigned integer less than or equal to \p Value and is
537/// \p Skew mod \p Align. \p Align must be non-zero. Guaranteed to never
538/// overflow.
539template <typename U, typename V, typename W = uint8_t,
540 typename T = common_uint<common_uint<U, V>, W>>
541constexpr T alignDown(U Value, V Align, W Skew = 0) {
542 assert(Align != 0u && "Align can't be 0.");
543 Skew %= Align;
544 return (Value - Skew) / Align * Align + Skew;
545}
546
547/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
548/// Requires B <= 32.
549template <unsigned B> constexpr int32_t SignExtend32(uint32_t X) {
550 static_assert(B <= 32, "Bit width out of range.");
551 if constexpr (B == 0)
552 return 0;
553 return int32_t(X << (32 - B)) >> (32 - B);
554}
555
556/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
557/// Requires B <= 32.
558inline int32_t SignExtend32(uint32_t X, unsigned B) {
559 assert(B <= 32 && "Bit width out of range.");
560 if (B == 0)
561 return 0;
562 return int32_t(X << (32 - B)) >> (32 - B);
563}
564
565/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
566/// Requires B <= 64.
567template <unsigned B> constexpr int64_t SignExtend64(uint64_t x) {
568 static_assert(B <= 64, "Bit width out of range.");
569 if constexpr (B == 0)
570 return 0;
571 return int64_t(x << (64 - B)) >> (64 - B);
572}
573
574/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
575/// Requires B <= 64.
576inline int64_t SignExtend64(uint64_t X, unsigned B) {
577 assert(B <= 64 && "Bit width out of range.");
578 if (B == 0)
579 return 0;
580 return int64_t(X << (64 - B)) >> (64 - B);
581}
582
583/// Return the absolute value of a signed integer, converted to the
584/// corresponding unsigned integer type. Avoids undefined behavior in std::abs
585/// when you pass it INT_MIN or similar.
586template <typename T, typename U = std::make_unsigned_t<T>>
587constexpr U AbsoluteValue(T X) {
588 // If X is negative, cast it to the unsigned type _before_ negating it.
589 return X < 0 ? -static_cast<U>(X) : X;
590}
591
592/// Subtract two unsigned integers, X and Y, of type T and return the absolute
593/// value of the result.
594template <typename U, typename V, typename T = common_uint<U, V>>
595constexpr T AbsoluteDifference(U X, V Y) {
596 return X > Y ? (X - Y) : (Y - X);
597}
598
599/// Add two unsigned integers, X and Y, of type T. Clamp the result to the
600/// maximum representable value of T on overflow. ResultOverflowed indicates if
601/// the result is larger than the maximum representable value of type T.
602template <typename T>
603std::enable_if_t<std::is_unsigned_v<T>, T>
604SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
605 bool Dummy;
606 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
607 // Hacker's Delight, p. 29
608 T Z = X + Y;
609 Overflowed = (Z < X || Z < Y);
610 if (Overflowed)
611 return std::numeric_limits<T>::max();
612 else
613 return Z;
614}
615
616/// Add multiple unsigned integers of type T. Clamp the result to the
617/// maximum representable value of T on overflow.
618template <class T, class... Ts>
619std::enable_if_t<std::is_unsigned_v<T>, T> SaturatingAdd(T X, T Y, T Z,
620 Ts... Args) {
621 bool Overflowed = false;
622 T XY = SaturatingAdd(X, Y, &Overflowed);
623 if (Overflowed)
624 return SaturatingAdd(std::numeric_limits<T>::max(), T(1), Args...);
625 return SaturatingAdd(XY, Z, Args...);
626}
627
628/// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the
629/// maximum representable value of T on overflow. ResultOverflowed indicates if
630/// the result is larger than the maximum representable value of type T.
631template <typename T>
632std::enable_if_t<std::is_unsigned_v<T>, T>
633SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
634 bool Dummy;
635 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
636
637 // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
638 // because it fails for uint16_t (where multiplication can have undefined
639 // behavior due to promotion to int), and requires a division in addition
640 // to the multiplication.
641
642 Overflowed = false;
643
644 // Log2(Z) would be either Log2Z or Log2Z + 1.
645 // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
646 // will necessarily be less than Log2Max as desired.
647 int Log2Z = Log2_64(X) + Log2_64(Y);
648 const T Max = std::numeric_limits<T>::max();
649 int Log2Max = Log2_64(Max);
650 if (Log2Z < Log2Max) {
651 return X * Y;
652 }
653 if (Log2Z > Log2Max) {
654 Overflowed = true;
655 return Max;
656 }
657
658 // We're going to use the top bit, and maybe overflow one
659 // bit past it. Multiply all but the bottom bit then add
660 // that on at the end.
661 T Z = (X >> 1) * Y;
662 if (Z & ~(Max >> 1)) {
663 Overflowed = true;
664 return Max;
665 }
666 Z <<= 1;
667 if (X & 1)
668 return SaturatingAdd(Z, Y, ResultOverflowed);
669
670 return Z;
671}
672
673/// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
674/// the product. Clamp the result to the maximum representable value of T on
675/// overflow. ResultOverflowed indicates if the result is larger than the
676/// maximum representable value of type T.
677template <typename T>
678std::enable_if_t<std::is_unsigned_v<T>, T>
679SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
680 bool Dummy;
681 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
682
683 T Product = SaturatingMultiply(X, Y, &Overflowed);
684 if (Overflowed)
685 return Product;
686
687 return SaturatingAdd(A, Product, &Overflowed);
688}
689
690/// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
691LLVM_ABI extern const float huge_valf;
692
693/// Add two signed integers, computing the two's complement truncated result,
694/// returning a pair {result, overflow}, where "overflow" is a boolean value
695/// indicating whether an overflow occurred.
696template <typename T>
697constexpr std::enable_if_t<std::is_signed_v<T>, std::pair<T, bool>>
699 // Perform the unsigned addition.
700 using U = std::make_unsigned_t<T>;
701 const U UX = static_cast<U>(X);
702 const U UY = static_cast<U>(Y);
703 const U UResult = UX + UY;
704
705 // Convert to signed.
706 auto Result = static_cast<T>(UResult);
707
708 // Adding two positive numbers should result in a positive number.
709 if (X > 0 && Y > 0)
710 return {Result, Result <= 0};
711 // Adding two negatives should result in a negative number.
712 if (X < 0 && Y < 0)
713 return {Result, Result >= 0};
714 return {Result, false};
715}
716
717/// Add two signed integers, computing the two's complement truncated result,
718/// returning true if overflow occurred.
719template <typename T>
720std::enable_if_t<std::is_signed_v<T>, T> AddOverflow(T X, T Y, T &Result) {
721#if __has_builtin(__builtin_add_overflow)
722 return __builtin_add_overflow(X, Y, &Result);
723#else
724 auto [Res, Ovf] = AddOverflow(X, Y);
725 Result = Res;
726 return Ovf;
727#endif
728}
729
730/// Subtract two signed integers, computing the two's complement truncated
731/// result, returning a pair {result, overflow}, where "overflow" is a
732/// boolean value indicating whether an overflow occurred.
733template <typename T>
734constexpr std::enable_if_t<std::is_signed_v<T>, std::pair<T, bool>>
736 // Perform the unsigned addition.
737 using U = std::make_unsigned_t<T>;
738 const U UX = static_cast<U>(X);
739 const U UY = static_cast<U>(Y);
740 const U UResult = UX - UY;
741
742 // Convert to signed.
743 auto Result = static_cast<T>(UResult);
744
745 // Subtracting a positive number from a negative results in a negative number.
746 if (X <= 0 && Y > 0)
747 return {Result, Result >= 0};
748 // Subtracting a negative number from a positive results in a positive number.
749 if (X >= 0 && Y < 0)
750 return {Result, Result <= 0};
751 return {Result, false};
752}
753
754/// Subtract two signed integers, computing the two's complement truncated
755/// result, returning true if an overflow occurred.
756template <typename T>
757std::enable_if_t<std::is_signed_v<T>, T> SubOverflow(T X, T Y, T &Result) {
758#if __has_builtin(__builtin_sub_overflow)
759 return __builtin_sub_overflow(X, Y, &Result);
760#else
761 auto [Res, Ovf] = SubOverflow(X, Y);
762 Result = Res;
763 return Ovf;
764#endif
765}
766
767/// Multiply two signed integers, computing the two's complement truncated
768/// result, returning a pair {result, overflow}, where "overflow" is a
769/// boolean value indicating whether an overflow occurred.
770template <typename T>
771constexpr std::enable_if_t<std::is_signed_v<T>, std::pair<T, bool>>
773 // Perform the unsigned multiplication on absolute values.
774 using U = std::make_unsigned_t<T>;
775 const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
776 const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
777 const U UResult = UX * UY;
778
779 // Convert to signed.
780 const bool IsNegative = (X < 0) ^ (Y < 0);
781 auto Result = IsNegative ? (0 - UResult) : UResult;
782
783 // If any of the args was 0, result is 0 and no overflow occurs.
784 if (UX == 0 || UY == 0)
785 return {Result, false};
786
787 // UX and UY are in [1, 2^n], where n is the number of digits.
788 // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
789 // positive) divided by an argument compares to the other.
790 bool Overflow =
791 IsNegative
792 ? UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY
793 : UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
794
795 return {Result, Overflow};
796}
797
798/// Multiply two signed integers, computing the two's complement truncated
799/// result, returning true if an overflow occurred.
800template <typename T>
801std::enable_if_t<std::is_signed_v<T>, T> MulOverflow(T X, T Y, T &Result) {
802#if __has_builtin(__builtin_mul_overflow)
803 return __builtin_mul_overflow(X, Y, &Result);
804#else
805 auto [Res, Ovf] = MulOverflow(X, Y);
806 Result = Res;
807 return Ovf;
808#endif
809}
810
811/// Type to force float point values onto the stack, so that x86 doesn't add
812/// hidden precision, avoiding rounding differences on various platforms.
813#if defined(__i386__) || defined(_M_IX86)
814using stack_float_t = volatile float;
815#else
816using stack_float_t = float;
817#endif
818
819/// Returns the number of digits in the given integer.
821
822} // namespace llvm
823
824#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
unsigned uint64_t
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define LLVM_ABI
Definition Compiler.h:215
#define R6(n)
#define T
uint64_t High
This file contains library features backported from future STL versions.
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
This file implements the C++20 <bit> header.
LLVM Value Representation.
Definition Value.h:75
#define UINT64_MAX
Definition DataTypes.h:77
Mathematical constants.
constexpr T log10e_v
constexpr float inv_sqrtpif
Definition MathExtras.h:56
constexpr T e_v
constexpr T log2e_v
constexpr double sqrtpi
Definition MathExtras.h:66
constexpr float pif
Definition MathExtras.h:54
constexpr float sqrtpif
Definition MathExtras.h:67
constexpr float log10ef
Definition MathExtras.h:53
constexpr T egamma_v
constexpr float ln10f
Definition MathExtras.h:51
constexpr T sqrt3_v
constexpr T sqrt2_v
constexpr float phif
Definition MathExtras.h:61
constexpr T inv_sqrt3_v
constexpr const char * pis
Definition MathExtras.h:71
constexpr float sqrt3f
Definition MathExtras.h:59
constexpr T inv_sqrtpi_v
constexpr float log2ef
Definition MathExtras.h:52
constexpr T ln10_v
constexpr float sqrt2f
Definition MathExtras.h:57
constexpr const char * inv_pis
Definition MathExtras.h:72
constexpr T pi_v
constexpr float inv_pif
Definition MathExtras.h:55
constexpr T sqrtpi_v
Definition MathExtras.h:65
constexpr T phi_v
constexpr float inv_sqrt2f
Definition MathExtras.h:58
constexpr T ln2_v
constexpr float egammaf
Definition MathExtras.h:49
constexpr T inv_pi_v
constexpr T inv_sqrt2_v
constexpr float ln2f
Definition MathExtras.h:50
constexpr float ef
Definition MathExtras.h:48
constexpr float inv_sqrt3f
Definition MathExtras.h:60
This is an optimization pass for GlobalISel generic memory operations.
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
Definition Threading.h:280
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:339
constexpr bool divideSignedWouldOverflow(U Numerator, V Denominator)
Definition MathExtras.h:405
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt mod(const DynamicAPInt &LHS, const DynamicAPInt &RHS)
is always non-negative.
constexpr uint64_t maxUIntN(uint64_t N)
Gets the maximum value for a N-bit unsigned integer.
Definition MathExtras.h:208
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:166
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:345
LLVM_ABI int NumDigitsBase10(uint64_t X)
Returns the number of digits in the given integer.
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:256
constexpr T divideFloorSigned(U Numerator, V Denominator)
Returns the integer floor(Numerator / Denominator).
Definition MathExtras.h:428
constexpr int64_t minIntN(int64_t N)
Gets the minimum value for a N-bit signed integer.
Definition MathExtras.h:224
constexpr size_t ConstantLog2()
Compile time Log2.
Definition MathExtras.h:318
constexpr 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:89
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
constexpr T alignDown(U Value, V Align, W Skew=0)
Returns the largest unsigned integer less than or equal to Value and is Skew mod Align.
Definition MathExtras.h:541
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > AddOverflow(T X, T Y)
Add two signed integers, computing the two's complement truncated result, returning a pair {result,...
Definition MathExtras.h:698
constexpr bool isPowerOf2_64(uint64_t Value)
Return true if the argument is a power of two > 0 (64 bit edition.)
Definition MathExtras.h:285
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:268
constexpr int popcount(T Value) noexcept
Count the number of set bits in a value.
Definition bit.h:156
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:332
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition MathExtras.h:380
int countr_zero(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:204
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:274
constexpr T MinAlign(U A, V B)
A and B are either alignments or offsets.
Definition MathExtras.h:352
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
Definition MathExtras.h:453
constexpr bool has_single_bit(T Value) noexcept
Definition bit.h:149
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > SubOverflow(T X, T Y)
Subtract two signed integers, computing the two's complement truncated result, returning a pair {resu...
Definition MathExtras.h:735
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:326
int countl_zero(T Val)
Count number of 0's from the most significant bit to the least stopping at the first 1.
Definition bit.h:263
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
constexpr uint32_t Hi_32(uint64_t Value)
Return the high 32 bits of a 64 bit value.
Definition MathExtras.h:151
constexpr T alignToPowerOf2(U Value, V Align)
Will overflow only if result is not representable in T.
Definition MathExtras.h:488
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:144
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:262
std::enable_if_t< std::is_unsigned_v< T >, T > 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:679
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition MathExtras.h:190
std::common_type_t< std::make_unsigned_t< T >, std::make_unsigned_t< U > > common_uint
Definition MathExtras.h:39
constexpr T divideCeilSigned(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:412
constexpr uint32_t Lo_32(uint64_t Value)
Return the low 32 bits of a 64 bit value.
Definition MathExtras.h:156
constexpr 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:101
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
LLVM_ABI const float huge_valf
Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingMultiply(T X, T Y, bool *ResultOverflowed=nullptr)
Multiply two unsigned integers, X and Y, of type T.
Definition MathExtras.h:633
constexpr 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:95
std::common_type_t< std::make_signed_t< T >, std::make_signed_t< U > > common_sint
Definition MathExtras.h:42
constexpr T AbsoluteDifference(U X, V Y)
Subtract two unsigned integers, X and Y, of type T and return the absolute value of the result.
Definition MathExtras.h:595
constexpr U AbsoluteValue(T X)
Return the absolute value of a signed integer, converted to the corresponding unsigned integer type.
Definition MathExtras.h:587
constexpr bool isShiftedInt(int64_t x)
Checks if a signed integer is an N bit number shifted left by S.
Definition MathExtras.h:183
constexpr int64_t maxIntN(int64_t N)
Gets the maximum value for a N-bit signed integer.
Definition MathExtras.h:233
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:549
constexpr int countr_zero_constexpr(T Val)
Count number of 0's from the least significant bit to the most stopping at the first 1.
Definition bit.h:190
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
constexpr T reverseBits(T Val)
Reverse the bits in Val.
Definition MathExtras.h:119
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:567
constexpr std::enable_if_t< std::is_signed_v< T >, std::pair< T, bool > > MulOverflow(T X, T Y)
Multiply two signed integers, computing the two's complement truncated result, returning a pair {resu...
Definition MathExtras.h:772
float stack_float_t
Type to force float point values onto the stack, so that x86 doesn't add hidden precision,...
Definition MathExtras.h:816
std::enable_if_t< std::is_integral_v< T > &&std::is_integral_v< U > > enableif_int
Some template parameter helpers to optimize for bitwidth, for functions that take multiple arguments.
Definition MathExtras.h:34
static const unsigned char BitReverseTable256[256]
Macro compressed bit reversal table for 256 bits.
Definition MathExtras.h:108
constexpr 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:78
std::enable_if_t< std::is_unsigned_v< T >, T > SaturatingAdd(T X, T Y, bool *ResultOverflowed=nullptr)
Add two unsigned integers, X and Y, of type T.
Definition MathExtras.h:604
constexpr bool isShiftedUInt(uint64_t x)
Checks if a unsigned integer is an N bit number shifted left by S.
Definition MathExtras.h:199
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:161
constexpr uint64_t NextPowerOf2(uint64_t A)
Returns the next power of two (in 64-bits) that is strictly greater than A.
Definition MathExtras.h:368
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39