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