//===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains some functions that are useful for math stuff. // //===----------------------------------------------------------------------===// #ifndef LLVM_SUPPORT_MATHEXTRAS_H #define LLVM_SUPPORT_MATHEXTRAS_H #include "llvm/ADT/bit.h" #include "llvm/Support/Compiler.h" #include <cassert> #include <climits> #include <cstdint> #include <cstring> #include <limits> #include <type_traits> namespace llvm { /// Some template parameter helpers to optimize for bitwidth, for functions that /// take multiple arguments. // We can't verify signedness, since callers rely on implicit coercions to // signed/unsigned. enableif_int; // Use std::common_type_t to widen only up to the widest argument. common_uint; common_sint; /// Mathematical constants. namespace numbers { // TODO: Track C++20 std::numbers. // TODO: Favor using the hexadecimal FP constants (requires C++17). constexpr double e = …, // (0x1.5bf0a8b145749P+1) https://oeis.org/A001113 egamma = …, // (0x1.2788cfc6fb619P-1) https://oeis.org/A001620 ln2 = …, // (0x1.62e42fefa39efP-1) https://oeis.org/A002162 ln10 = …, // (0x1.24bb1bbb55516P+1) https://oeis.org/A002392 log2e = …, // (0x1.71547652b82feP+0) log10e = …, // (0x1.bcb7b1526e50eP-2) pi = …, // (0x1.921fb54442d18P+1) https://oeis.org/A000796 inv_pi = …, // (0x1.45f306bc9c883P-2) https://oeis.org/A049541 sqrtpi = …, // (0x1.c5bf891b4ef6bP+0) https://oeis.org/A002161 inv_sqrtpi = …, // (0x1.20dd750429b6dP-1) https://oeis.org/A087197 sqrt2 = …, // (0x1.6a09e667f3bcdP+0) https://oeis.org/A00219 inv_sqrt2 = …, // (0x1.6a09e667f3bcdP-1) sqrt3 = …, // (0x1.bb67ae8584caaP+0) https://oeis.org/A002194 inv_sqrt3 = …, // (0x1.279a74590331cP-1) phi = …; // (0x1.9e3779b97f4a8P+0) https://oeis.org/A001622 constexpr float ef = …, // (0x1.5bf0a8P+1) https://oeis.org/A001113 egammaf = …, // (0x1.2788d0P-1) https://oeis.org/A001620 ln2f = …, // (0x1.62e430P-1) https://oeis.org/A002162 ln10f = …, // (0x1.26bb1cP+1) https://oeis.org/A002392 log2ef = …, // (0x1.715476P+0) log10ef = …, // (0x1.bcb7b2P-2) pif = …, // (0x1.921fb6P+1) https://oeis.org/A000796 inv_pif = …, // (0x1.45f306P-2) https://oeis.org/A049541 sqrtpif = …, // (0x1.c5bf8aP+0) https://oeis.org/A002161 inv_sqrtpif = …, // (0x1.20dd76P-1) https://oeis.org/A087197 sqrt2f = …, // (0x1.6a09e6P+0) https://oeis.org/A002193 inv_sqrt2f = …, // (0x1.6a09e6P-1) sqrt3f = …, // (0x1.bb67aeP+0) https://oeis.org/A002194 inv_sqrt3f = …, // (0x1.279a74P-1) phif = …; // (0x1.9e377aP+0) https://oeis.org/A001622 } // namespace numbers /// Create a bitmask with the N right-most bits set to 1, and all other /// bits set to 0. Only unsigned types are allowed. template <typename T> T maskTrailingOnes(unsigned N) { … } /// Create a bitmask with the N left-most bits set to 1, and all other /// bits set to 0. Only unsigned types are allowed. template <typename T> T maskLeadingOnes(unsigned N) { … } /// Create a bitmask with the N right-most bits set to 0, and all other /// bits set to 1. Only unsigned types are allowed. template <typename T> T maskTrailingZeros(unsigned N) { … } /// Create a bitmask with the N left-most bits set to 0, and all other /// bits set to 1. Only unsigned types are allowed. template <typename T> T maskLeadingZeros(unsigned N) { … } /// Macro compressed bit reversal table for 256 bits. /// /// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable static const unsigned char BitReverseTable256[256] = …; /// Reverse the bits in \p Val. template <typename T> T reverseBits(T Val) { … } // NOTE: The following support functions use the _32/_64 extensions instead of // type overloading so that signed and unsigned integers can be used without // ambiguity. /// Return the high 32 bits of a 64 bit value. constexpr uint32_t Hi_32(uint64_t Value) { … } /// Return the low 32 bits of a 64 bit value. constexpr uint32_t Lo_32(uint64_t Value) { … } /// Make a 64-bit integer from a high / low pair of 32-bit integers. constexpr uint64_t Make_64(uint32_t High, uint32_t Low) { … } /// Checks if an integer fits into the given bit width. template <unsigned N> constexpr bool isInt(int64_t x) { … } /// Checks if a signed integer is an N bit number shifted left by S. template <unsigned N, unsigned S> constexpr bool isShiftedInt(int64_t x) { … } /// Checks if an unsigned integer fits into the given bit width. template <unsigned N> constexpr bool isUInt(uint64_t x) { … } /// Checks if a unsigned integer is an N bit number shifted left by S. template <unsigned N, unsigned S> constexpr bool isShiftedUInt(uint64_t x) { … } /// Gets the maximum value for a N-bit unsigned integer. inline uint64_t maxUIntN(uint64_t N) { … } /// Gets the minimum value for a N-bit signed integer. inline int64_t minIntN(int64_t N) { … } /// Gets the maximum value for a N-bit signed integer. inline int64_t maxIntN(int64_t N) { … } /// Checks if an unsigned integer fits into the given (dynamic) bit width. inline bool isUIntN(unsigned N, uint64_t x) { … } /// Checks if an signed integer fits into the given (dynamic) bit width. inline bool isIntN(unsigned N, int64_t x) { … } /// Return true if the argument is a non-empty sequence of ones starting at the /// least significant bit with the remainder zero (32 bit version). /// Ex. isMask_32(0x0000FFFFU) == true. 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 with the remainder zero (64 bit version). constexpr bool isMask_64(uint64_t Value) { … } /// Return true if the argument contains a non-empty sequence of ones with the /// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true. constexpr bool isShiftedMask_32(uint32_t Value) { … } /// Return true if the argument contains a non-empty sequence of ones with the /// remainder zero (64 bit version.) constexpr bool isShiftedMask_64(uint64_t Value) { … } /// Return true if the argument is a power of two > 0. /// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.) constexpr bool isPowerOf2_32(uint32_t Value) { … } /// Return true if the argument is a power of two > 0 (64 bit edition.) constexpr bool isPowerOf2_64(uint64_t Value) { … } /// Return true if the argument contains a non-empty sequence of ones with the /// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true. /// If true, \p MaskIdx will specify the index of the lowest set bit and \p /// MaskLen is updated to specify the length of the mask, else neither are /// updated. inline bool isShiftedMask_32(uint32_t Value, unsigned &MaskIdx, unsigned &MaskLen) { … } /// Return true if the argument contains a non-empty sequence of ones with the /// remainder zero (64 bit version.) If true, \p MaskIdx will specify the index /// of the lowest set bit and \p MaskLen is updated to specify the length of the /// mask, else neither are updated. inline bool isShiftedMask_64(uint64_t Value, unsigned &MaskIdx, unsigned &MaskLen) { … } /// Compile time Log2. /// Valid only for positive powers of two. template <size_t kValue> constexpr size_t CTLog2() { … } template <> constexpr size_t CTLog2<1>() { … } /// Return the floor log base 2 of the specified value, -1 if the value is zero. /// (32 bit edition.) /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2 inline unsigned Log2_32(uint32_t Value) { … } /// Return the floor log base 2 of the specified value, -1 if the value is zero. /// (64 bit edition.) inline unsigned Log2_64(uint64_t Value) { … } /// Return the ceil log base 2 of the specified value, 32 if the value is zero. /// (32 bit edition). /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3 inline unsigned Log2_32_Ceil(uint32_t Value) { … } /// Return the ceil log base 2 of the specified value, 64 if the value is zero. /// (64 bit edition.) inline unsigned Log2_64_Ceil(uint64_t Value) { … } /// A and B are either alignments or offsets. Return the minimum alignment that /// may be assumed after adding the two together. template <typename U, typename V, typename T = common_uint<U, V>> constexpr T MinAlign(U A, V B) { … } /// Fallback when arguments aren't integral. constexpr uint64_t MinAlign(uint64_t A, uint64_t B) { … } /// Returns the next power of two (in 64-bits) that is strictly greater than A. /// Returns zero on overflow. constexpr uint64_t NextPowerOf2(uint64_t A) { … } /// Returns the power of two which is greater than or equal to the given value. /// Essentially, it is a ceil operation across the domain of powers of two. inline uint64_t PowerOf2Ceil(uint64_t A) { … } /// Returns the integer ceil(Numerator / Denominator). Unsigned version. /// Guaranteed to never overflow. template <typename U, typename V, typename T = common_uint<U, V>> constexpr T divideCeil(U Numerator, V Denominator) { … } /// Fallback when arguments aren't integral. constexpr uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) { … } // Check whether divideCeilSigned or divideFloorSigned would overflow. This // happens only when Numerator = INT_MIN and Denominator = -1. template <typename U, typename V> constexpr bool divideSignedWouldOverflow(U Numerator, V Denominator) { … } /// Returns the integer ceil(Numerator / Denominator). Signed version. /// Overflow is explicitly forbidden with an assert. template <typename U, typename V, typename T = common_sint<U, V>> constexpr T divideCeilSigned(U Numerator, V Denominator) { … } /// Returns the integer floor(Numerator / Denominator). Signed version. /// Overflow is explicitly forbidden with an assert. template <typename U, typename V, typename T = common_sint<U, V>> constexpr T divideFloorSigned(U Numerator, V Denominator) { … } /// Returns the remainder of the Euclidean division of LHS by RHS. Result is /// always non-negative. template <typename U, typename V, typename T = common_sint<U, V>> constexpr T mod(U Numerator, V Denominator) { … } /// Returns (Numerator / Denominator) rounded by round-half-up. Guaranteed to /// never overflow. template <typename U, typename V, typename T = common_uint<U, V>> constexpr T divideNearest(U Numerator, V Denominator) { … } /// Returns the next integer (mod 2**nbits) that is greater than or equal to /// \p Value and is a multiple of \p Align. \p Align must be non-zero. /// /// Examples: /// \code /// alignTo(5, 8) = 8 /// alignTo(17, 8) = 24 /// alignTo(~0LL, 8) = 0 /// alignTo(321, 255) = 510 /// \endcode /// /// Will overflow only if result is not representable in T. template <typename U, typename V, typename T = common_uint<U, V>> constexpr T alignTo(U Value, V Align) { … } /// Fallback when arguments aren't integral. constexpr uint64_t alignTo(uint64_t Value, uint64_t Align) { … } /// Will overflow only if result is not representable in T. template <typename U, typename V, typename T = common_uint<U, V>> constexpr T alignToPowerOf2(U Value, V Align) { … } /// Fallback when arguments aren't integral. constexpr uint64_t alignToPowerOf2(uint64_t Value, uint64_t Align) { … } /// If non-zero \p Skew is specified, the return value will be a minimal integer /// that is greater than or equal to \p Size and equal to \p A * N + \p Skew for /// some integer N. If \p Skew is larger than \p A, its value is adjusted to '\p /// Skew mod \p A'. \p Align must be non-zero. /// /// Examples: /// \code /// alignTo(5, 8, 7) = 7 /// alignTo(17, 8, 1) = 17 /// alignTo(~0LL, 8, 3) = 3 /// alignTo(321, 255, 42) = 552 /// \endcode /// /// May overflow. template <typename U, typename V, typename W, typename T = common_uint<common_uint<U, V>, W>> constexpr T alignTo(U Value, V Align, W Skew) { … } /// Returns the next integer (mod 2**nbits) that is greater than or equal to /// \p Value and is a multiple of \c Align. \c Align must be non-zero. /// /// Will overflow only if result is not representable in T. template <auto Align, typename V, typename T = common_uint<decltype(Align), V>> constexpr T alignTo(V Value) { … } /// Returns the largest unsigned integer less than or equal to \p Value and is /// \p Skew mod \p Align. \p Align must be non-zero. Guaranteed to never /// overflow. template <typename U, typename V, typename W = uint8_t, typename T = common_uint<common_uint<U, V>, W>> constexpr T alignDown(U Value, V Align, W Skew = 0) { … } /// Sign-extend the number in the bottom B bits of X to a 32-bit integer. /// Requires B <= 32. template <unsigned B> constexpr int32_t SignExtend32(uint32_t X) { … } /// Sign-extend the number in the bottom B bits of X to a 32-bit integer. /// Requires B <= 32. inline int32_t SignExtend32(uint32_t X, unsigned B) { … } /// Sign-extend the number in the bottom B bits of X to a 64-bit integer. /// Requires B <= 64. template <unsigned B> constexpr int64_t SignExtend64(uint64_t x) { … } /// Sign-extend the number in the bottom B bits of X to a 64-bit integer. /// Requires B <= 64. inline int64_t SignExtend64(uint64_t X, unsigned B) { … } /// Subtract two unsigned integers, X and Y, of type T and return the absolute /// value of the result. template <typename U, typename V, typename T = common_uint<U, V>> constexpr T AbsoluteDifference(U X, V Y) { … } /// Add two unsigned integers, X and Y, of type T. Clamp the result to the /// maximum representable value of T on overflow. ResultOverflowed indicates if /// the result is larger than the maximum representable value of type T. template <typename T> std::enable_if_t<std::is_unsigned_v<T>, T> SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) { … } /// Add multiple unsigned integers of type T. Clamp the result to the /// maximum representable value of T on overflow. template <class T, class... Ts> std::enable_if_t<std::is_unsigned_v<T>, T> SaturatingAdd(T X, T Y, T Z, Ts... Args) { … } /// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the /// maximum representable value of T on overflow. ResultOverflowed indicates if /// the result is larger than the maximum representable value of type T. template <typename T> 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, and add the unsigned integer, A to /// the product. Clamp the result to the maximum representable value of T on /// overflow. ResultOverflowed indicates if the result is larger than the /// maximum representable value of type T. template <typename T> std::enable_if_t<std::is_unsigned_v<T>, T> SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) { … } /// Use this rather than HUGE_VALF; the latter causes warnings on MSVC. extern const float huge_valf; /// Add two signed integers, computing the two's complement truncated result, /// returning true if overflow occurred. template <typename T> std::enable_if_t<std::is_signed_v<T>, T> AddOverflow(T X, T Y, T &Result) { … } /// Subtract two signed integers, computing the two's complement truncated /// result, returning true if an overflow ocurred. template <typename T> std::enable_if_t<std::is_signed_v<T>, T> SubOverflow(T X, T Y, T &Result) { … } /// Multiply two signed integers, computing the two's complement truncated /// result, returning true if an overflow ocurred. template <typename T> std::enable_if_t<std::is_signed_v<T>, T> MulOverflow(T X, T Y, T &Result) { … } /// Type to force float point values onto the stack, so that x86 doesn't add /// hidden precision, avoiding rounding differences on various platforms. #if defined(__i386__) || defined(_M_IX86) using stack_float_t = volatile float; #else stack_float_t; #endif } // namespace llvm #endif