llvmMathExtras.h 29 KB

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