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 CTLog2() {
327 static_assert(llvm::isPowerOf2_64(kValue), "Value is not a valid power of 2");
328 return 1 + CTLog2<kValue / 2>();
329}
330
331template <> constexpr size_t CTLog2<1>() { return 0; }
332
333/// Return the floor log base 2 of the specified value, -1 if the value is zero.
334/// (32 bit edition.)
335/// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
336inline unsigned Log2_32(uint32_t Value) {
337 return 31 - llvm::countl_zero(Value);
338}
339
340/// Return the floor log base 2 of the specified value, -1 if the value is zero.
341/// (64 bit edition.)
342inline unsigned Log2_64(uint64_t Value) {
343 return 63 - llvm::countl_zero(Value);
344}
345
346/// Return the ceil log base 2 of the specified value, 32 if the value is zero.
347/// (32 bit edition).
348/// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
349inline unsigned Log2_32_Ceil(uint32_t Value) {
350 return 32 - llvm::countl_zero(Value - 1);
351}
352
353/// Return the ceil log base 2 of the specified value, 64 if the value is zero.
354/// (64 bit edition.)
355inline unsigned Log2_64_Ceil(uint64_t Value) {
356 return 64 - llvm::countl_zero(Value - 1);
357}
358
359/// A and B are either alignments or offsets. Return the minimum alignment that
360/// may be assumed after adding the two together.
361template <typename U, typename V, typename T = common_uint<U, V>>
362constexpr T MinAlign(U A, V B) {
363 // The largest power of 2 that divides both A and B.
364 //
365 // Replace "-Value" by "1+~Value" in the following commented code to avoid
366 // MSVC warning C4146
367 // return (A | B) & -(A | B);
368 return (A | B) & (1 + ~(A | B));
369}
370
371/// Fallback when arguments aren't integral.
373 return (A | B) & (1 + ~(A | B));
374}
375
376/// Returns the next power of two (in 64-bits) that is strictly greater than A.
377/// Returns zero on overflow.
379 A |= (A >> 1);
380 A |= (A >> 2);
381 A |= (A >> 4);
382 A |= (A >> 8);
383 A |= (A >> 16);
384 A |= (A >> 32);
385 return A + 1;
386}
387
388/// Returns the power of two which is greater than or equal to the given value.
389/// Essentially, it is a ceil operation across the domain of powers of two.
391 if (!A || A > UINT64_MAX / 2)
392 return 0;
393 return UINT64_C(1) << Log2_64_Ceil(A);
394}
395
396/// Returns the integer ceil(Numerator / Denominator). Unsigned version.
397/// Guaranteed to never overflow.
398template <typename U, typename V, typename T = common_uint<U, V>>
399constexpr T divideCeil(U Numerator, V Denominator) {
400 assert(Denominator && "Division by zero");
401 T Bias = (Numerator != 0);
402 return (Numerator - Bias) / Denominator + Bias;
403}
404
405/// Fallback when arguments aren't integral.
406constexpr uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
407 assert(Denominator && "Division by zero");
408 uint64_t Bias = (Numerator != 0);
409 return (Numerator - Bias) / Denominator + Bias;
410}
411
412// Check whether divideCeilSigned or divideFloorSigned would overflow. This
413// happens only when Numerator = INT_MIN and Denominator = -1.
414template <typename U, typename V>
415constexpr bool divideSignedWouldOverflow(U Numerator, V Denominator) {
416 return Numerator == std::numeric_limits<U>::min() && Denominator == -1;
417}
418
419/// Returns the integer ceil(Numerator / Denominator). Signed version.
420/// Overflow is explicitly forbidden with an assert.
421template <typename U, typename V, typename T = common_sint<U, V>>
422constexpr T divideCeilSigned(U Numerator, V Denominator) {
423 assert(Denominator && "Division by zero");
424 assert(!divideSignedWouldOverflow(Numerator, Denominator) &&
425 "Divide would overflow");
426 if (!Numerator)
427 return 0;
428 // C's integer division rounds towards 0.
429 T Bias = Denominator >= 0 ? 1 : -1;
430 bool SameSign = (Numerator >= 0) == (Denominator >= 0);
431 return SameSign ? (Numerator - Bias) / Denominator + 1
432 : Numerator / Denominator;
433}
434
435/// Returns the integer floor(Numerator / Denominator). Signed version.
436/// Overflow is explicitly forbidden with an assert.
437template <typename U, typename V, typename T = common_sint<U, V>>
438constexpr T divideFloorSigned(U Numerator, V Denominator) {
439 assert(Denominator && "Division by zero");
440 assert(!divideSignedWouldOverflow(Numerator, Denominator) &&
441 "Divide would overflow");
442 if (!Numerator)
443 return 0;
444 // C's integer division rounds towards 0.
445 T Bias = Denominator >= 0 ? -1 : 1;
446 bool SameSign = (Numerator >= 0) == (Denominator >= 0);
447 return SameSign ? Numerator / Denominator
448 : (Numerator - Bias) / Denominator - 1;
449}
450
451/// Returns the remainder of the Euclidean division of LHS by RHS. Result is
452/// always non-negative.
453template <typename U, typename V, typename T = common_sint<U, V>>
454constexpr T mod(U Numerator, V Denominator) {
455 assert(Denominator >= 1 && "Mod by non-positive number");
456 T Mod = Numerator % Denominator;
457 return Mod < 0 ? Mod + Denominator : Mod;
458}
459
460/// Returns (Numerator / Denominator) rounded by round-half-up. Guaranteed to
461/// never overflow.
462template <typename U, typename V, typename T = common_uint<U, V>>
463constexpr T divideNearest(U Numerator, V Denominator) {
464 assert(Denominator && "Division by zero");
465 T Mod = Numerator % Denominator;
466 return (Numerator / Denominator) +
467 (Mod > (static_cast<T>(Denominator) - 1) / 2);
468}
469
470/// Returns the next integer (mod 2**nbits) that is greater than or equal to
471/// \p Value and is a multiple of \p Align. \p Align must be non-zero.
472///
473/// Examples:
474/// \code
475/// alignTo(5, 8) = 8
476/// alignTo(17, 8) = 24
477/// alignTo(~0LL, 8) = 0
478/// alignTo(321, 255) = 510
479/// \endcode
480///
481/// Will overflow only if result is not representable in T.
482template <typename U, typename V, typename T = common_uint<U, V>>
483constexpr T alignTo(U Value, V Align) {
484 assert(Align != 0u && "Align can't be 0.");
485 T CeilDiv = divideCeil(Value, Align);
486 return CeilDiv * Align;
487}
488
489/// Fallback when arguments aren't integral.
491 assert(Align != 0u && "Align can't be 0.");
492 uint64_t CeilDiv = divideCeil(Value, Align);
493 return CeilDiv * Align;
494}
495
496/// Will overflow only if result is not representable in T.
497template <typename U, typename V, typename T = common_uint<U, V>>
498constexpr T alignToPowerOf2(U Value, V Align) {
499 assert(Align != 0 && (Align & (Align - 1)) == 0 &&
500 "Align must be a power of 2");
501 T NegAlign = static_cast<T>(0) - Align;
502 return (Value + (Align - 1)) & NegAlign;
503}
504
505/// Fallback when arguments aren't integral.
507 assert(Align != 0 && (Align & (Align - 1)) == 0 &&
508 "Align must be a power of 2");
509 uint64_t NegAlign = 0 - Align;
510 return (Value + (Align - 1)) & NegAlign;
511}
512
513/// If non-zero \p Skew is specified, the return value will be a minimal integer
514/// that is greater than or equal to \p Size and equal to \p A * N + \p Skew for
515/// some integer N. If \p Skew is larger than \p A, its value is adjusted to '\p
516/// Skew mod \p A'. \p Align must be non-zero.
517///
518/// Examples:
519/// \code
520/// alignTo(5, 8, 7) = 7
521/// alignTo(17, 8, 1) = 17
522/// alignTo(~0LL, 8, 3) = 3
523/// alignTo(321, 255, 42) = 552
524/// \endcode
525///
526/// May overflow.
527template <typename U, typename V, typename W,
528 typename T = common_uint<common_uint<U, V>, W>>
529constexpr T alignTo(U Value, V Align, W Skew) {
530 assert(Align != 0u && "Align can't be 0.");
531 Skew %= Align;
532 return alignTo(Value - Skew, Align) + Skew;
533}
534
535/// Returns the next integer (mod 2**nbits) that is greater than or equal to
536/// \p Value and is a multiple of \c Align. \c Align must be non-zero.
537///
538/// Will overflow only if result is not representable in T.
539template <auto Align, typename V, typename T = common_uint<decltype(Align), V>>
540constexpr T alignTo(V Value) {
541 static_assert(Align != 0u, "Align must be non-zero");
542 T CeilDiv = divideCeil(Value, Align);
543 return CeilDiv * Align;
544}
545
546/// Returns the largest unsigned integer less than or equal to \p Value and is
547/// \p Skew mod \p Align. \p Align must be non-zero. Guaranteed to never
548/// overflow.
549template <typename U, typename V, typename W = uint8_t,
550 typename T = common_uint<common_uint<U, V>, W>>
551constexpr T alignDown(U Value, V Align, W Skew = 0) {
552 assert(Align != 0u && "Align can't be 0.");
553 Skew %= Align;
554 return (Value - Skew) / Align * Align + Skew;
555}
556
557/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
558/// Requires B <= 32.
559template <unsigned B> constexpr int32_t SignExtend32(uint32_t X) {
560 static_assert(B <= 32, "Bit width out of range.");
561 if constexpr (B == 0)
562 return 0;
563 return int32_t(X << (32 - B)) >> (32 - B);
564}
565
566/// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
567/// Requires B <= 32.
568inline int32_t SignExtend32(uint32_t X, unsigned B) {
569 assert(B <= 32 && "Bit width out of range.");
570 if (B == 0)
571 return 0;
572 return int32_t(X << (32 - B)) >> (32 - B);
573}
574
575/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
576/// Requires B <= 64.
577template <unsigned B> constexpr int64_t SignExtend64(uint64_t x) {
578 static_assert(B <= 64, "Bit width out of range.");
579 if constexpr (B == 0)
580 return 0;
581 return int64_t(x << (64 - B)) >> (64 - B);
582}
583
584/// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
585/// Requires B <= 64.
586inline int64_t SignExtend64(uint64_t X, unsigned B) {
587 assert(B <= 64 && "Bit width out of range.");
588 if (B == 0)
589 return 0;
590 return int64_t(X << (64 - B)) >> (64 - B);
591}
592
593/// Return the absolute value of a signed integer, converted to the
594/// corresponding unsigned integer type. Avoids undefined behavior in std::abs
595/// when you pass it INT_MIN or similar.
596template <typename T, typename U = std::make_unsigned_t<T>>
597constexpr U AbsoluteValue(T X) {
598 // If X is negative, cast it to the unsigned type _before_ negating it.
599 return X < 0 ? -static_cast<U>(X) : X;
600}
601
602/// Subtract two unsigned integers, X and Y, of type T and return the absolute
603/// value of the result.
604template <typename U, typename V, typename T = common_uint<U, V>>
605constexpr T AbsoluteDifference(U X, V Y) {
606 return X > Y ? (X - Y) : (Y - X);
607}
608
609/// Add two unsigned integers, X and Y, of type T. Clamp the result to the
610/// maximum representable value of T on overflow. ResultOverflowed indicates if
611/// the result is larger than the maximum representable value of type T.
612template <typename T>
613std::enable_if_t<std::is_unsigned_v<T>, T>
614SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
615 bool Dummy;
616 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
617 // Hacker's Delight, p. 29
618 T Z = X + Y;
619 Overflowed = (Z < X || Z < Y);
620 if (Overflowed)
621 return std::numeric_limits<T>::max();
622 else
623 return Z;
624}
625
626/// Add multiple unsigned integers of type T. Clamp the result to the
627/// maximum representable value of T on overflow.
628template <class T, class... Ts>
629std::enable_if_t<std::is_unsigned_v<T>, T> SaturatingAdd(T X, T Y, T Z,
630 Ts... Args) {
631 bool Overflowed = false;
632 T XY = SaturatingAdd(X, Y, &Overflowed);
633 if (Overflowed)
634 return SaturatingAdd(std::numeric_limits<T>::max(), T(1), Args...);
635 return SaturatingAdd(XY, Z, Args...);
636}
637
638/// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the
639/// maximum representable value of T on overflow. ResultOverflowed indicates if
640/// the result is larger than the maximum representable value of type T.
641template <typename T>
642std::enable_if_t<std::is_unsigned_v<T>, T>
643SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
644 bool Dummy;
645 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
646
647 // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
648 // because it fails for uint16_t (where multiplication can have undefined
649 // behavior due to promotion to int), and requires a division in addition
650 // to the multiplication.
651
652 Overflowed = false;
653
654 // Log2(Z) would be either Log2Z or Log2Z + 1.
655 // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
656 // will necessarily be less than Log2Max as desired.
657 int Log2Z = Log2_64(X) + Log2_64(Y);
658 const T Max = std::numeric_limits<T>::max();
659 int Log2Max = Log2_64(Max);
660 if (Log2Z < Log2Max) {
661 return X * Y;
662 }
663 if (Log2Z > Log2Max) {
664 Overflowed = true;
665 return Max;
666 }
667
668 // We're going to use the top bit, and maybe overflow one
669 // bit past it. Multiply all but the bottom bit then add
670 // that on at the end.
671 T Z = (X >> 1) * Y;
672 if (Z & ~(Max >> 1)) {
673 Overflowed = true;
674 return Max;
675 }
676 Z <<= 1;
677 if (X & 1)
678 return SaturatingAdd(Z, Y, ResultOverflowed);
679
680 return Z;
681}
682
683/// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
684/// the product. Clamp the result to the maximum representable value of T on
685/// overflow. ResultOverflowed indicates if the result is larger than the
686/// maximum representable value of type T.
687template <typename T>
688std::enable_if_t<std::is_unsigned_v<T>, T>
689SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
690 bool Dummy;
691 bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
692
693 T Product = SaturatingMultiply(X, Y, &Overflowed);
694 if (Overflowed)
695 return Product;
696
697 return SaturatingAdd(A, Product, &Overflowed);
698}
699
700/// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
701LLVM_ABI extern const float huge_valf;
702
703/// Add two signed integers, computing the two's complement truncated result,
704/// returning true if overflow occurred.
705template <typename T>
706std::enable_if_t<std::is_signed_v<T>, T> AddOverflow(T X, T Y, T &Result) {
707#if __has_builtin(__builtin_add_overflow)
708 return __builtin_add_overflow(X, Y, &Result);
709#else
710 // Perform the unsigned addition.
711 using U = std::make_unsigned_t<T>;
712 const U UX = static_cast<U>(X);
713 const U UY = static_cast<U>(Y);
714 const U UResult = UX + UY;
715
716 // Convert to signed.
717 Result = static_cast<T>(UResult);
718
719 // Adding two positive numbers should result in a positive number.
720 if (X > 0 && Y > 0)
721 return Result <= 0;
722 // Adding two negatives should result in a negative number.
723 if (X < 0 && Y < 0)
724 return Result >= 0;
725 return false;
726#endif
727}
728
729/// Subtract two signed integers, computing the two's complement truncated
730/// result, returning true if an overflow occurred.
731template <typename T>
732std::enable_if_t<std::is_signed_v<T>, T> SubOverflow(T X, T Y, T &Result) {
733#if __has_builtin(__builtin_sub_overflow)
734 return __builtin_sub_overflow(X, Y, &Result);
735#else
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 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 >= 0;
748 // Subtracting a negative number from a positive results in a positive number.
749 if (X >= 0 && Y < 0)
750 return Result <= 0;
751 return false;
752#endif
753}
754
755/// Multiply two signed integers, computing the two's complement truncated
756/// result, returning true if an overflow occurred.
757template <typename T>
758std::enable_if_t<std::is_signed_v<T>, T> MulOverflow(T X, T Y, T &Result) {
759#if __has_builtin(__builtin_mul_overflow)
760 return __builtin_mul_overflow(X, Y, &Result);
761#else
762 // Perform the unsigned multiplication on absolute values.
763 using U = std::make_unsigned_t<T>;
764 const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
765 const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
766 const U UResult = UX * UY;
767
768 // Convert to signed.
769 const bool IsNegative = (X < 0) ^ (Y < 0);
770 Result = IsNegative ? (0 - UResult) : UResult;
771
772 // If any of the args was 0, result is 0 and no overflow occurs.
773 if (UX == 0 || UY == 0)
774 return false;
775
776 // UX and UY are in [1, 2^n], where n is the number of digits.
777 // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
778 // positive) divided by an argument compares to the other.
779 if (IsNegative)
780 return UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY;
781 else
782 return UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
783#endif
784}
785
786/// Type to force float point values onto the stack, so that x86 doesn't add
787/// hidden precision, avoiding rounding differences on various platforms.
788#if defined(__i386__) || defined(_M_IX86)
789using stack_float_t = volatile float;
790#else
791using stack_float_t = float;
792#endif
793
794} // namespace llvm
795
796#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
#define LLVM_ABI
Definition: Compiler.h:213
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
#define R6(n)
#define T
uint64_t High
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
This file implements the C++20 <bit> header.
LLVM Value Representation.
Definition: Value.h:75
#define UINT64_MAX
Definition: DataTypes.h:77
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.
Definition: AddressRanges.h:18
std::common_type_t< std::make_unsigned_t< T >, std::make_unsigned_t< U > > common_uint
Definition: MathExtras.h:38
float stack_float_t
Type to force float point values onto the stack, so that x86 doesn't add hidden precision,...
Definition: MathExtras.h:791
@ Low
Lower the current thread's priority such that it does not affect foreground tasks significantly.
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:349
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:758
constexpr bool divideSignedWouldOverflow(U Numerator, V Denominator)
Definition: MathExtras.h:415
LLVM_ATTRIBUTE_ALWAYS_INLINE DynamicAPInt mod(const DynamicAPInt &LHS, const DynamicAPInt &RHS)
is always non-negative.
Definition: DynamicAPInt.h:395
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()
Compile time Log2.
Definition: MathExtras.h:326
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition: MathExtras.h:174
constexpr size_t CTLog2< 1 >()
Definition: MathExtras.h:331
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:355
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:438
constexpr int64_t minIntN(int64_t N)
Gets the minimum value for a N-bit signed integer.
Definition: MathExtras.h:232
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:551
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:342
uint64_t PowerOf2Ceil(uint64_t A)
Returns the power of two which is greater than or equal to the given value.
Definition: MathExtras.h:390
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:362
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
Definition: MathExtras.h:463
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:336
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
std::common_type_t< std::make_signed_t< T >, std::make_signed_t< U > > common_sint
Definition: MathExtras.h:41
constexpr T alignToPowerOf2(U Value, V Align)
Will overflow only if result is not representable in T.
Definition: MathExtras.h:498
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:689
constexpr bool isUInt(uint64_t x)
Checks if an unsigned integer fits into the given bit width.
Definition: MathExtras.h:198
constexpr T divideCeilSigned(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition: MathExtras.h:422
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.
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition: MathExtras.h:399
LLVM_ABI const float huge_valf
Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
Definition: MathExtras.cpp:28
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:643
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
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:605
constexpr U AbsoluteValue(T X)
Return the absolute value of a signed integer, converted to the corresponding unsigned integer type.
Definition: MathExtras.h:597
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:559
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:577
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:706
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:732
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:614
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:33
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:378
#define N
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39