MathExtras.h 33 KB

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