MathExtras.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===-- llvm/Support/MathExtras.h - Useful math functions -------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file contains some functions that are useful for math stuff.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_SUPPORT_MATHEXTRAS_H
  18. #define LLVM_SUPPORT_MATHEXTRAS_H
  19. #include "llvm/ADT/bit.h"
  20. #include "llvm/Support/Compiler.h"
  21. #include <cassert>
  22. #include <climits>
  23. #include <cstdint>
  24. #include <cstring>
  25. #include <limits>
  26. #include <type_traits>
  27. namespace llvm {
  28. /// The behavior an operation has on an input of 0.
  29. enum ZeroBehavior {
  30. /// The returned value is undefined.
  31. ZB_Undefined,
  32. /// The returned value is numeric_limits<T>::max()
  33. ZB_Max
  34. };
  35. /// Mathematical constants.
  36. namespace numbers {
  37. // TODO: Track C++20 std::numbers.
  38. // TODO: Favor using the hexadecimal FP constants (requires C++17).
  39. constexpr double e = 2.7182818284590452354, // (0x1.5bf0a8b145749P+1) https://oeis.org/A001113
  40. egamma = .57721566490153286061, // (0x1.2788cfc6fb619P-1) https://oeis.org/A001620
  41. ln2 = .69314718055994530942, // (0x1.62e42fefa39efP-1) https://oeis.org/A002162
  42. ln10 = 2.3025850929940456840, // (0x1.24bb1bbb55516P+1) https://oeis.org/A002392
  43. log2e = 1.4426950408889634074, // (0x1.71547652b82feP+0)
  44. log10e = .43429448190325182765, // (0x1.bcb7b1526e50eP-2)
  45. pi = 3.1415926535897932385, // (0x1.921fb54442d18P+1) https://oeis.org/A000796
  46. inv_pi = .31830988618379067154, // (0x1.45f306bc9c883P-2) https://oeis.org/A049541
  47. sqrtpi = 1.7724538509055160273, // (0x1.c5bf891b4ef6bP+0) https://oeis.org/A002161
  48. inv_sqrtpi = .56418958354775628695, // (0x1.20dd750429b6dP-1) https://oeis.org/A087197
  49. sqrt2 = 1.4142135623730950488, // (0x1.6a09e667f3bcdP+0) https://oeis.org/A00219
  50. inv_sqrt2 = .70710678118654752440, // (0x1.6a09e667f3bcdP-1)
  51. sqrt3 = 1.7320508075688772935, // (0x1.bb67ae8584caaP+0) https://oeis.org/A002194
  52. inv_sqrt3 = .57735026918962576451, // (0x1.279a74590331cP-1)
  53. phi = 1.6180339887498948482; // (0x1.9e3779b97f4a8P+0) https://oeis.org/A001622
  54. constexpr float ef = 2.71828183F, // (0x1.5bf0a8P+1) https://oeis.org/A001113
  55. egammaf = .577215665F, // (0x1.2788d0P-1) https://oeis.org/A001620
  56. ln2f = .693147181F, // (0x1.62e430P-1) https://oeis.org/A002162
  57. ln10f = 2.30258509F, // (0x1.26bb1cP+1) https://oeis.org/A002392
  58. log2ef = 1.44269504F, // (0x1.715476P+0)
  59. log10ef = .434294482F, // (0x1.bcb7b2P-2)
  60. pif = 3.14159265F, // (0x1.921fb6P+1) https://oeis.org/A000796
  61. inv_pif = .318309886F, // (0x1.45f306P-2) https://oeis.org/A049541
  62. sqrtpif = 1.77245385F, // (0x1.c5bf8aP+0) https://oeis.org/A002161
  63. inv_sqrtpif = .564189584F, // (0x1.20dd76P-1) https://oeis.org/A087197
  64. sqrt2f = 1.41421356F, // (0x1.6a09e6P+0) https://oeis.org/A002193
  65. inv_sqrt2f = .707106781F, // (0x1.6a09e6P-1)
  66. sqrt3f = 1.73205081F, // (0x1.bb67aeP+0) https://oeis.org/A002194
  67. inv_sqrt3f = .577350269F, // (0x1.279a74P-1)
  68. phif = 1.61803399F; // (0x1.9e377aP+0) https://oeis.org/A001622
  69. } // namespace numbers
  70. /// Count number of 0's from the least significant bit to the most
  71. /// stopping at the first 1.
  72. ///
  73. /// Only unsigned integral types are allowed.
  74. ///
  75. /// Returns std::numeric_limits<T>::digits on an input of 0.
  76. template <typename T> unsigned countTrailingZeros(T Val) {
  77. static_assert(std::is_unsigned_v<T>,
  78. "Only unsigned integral types are allowed.");
  79. return llvm::countr_zero(Val);
  80. }
  81. /// Count number of 0's from the most significant bit to the least
  82. /// stopping at the first 1.
  83. ///
  84. /// Only unsigned integral types are allowed.
  85. ///
  86. /// Returns std::numeric_limits<T>::digits on an input of 0.
  87. template <typename T> unsigned countLeadingZeros(T Val) {
  88. static_assert(std::is_unsigned_v<T>,
  89. "Only unsigned integral types are allowed.");
  90. return llvm::countl_zero(Val);
  91. }
  92. /// Get the index of the first set bit starting from the least
  93. /// significant bit.
  94. ///
  95. /// Only unsigned integral types are allowed.
  96. ///
  97. /// \param ZB the behavior on an input of 0.
  98. template <typename T> T findFirstSet(T Val, ZeroBehavior ZB = ZB_Max) {
  99. if (ZB == ZB_Max && Val == 0)
  100. return std::numeric_limits<T>::max();
  101. return llvm::countr_zero(Val);
  102. }
  103. /// Create a bitmask with the N right-most bits set to 1, and all other
  104. /// bits set to 0. Only unsigned types are allowed.
  105. template <typename T> T maskTrailingOnes(unsigned N) {
  106. static_assert(std::is_unsigned<T>::value, "Invalid type!");
  107. const unsigned Bits = CHAR_BIT * sizeof(T);
  108. assert(N <= Bits && "Invalid bit index");
  109. return N == 0 ? 0 : (T(-1) >> (Bits - N));
  110. }
  111. /// Create a bitmask with the N left-most bits set to 1, and all other
  112. /// bits set to 0. Only unsigned types are allowed.
  113. template <typename T> T maskLeadingOnes(unsigned N) {
  114. return ~maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
  115. }
  116. /// Create a bitmask with the N right-most bits set to 0, and all other
  117. /// bits set to 1. Only unsigned types are allowed.
  118. template <typename T> T maskTrailingZeros(unsigned N) {
  119. return maskLeadingOnes<T>(CHAR_BIT * sizeof(T) - N);
  120. }
  121. /// Create a bitmask with the N left-most bits set to 0, and all other
  122. /// bits set to 1. Only unsigned types are allowed.
  123. template <typename T> T maskLeadingZeros(unsigned N) {
  124. return maskTrailingOnes<T>(CHAR_BIT * sizeof(T) - N);
  125. }
  126. /// Get the index of the last set bit starting from the least
  127. /// significant bit.
  128. ///
  129. /// Only unsigned integral types are allowed.
  130. ///
  131. /// \param ZB the behavior on an input of 0.
  132. template <typename T> T findLastSet(T Val, ZeroBehavior ZB = ZB_Max) {
  133. if (ZB == ZB_Max && Val == 0)
  134. return std::numeric_limits<T>::max();
  135. // Use ^ instead of - because both gcc and llvm can remove the associated ^
  136. // in the __builtin_clz intrinsic on x86.
  137. return llvm::countl_zero(Val) ^ (std::numeric_limits<T>::digits - 1);
  138. }
  139. /// Macro compressed bit reversal table for 256 bits.
  140. ///
  141. /// http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
  142. static const unsigned char BitReverseTable256[256] = {
  143. #define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
  144. #define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
  145. #define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
  146. R6(0), R6(2), R6(1), R6(3)
  147. #undef R2
  148. #undef R4
  149. #undef R6
  150. };
  151. /// Reverse the bits in \p Val.
  152. template <typename T> T reverseBits(T Val) {
  153. #if __has_builtin(__builtin_bitreverse8)
  154. if constexpr (std::is_same_v<T, uint8_t>)
  155. return __builtin_bitreverse8(Val);
  156. #endif
  157. #if __has_builtin(__builtin_bitreverse16)
  158. if constexpr (std::is_same_v<T, uint16_t>)
  159. return __builtin_bitreverse16(Val);
  160. #endif
  161. #if __has_builtin(__builtin_bitreverse32)
  162. if constexpr (std::is_same_v<T, uint32_t>)
  163. return __builtin_bitreverse32(Val);
  164. #endif
  165. #if __has_builtin(__builtin_bitreverse64)
  166. if constexpr (std::is_same_v<T, uint64_t>)
  167. return __builtin_bitreverse64(Val);
  168. #endif
  169. unsigned char in[sizeof(Val)];
  170. unsigned char out[sizeof(Val)];
  171. std::memcpy(in, &Val, sizeof(Val));
  172. for (unsigned i = 0; i < sizeof(Val); ++i)
  173. out[(sizeof(Val) - i) - 1] = BitReverseTable256[in[i]];
  174. std::memcpy(&Val, out, sizeof(Val));
  175. return Val;
  176. }
  177. // NOTE: The following support functions use the _32/_64 extensions instead of
  178. // type overloading so that signed and unsigned integers can be used without
  179. // ambiguity.
  180. /// Return the high 32 bits of a 64 bit value.
  181. constexpr inline uint32_t Hi_32(uint64_t Value) {
  182. return static_cast<uint32_t>(Value >> 32);
  183. }
  184. /// Return the low 32 bits of a 64 bit value.
  185. constexpr inline uint32_t Lo_32(uint64_t Value) {
  186. return static_cast<uint32_t>(Value);
  187. }
  188. /// Make a 64-bit integer from a high / low pair of 32-bit integers.
  189. constexpr inline uint64_t Make_64(uint32_t High, uint32_t Low) {
  190. return ((uint64_t)High << 32) | (uint64_t)Low;
  191. }
  192. /// Checks if an integer fits into the given bit width.
  193. template <unsigned N> constexpr inline bool isInt(int64_t x) {
  194. if constexpr (N == 8)
  195. return static_cast<int8_t>(x) == x;
  196. if constexpr (N == 16)
  197. return static_cast<int16_t>(x) == x;
  198. if constexpr (N == 32)
  199. return static_cast<int32_t>(x) == x;
  200. if constexpr (N < 64)
  201. return -(INT64_C(1) << (N - 1)) <= x && x < (INT64_C(1) << (N - 1));
  202. (void)x; // MSVC v19.25 warns that x is unused.
  203. return true;
  204. }
  205. /// Checks if a signed integer is an N bit number shifted left by S.
  206. template <unsigned N, unsigned S>
  207. constexpr inline bool isShiftedInt(int64_t x) {
  208. static_assert(
  209. N > 0, "isShiftedInt<0> doesn't make sense (refers to a 0-bit number.");
  210. static_assert(N + S <= 64, "isShiftedInt<N, S> with N + S > 64 is too wide.");
  211. return isInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
  212. }
  213. /// Checks if an unsigned integer fits into the given bit width.
  214. template <unsigned N> constexpr inline bool isUInt(uint64_t x) {
  215. static_assert(N > 0, "isUInt<0> doesn't make sense");
  216. if constexpr (N == 8)
  217. return static_cast<uint8_t>(x) == x;
  218. if constexpr (N == 16)
  219. return static_cast<uint16_t>(x) == x;
  220. if constexpr (N == 32)
  221. return static_cast<uint32_t>(x) == x;
  222. if constexpr (N < 64)
  223. return x < (UINT64_C(1) << (N));
  224. (void)x; // MSVC v19.25 warns that x is unused.
  225. return true;
  226. }
  227. /// Checks if a unsigned integer is an N bit number shifted left by S.
  228. template <unsigned N, unsigned S>
  229. constexpr inline bool isShiftedUInt(uint64_t x) {
  230. static_assert(
  231. N > 0, "isShiftedUInt<0> doesn't make sense (refers to a 0-bit number)");
  232. static_assert(N + S <= 64,
  233. "isShiftedUInt<N, S> with N + S > 64 is too wide.");
  234. // Per the two static_asserts above, S must be strictly less than 64. So
  235. // 1 << S is not undefined behavior.
  236. return isUInt<N + S>(x) && (x % (UINT64_C(1) << S) == 0);
  237. }
  238. /// Gets the maximum value for a N-bit unsigned integer.
  239. inline uint64_t maxUIntN(uint64_t N) {
  240. assert(N > 0 && N <= 64 && "integer width out of range");
  241. // uint64_t(1) << 64 is undefined behavior, so we can't do
  242. // (uint64_t(1) << N) - 1
  243. // without checking first that N != 64. But this works and doesn't have a
  244. // branch.
  245. return UINT64_MAX >> (64 - N);
  246. }
  247. /// Gets the minimum value for a N-bit signed integer.
  248. inline int64_t minIntN(int64_t N) {
  249. assert(N > 0 && N <= 64 && "integer width out of range");
  250. return UINT64_C(1) + ~(UINT64_C(1) << (N - 1));
  251. }
  252. /// Gets the maximum value for a N-bit signed integer.
  253. inline int64_t maxIntN(int64_t N) {
  254. assert(N > 0 && N <= 64 && "integer width out of range");
  255. // This relies on two's complement wraparound when N == 64, so we convert to
  256. // int64_t only at the very end to avoid UB.
  257. return (UINT64_C(1) << (N - 1)) - 1;
  258. }
  259. /// Checks if an unsigned integer fits into the given (dynamic) bit width.
  260. inline bool isUIntN(unsigned N, uint64_t x) {
  261. return N >= 64 || x <= maxUIntN(N);
  262. }
  263. /// Checks if an signed integer fits into the given (dynamic) bit width.
  264. inline bool isIntN(unsigned N, int64_t x) {
  265. return N >= 64 || (minIntN(N) <= x && x <= maxIntN(N));
  266. }
  267. /// Return true if the argument is a non-empty sequence of ones starting at the
  268. /// least significant bit with the remainder zero (32 bit version).
  269. /// Ex. isMask_32(0x0000FFFFU) == true.
  270. constexpr inline bool isMask_32(uint32_t Value) {
  271. return Value && ((Value + 1) & Value) == 0;
  272. }
  273. /// Return true if the argument is a non-empty sequence of ones starting at the
  274. /// least significant bit with the remainder zero (64 bit version).
  275. constexpr inline bool isMask_64(uint64_t Value) {
  276. return Value && ((Value + 1) & Value) == 0;
  277. }
  278. /// Return true if the argument contains a non-empty sequence of ones with the
  279. /// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
  280. constexpr inline bool isShiftedMask_32(uint32_t Value) {
  281. return Value && isMask_32((Value - 1) | Value);
  282. }
  283. /// Return true if the argument contains a non-empty sequence of ones with the
  284. /// remainder zero (64 bit version.)
  285. constexpr inline bool isShiftedMask_64(uint64_t Value) {
  286. return Value && isMask_64((Value - 1) | Value);
  287. }
  288. /// Return true if the argument is a power of two > 0.
  289. /// Ex. isPowerOf2_32(0x00100000U) == true (32 bit edition.)
  290. constexpr inline bool isPowerOf2_32(uint32_t Value) {
  291. return llvm::has_single_bit(Value);
  292. }
  293. /// Return true if the argument is a power of two > 0 (64 bit edition.)
  294. constexpr inline bool isPowerOf2_64(uint64_t Value) {
  295. return llvm::has_single_bit(Value);
  296. }
  297. /// Count the number of ones from the most significant bit to the first
  298. /// zero bit.
  299. ///
  300. /// Ex. countLeadingOnes(0xFF0FFF00) == 8.
  301. /// Only unsigned integral types are allowed.
  302. ///
  303. /// Returns std::numeric_limits<T>::digits on an input of all ones.
  304. template <typename T> unsigned countLeadingOnes(T Value) {
  305. static_assert(std::is_unsigned_v<T>,
  306. "Only unsigned integral types are allowed.");
  307. return llvm::countl_one<T>(Value);
  308. }
  309. /// Count the number of ones from the least significant bit to the first
  310. /// zero bit.
  311. ///
  312. /// Ex. countTrailingOnes(0x00FF00FF) == 8.
  313. /// Only unsigned integral types are allowed.
  314. ///
  315. /// Returns std::numeric_limits<T>::digits on an input of all ones.
  316. template <typename T> unsigned countTrailingOnes(T Value) {
  317. static_assert(std::is_unsigned_v<T>,
  318. "Only unsigned integral types are allowed.");
  319. return llvm::countr_one<T>(Value);
  320. }
  321. /// Count the number of set bits in a value.
  322. /// Ex. countPopulation(0xF000F000) = 8
  323. /// Returns 0 if the word is zero.
  324. template <typename T>
  325. inline unsigned countPopulation(T Value) {
  326. static_assert(std::is_unsigned_v<T>,
  327. "Only unsigned integral types are allowed.");
  328. return (unsigned)llvm::popcount(Value);
  329. }
  330. /// Return true if the argument contains a non-empty sequence of ones with the
  331. /// remainder zero (32 bit version.) Ex. isShiftedMask_32(0x0000FF00U) == true.
  332. /// If true, \p MaskIdx will specify the index of the lowest set bit and \p
  333. /// MaskLen is updated to specify the length of the mask, else neither are
  334. /// updated.
  335. inline bool isShiftedMask_32(uint32_t Value, unsigned &MaskIdx,
  336. unsigned &MaskLen) {
  337. if (!isShiftedMask_32(Value))
  338. return false;
  339. MaskIdx = llvm::countr_zero(Value);
  340. MaskLen = llvm::popcount(Value);
  341. return true;
  342. }
  343. /// Return true if the argument contains a non-empty sequence of ones with the
  344. /// remainder zero (64 bit version.) If true, \p MaskIdx will specify the index
  345. /// of the lowest set bit and \p MaskLen is updated to specify the length of the
  346. /// mask, else neither are updated.
  347. inline bool isShiftedMask_64(uint64_t Value, unsigned &MaskIdx,
  348. unsigned &MaskLen) {
  349. if (!isShiftedMask_64(Value))
  350. return false;
  351. MaskIdx = llvm::countr_zero(Value);
  352. MaskLen = llvm::popcount(Value);
  353. return true;
  354. }
  355. /// Compile time Log2.
  356. /// Valid only for positive powers of two.
  357. template <size_t kValue> constexpr inline size_t CTLog2() {
  358. static_assert(kValue > 0 && llvm::isPowerOf2_64(kValue),
  359. "Value is not a valid power of 2");
  360. return 1 + CTLog2<kValue / 2>();
  361. }
  362. template <> constexpr inline size_t CTLog2<1>() { return 0; }
  363. /// Return the floor log base 2 of the specified value, -1 if the value is zero.
  364. /// (32 bit edition.)
  365. /// Ex. Log2_32(32) == 5, Log2_32(1) == 0, Log2_32(0) == -1, Log2_32(6) == 2
  366. inline unsigned Log2_32(uint32_t Value) {
  367. return 31 - llvm::countl_zero(Value);
  368. }
  369. /// Return the floor log base 2 of the specified value, -1 if the value is zero.
  370. /// (64 bit edition.)
  371. inline unsigned Log2_64(uint64_t Value) {
  372. return 63 - llvm::countl_zero(Value);
  373. }
  374. /// Return the ceil log base 2 of the specified value, 32 if the value is zero.
  375. /// (32 bit edition).
  376. /// Ex. Log2_32_Ceil(32) == 5, Log2_32_Ceil(1) == 0, Log2_32_Ceil(6) == 3
  377. inline unsigned Log2_32_Ceil(uint32_t Value) {
  378. return 32 - llvm::countl_zero(Value - 1);
  379. }
  380. /// Return the ceil log base 2 of the specified value, 64 if the value is zero.
  381. /// (64 bit edition.)
  382. inline unsigned Log2_64_Ceil(uint64_t Value) {
  383. return 64 - llvm::countl_zero(Value - 1);
  384. }
  385. /// This function takes a 64-bit integer and returns the bit equivalent double.
  386. inline double BitsToDouble(uint64_t Bits) {
  387. static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
  388. return llvm::bit_cast<double>(Bits);
  389. }
  390. /// This function takes a 32-bit integer and returns the bit equivalent float.
  391. inline float BitsToFloat(uint32_t Bits) {
  392. static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
  393. return llvm::bit_cast<float>(Bits);
  394. }
  395. /// This function takes a double and returns the bit equivalent 64-bit integer.
  396. /// Note that copying doubles around changes the bits of NaNs on some hosts,
  397. /// notably x86, so this routine cannot be used if these bits are needed.
  398. inline uint64_t DoubleToBits(double Double) {
  399. static_assert(sizeof(uint64_t) == sizeof(double), "Unexpected type sizes");
  400. return llvm::bit_cast<uint64_t>(Double);
  401. }
  402. /// This function takes a float and returns the bit equivalent 32-bit integer.
  403. /// Note that copying floats around changes the bits of NaNs on some hosts,
  404. /// notably x86, so this routine cannot be used if these bits are needed.
  405. inline uint32_t FloatToBits(float Float) {
  406. static_assert(sizeof(uint32_t) == sizeof(float), "Unexpected type sizes");
  407. return llvm::bit_cast<uint32_t>(Float);
  408. }
  409. /// A and B are either alignments or offsets. Return the minimum alignment that
  410. /// may be assumed after adding the two together.
  411. constexpr inline uint64_t MinAlign(uint64_t A, uint64_t B) {
  412. // The largest power of 2 that divides both A and B.
  413. //
  414. // Replace "-Value" by "1+~Value" in the following commented code to avoid
  415. // MSVC warning C4146
  416. // return (A | B) & -(A | B);
  417. return (A | B) & (1 + ~(A | B));
  418. }
  419. /// Returns the next power of two (in 64-bits) that is strictly greater than A.
  420. /// Returns zero on overflow.
  421. constexpr inline uint64_t NextPowerOf2(uint64_t A) {
  422. A |= (A >> 1);
  423. A |= (A >> 2);
  424. A |= (A >> 4);
  425. A |= (A >> 8);
  426. A |= (A >> 16);
  427. A |= (A >> 32);
  428. return A + 1;
  429. }
  430. /// Returns the power of two which is less than or equal to the given value.
  431. /// Essentially, it is a floor operation across the domain of powers of two.
  432. inline uint64_t PowerOf2Floor(uint64_t A) {
  433. return llvm::bit_floor(A);
  434. }
  435. /// Returns the power of two which is greater than or equal to the given value.
  436. /// Essentially, it is a ceil operation across the domain of powers of two.
  437. inline uint64_t PowerOf2Ceil(uint64_t A) {
  438. if (!A)
  439. return 0;
  440. return NextPowerOf2(A - 1);
  441. }
  442. /// Returns the next integer (mod 2**64) that is greater than or equal to
  443. /// \p Value and is a multiple of \p Align. \p Align must be non-zero.
  444. ///
  445. /// Examples:
  446. /// \code
  447. /// alignTo(5, 8) = 8
  448. /// alignTo(17, 8) = 24
  449. /// alignTo(~0LL, 8) = 0
  450. /// alignTo(321, 255) = 510
  451. /// \endcode
  452. inline uint64_t alignTo(uint64_t Value, uint64_t Align) {
  453. assert(Align != 0u && "Align can't be 0.");
  454. return (Value + Align - 1) / Align * Align;
  455. }
  456. inline uint64_t alignToPowerOf2(uint64_t Value, uint64_t Align) {
  457. assert(Align != 0 && (Align & (Align - 1)) == 0 &&
  458. "Align must be a power of 2");
  459. return (Value + Align - 1) & -Align;
  460. }
  461. /// If non-zero \p Skew is specified, the return value will be a minimal integer
  462. /// that is greater than or equal to \p Size and equal to \p A * N + \p Skew for
  463. /// some integer N. If \p Skew is larger than \p A, its value is adjusted to '\p
  464. /// Skew mod \p A'. \p Align must be non-zero.
  465. ///
  466. /// Examples:
  467. /// \code
  468. /// alignTo(5, 8, 7) = 7
  469. /// alignTo(17, 8, 1) = 17
  470. /// alignTo(~0LL, 8, 3) = 3
  471. /// alignTo(321, 255, 42) = 552
  472. /// \endcode
  473. inline uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew) {
  474. assert(Align != 0u && "Align can't be 0.");
  475. Skew %= Align;
  476. return alignTo(Value - Skew, Align) + Skew;
  477. }
  478. /// Returns the next integer (mod 2**64) that is greater than or equal to
  479. /// \p Value and is a multiple of \c Align. \c Align must be non-zero.
  480. template <uint64_t Align> constexpr inline uint64_t alignTo(uint64_t Value) {
  481. static_assert(Align != 0u, "Align must be non-zero");
  482. return (Value + Align - 1) / Align * Align;
  483. }
  484. /// Returns the integer ceil(Numerator / Denominator).
  485. inline uint64_t divideCeil(uint64_t Numerator, uint64_t Denominator) {
  486. return alignTo(Numerator, Denominator) / Denominator;
  487. }
  488. /// Returns the integer nearest(Numerator / Denominator).
  489. inline uint64_t divideNearest(uint64_t Numerator, uint64_t Denominator) {
  490. return (Numerator + (Denominator / 2)) / Denominator;
  491. }
  492. /// Returns the largest uint64_t less than or equal to \p Value and is
  493. /// \p Skew mod \p Align. \p Align must be non-zero
  494. inline uint64_t alignDown(uint64_t Value, uint64_t Align, uint64_t Skew = 0) {
  495. assert(Align != 0u && "Align can't be 0.");
  496. Skew %= Align;
  497. return (Value - Skew) / Align * Align + Skew;
  498. }
  499. /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
  500. /// Requires 0 < B <= 32.
  501. template <unsigned B> constexpr inline int32_t SignExtend32(uint32_t X) {
  502. static_assert(B > 0, "Bit width can't be 0.");
  503. static_assert(B <= 32, "Bit width out of range.");
  504. return int32_t(X << (32 - B)) >> (32 - B);
  505. }
  506. /// Sign-extend the number in the bottom B bits of X to a 32-bit integer.
  507. /// Requires 0 < B <= 32.
  508. inline int32_t SignExtend32(uint32_t X, unsigned B) {
  509. assert(B > 0 && "Bit width can't be 0.");
  510. assert(B <= 32 && "Bit width out of range.");
  511. return int32_t(X << (32 - B)) >> (32 - B);
  512. }
  513. /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
  514. /// Requires 0 < B <= 64.
  515. template <unsigned B> constexpr inline int64_t SignExtend64(uint64_t x) {
  516. static_assert(B > 0, "Bit width can't be 0.");
  517. static_assert(B <= 64, "Bit width out of range.");
  518. return int64_t(x << (64 - B)) >> (64 - B);
  519. }
  520. /// Sign-extend the number in the bottom B bits of X to a 64-bit integer.
  521. /// Requires 0 < B <= 64.
  522. inline int64_t SignExtend64(uint64_t X, unsigned B) {
  523. assert(B > 0 && "Bit width can't be 0.");
  524. assert(B <= 64 && "Bit width out of range.");
  525. return int64_t(X << (64 - B)) >> (64 - B);
  526. }
  527. /// Subtract two unsigned integers, X and Y, of type T and return the absolute
  528. /// value of the result.
  529. template <typename T>
  530. std::enable_if_t<std::is_unsigned<T>::value, T> AbsoluteDifference(T X, T Y) {
  531. return X > Y ? (X - Y) : (Y - X);
  532. }
  533. /// Add two unsigned integers, X and Y, of type T. Clamp the result to the
  534. /// maximum representable value of T on overflow. ResultOverflowed indicates if
  535. /// the result is larger than the maximum representable value of type T.
  536. template <typename T>
  537. std::enable_if_t<std::is_unsigned<T>::value, T>
  538. SaturatingAdd(T X, T Y, bool *ResultOverflowed = nullptr) {
  539. bool Dummy;
  540. bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
  541. // Hacker's Delight, p. 29
  542. T Z = X + Y;
  543. Overflowed = (Z < X || Z < Y);
  544. if (Overflowed)
  545. return std::numeric_limits<T>::max();
  546. else
  547. return Z;
  548. }
  549. /// Add multiple unsigned integers of type T. Clamp the result to the
  550. /// maximum representable value of T on overflow.
  551. template <class T, class... Ts>
  552. std::enable_if_t<std::is_unsigned_v<T>, T> SaturatingAdd(T X, T Y, T Z,
  553. Ts... Args) {
  554. bool Overflowed = false;
  555. T XY = SaturatingAdd(X, Y, &Overflowed);
  556. if (Overflowed)
  557. return SaturatingAdd(std::numeric_limits<T>::max(), T(1), Args...);
  558. return SaturatingAdd(XY, Z, Args...);
  559. }
  560. /// Multiply two unsigned integers, X and Y, of type T. Clamp the result to the
  561. /// maximum representable value of T on overflow. ResultOverflowed indicates if
  562. /// the result is larger than the maximum representable value of type T.
  563. template <typename T>
  564. std::enable_if_t<std::is_unsigned<T>::value, T>
  565. SaturatingMultiply(T X, T Y, bool *ResultOverflowed = nullptr) {
  566. bool Dummy;
  567. bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
  568. // Hacker's Delight, p. 30 has a different algorithm, but we don't use that
  569. // because it fails for uint16_t (where multiplication can have undefined
  570. // behavior due to promotion to int), and requires a division in addition
  571. // to the multiplication.
  572. Overflowed = false;
  573. // Log2(Z) would be either Log2Z or Log2Z + 1.
  574. // Special case: if X or Y is 0, Log2_64 gives -1, and Log2Z
  575. // will necessarily be less than Log2Max as desired.
  576. int Log2Z = Log2_64(X) + Log2_64(Y);
  577. const T Max = std::numeric_limits<T>::max();
  578. int Log2Max = Log2_64(Max);
  579. if (Log2Z < Log2Max) {
  580. return X * Y;
  581. }
  582. if (Log2Z > Log2Max) {
  583. Overflowed = true;
  584. return Max;
  585. }
  586. // We're going to use the top bit, and maybe overflow one
  587. // bit past it. Multiply all but the bottom bit then add
  588. // that on at the end.
  589. T Z = (X >> 1) * Y;
  590. if (Z & ~(Max >> 1)) {
  591. Overflowed = true;
  592. return Max;
  593. }
  594. Z <<= 1;
  595. if (X & 1)
  596. return SaturatingAdd(Z, Y, ResultOverflowed);
  597. return Z;
  598. }
  599. /// Multiply two unsigned integers, X and Y, and add the unsigned integer, A to
  600. /// the product. Clamp the result to the maximum representable value of T on
  601. /// overflow. ResultOverflowed indicates if the result is larger than the
  602. /// maximum representable value of type T.
  603. template <typename T>
  604. std::enable_if_t<std::is_unsigned<T>::value, T>
  605. SaturatingMultiplyAdd(T X, T Y, T A, bool *ResultOverflowed = nullptr) {
  606. bool Dummy;
  607. bool &Overflowed = ResultOverflowed ? *ResultOverflowed : Dummy;
  608. T Product = SaturatingMultiply(X, Y, &Overflowed);
  609. if (Overflowed)
  610. return Product;
  611. return SaturatingAdd(A, Product, &Overflowed);
  612. }
  613. /// Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
  614. extern const float huge_valf;
  615. /// Add two signed integers, computing the two's complement truncated result,
  616. /// returning true if overflow occurred.
  617. template <typename T>
  618. std::enable_if_t<std::is_signed<T>::value, T> AddOverflow(T X, T Y, T &Result) {
  619. #if __has_builtin(__builtin_add_overflow)
  620. return __builtin_add_overflow(X, Y, &Result);
  621. #else
  622. // Perform the unsigned addition.
  623. using U = std::make_unsigned_t<T>;
  624. const U UX = static_cast<U>(X);
  625. const U UY = static_cast<U>(Y);
  626. const U UResult = UX + UY;
  627. // Convert to signed.
  628. Result = static_cast<T>(UResult);
  629. // Adding two positive numbers should result in a positive number.
  630. if (X > 0 && Y > 0)
  631. return Result <= 0;
  632. // Adding two negatives should result in a negative number.
  633. if (X < 0 && Y < 0)
  634. return Result >= 0;
  635. return false;
  636. #endif
  637. }
  638. /// Subtract two signed integers, computing the two's complement truncated
  639. /// result, returning true if an overflow ocurred.
  640. template <typename T>
  641. std::enable_if_t<std::is_signed<T>::value, T> SubOverflow(T X, T Y, T &Result) {
  642. #if __has_builtin(__builtin_sub_overflow)
  643. return __builtin_sub_overflow(X, Y, &Result);
  644. #else
  645. // Perform the unsigned addition.
  646. using U = std::make_unsigned_t<T>;
  647. const U UX = static_cast<U>(X);
  648. const U UY = static_cast<U>(Y);
  649. const U UResult = UX - UY;
  650. // Convert to signed.
  651. Result = static_cast<T>(UResult);
  652. // Subtracting a positive number from a negative results in a negative number.
  653. if (X <= 0 && Y > 0)
  654. return Result >= 0;
  655. // Subtracting a negative number from a positive results in a positive number.
  656. if (X >= 0 && Y < 0)
  657. return Result <= 0;
  658. return false;
  659. #endif
  660. }
  661. /// Multiply two signed integers, computing the two's complement truncated
  662. /// result, returning true if an overflow ocurred.
  663. template <typename T>
  664. std::enable_if_t<std::is_signed<T>::value, T> MulOverflow(T X, T Y, T &Result) {
  665. // Perform the unsigned multiplication on absolute values.
  666. using U = std::make_unsigned_t<T>;
  667. const U UX = X < 0 ? (0 - static_cast<U>(X)) : static_cast<U>(X);
  668. const U UY = Y < 0 ? (0 - static_cast<U>(Y)) : static_cast<U>(Y);
  669. const U UResult = UX * UY;
  670. // Convert to signed.
  671. const bool IsNegative = (X < 0) ^ (Y < 0);
  672. Result = IsNegative ? (0 - UResult) : UResult;
  673. // If any of the args was 0, result is 0 and no overflow occurs.
  674. if (UX == 0 || UY == 0)
  675. return false;
  676. // UX and UY are in [1, 2^n], where n is the number of digits.
  677. // Check how the max allowed absolute value (2^n for negative, 2^(n-1) for
  678. // positive) divided by an argument compares to the other.
  679. if (IsNegative)
  680. return UX > (static_cast<U>(std::numeric_limits<T>::max()) + U(1)) / UY;
  681. else
  682. return UX > (static_cast<U>(std::numeric_limits<T>::max())) / UY;
  683. }
  684. } // End llvm namespace
  685. #endif
  686. #ifdef __GNUC__
  687. #pragma GCC diagnostic pop
  688. #endif