ScaledNumber.h 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. //===- llvm/Support/ScaledNumber.h - Support for scaled numbers -*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file contains functions (and a class) useful for working with scaled
  11. // numbers -- in particular, pairs of integers where one represents digits and
  12. // another represents a scale. The functions are helpers and live in the
  13. // namespace ScaledNumbers. The class ScaledNumber is useful for modelling
  14. // certain cost metrics that need simple, integer-like semantics that are easy
  15. // to reason about.
  16. //
  17. // These might remind you of soft-floats. If you want one of those, you're in
  18. // the wrong place. Look at include/llvm/ADT/APFloat.h instead.
  19. //
  20. //===----------------------------------------------------------------------===//
  21. #ifndef LLVM_SUPPORT_SCALEDNUMBER_H
  22. #define LLVM_SUPPORT_SCALEDNUMBER_H
  23. #include "llvm/Support/MathExtras.h"
  24. #include <algorithm>
  25. #include <cstdint>
  26. #include <limits>
  27. #include <string>
  28. #include <tuple>
  29. #include <utility>
  30. namespace llvm {
  31. namespace ScaledNumbers {
  32. /// \brief Maximum scale; same as APFloat for easy debug printing.
  33. const int32_t MaxScale = 16383;
  34. /// \brief Maximum scale; same as APFloat for easy debug printing.
  35. const int32_t MinScale = -16382;
  36. /// \brief Get the width of a number.
  37. template <class DigitsT> inline int getWidth() { return sizeof(DigitsT) * 8; }
  38. /// \brief Conditionally round up a scaled number.
  39. ///
  40. /// Given \c Digits and \c Scale, round up iff \c ShouldRound is \c true.
  41. /// Always returns \c Scale unless there's an overflow, in which case it
  42. /// returns \c 1+Scale.
  43. ///
  44. /// \pre adding 1 to \c Scale will not overflow INT16_MAX.
  45. template <class DigitsT>
  46. inline std::pair<DigitsT, int16_t> getRounded(DigitsT Digits, int16_t Scale,
  47. bool ShouldRound) {
  48. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  49. if (ShouldRound)
  50. if (!++Digits)
  51. // Overflow.
  52. return std::make_pair(DigitsT(1) << (getWidth<DigitsT>() - 1), Scale + 1);
  53. return std::make_pair(Digits, Scale);
  54. }
  55. /// \brief Convenience helper for 32-bit rounding.
  56. inline std::pair<uint32_t, int16_t> getRounded32(uint32_t Digits, int16_t Scale,
  57. bool ShouldRound) {
  58. return getRounded(Digits, Scale, ShouldRound);
  59. }
  60. /// \brief Convenience helper for 64-bit rounding.
  61. inline std::pair<uint64_t, int16_t> getRounded64(uint64_t Digits, int16_t Scale,
  62. bool ShouldRound) {
  63. return getRounded(Digits, Scale, ShouldRound);
  64. }
  65. /// \brief Adjust a 64-bit scaled number down to the appropriate width.
  66. ///
  67. /// \pre Adding 64 to \c Scale will not overflow INT16_MAX.
  68. template <class DigitsT>
  69. inline std::pair<DigitsT, int16_t> getAdjusted(uint64_t Digits,
  70. int16_t Scale = 0) {
  71. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  72. const int Width = getWidth<DigitsT>();
  73. if (Width == 64 || Digits <= std::numeric_limits<DigitsT>::max())
  74. return std::make_pair(Digits, Scale);
  75. // Shift right and round.
  76. int Shift = 64 - Width - countLeadingZeros(Digits);
  77. return getRounded<DigitsT>(Digits >> Shift, Scale + Shift,
  78. Digits & (UINT64_C(1) << (Shift - 1)));
  79. }
  80. /// \brief Convenience helper for adjusting to 32 bits.
  81. inline std::pair<uint32_t, int16_t> getAdjusted32(uint64_t Digits,
  82. int16_t Scale = 0) {
  83. return getAdjusted<uint32_t>(Digits, Scale);
  84. }
  85. /// \brief Convenience helper for adjusting to 64 bits.
  86. inline std::pair<uint64_t, int16_t> getAdjusted64(uint64_t Digits,
  87. int16_t Scale = 0) {
  88. return getAdjusted<uint64_t>(Digits, Scale);
  89. }
  90. /// \brief Multiply two 64-bit integers to create a 64-bit scaled number.
  91. ///
  92. /// Implemented with four 64-bit integer multiplies.
  93. std::pair<uint64_t, int16_t> multiply64(uint64_t LHS, uint64_t RHS);
  94. /// \brief Multiply two 32-bit integers to create a 32-bit scaled number.
  95. ///
  96. /// Implemented with one 64-bit integer multiply.
  97. template <class DigitsT>
  98. inline std::pair<DigitsT, int16_t> getProduct(DigitsT LHS, DigitsT RHS) {
  99. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  100. if (getWidth<DigitsT>() <= 32 || (LHS <= UINT32_MAX && RHS <= UINT32_MAX))
  101. return getAdjusted<DigitsT>(uint64_t(LHS) * RHS);
  102. return multiply64(LHS, RHS);
  103. }
  104. /// \brief Convenience helper for 32-bit product.
  105. inline std::pair<uint32_t, int16_t> getProduct32(uint32_t LHS, uint32_t RHS) {
  106. return getProduct(LHS, RHS);
  107. }
  108. /// \brief Convenience helper for 64-bit product.
  109. inline std::pair<uint64_t, int16_t> getProduct64(uint64_t LHS, uint64_t RHS) {
  110. return getProduct(LHS, RHS);
  111. }
  112. /// \brief Divide two 64-bit integers to create a 64-bit scaled number.
  113. ///
  114. /// Implemented with long division.
  115. ///
  116. /// \pre \c Dividend and \c Divisor are non-zero.
  117. std::pair<uint64_t, int16_t> divide64(uint64_t Dividend, uint64_t Divisor);
  118. /// \brief Divide two 32-bit integers to create a 32-bit scaled number.
  119. ///
  120. /// Implemented with one 64-bit integer divide/remainder pair.
  121. ///
  122. /// \pre \c Dividend and \c Divisor are non-zero.
  123. std::pair<uint32_t, int16_t> divide32(uint32_t Dividend, uint32_t Divisor);
  124. /// \brief Divide two 32-bit numbers to create a 32-bit scaled number.
  125. ///
  126. /// Implemented with one 64-bit integer divide/remainder pair.
  127. ///
  128. /// Returns \c (DigitsT_MAX, MaxScale) for divide-by-zero (0 for 0/0).
  129. template <class DigitsT>
  130. std::pair<DigitsT, int16_t> getQuotient(DigitsT Dividend, DigitsT Divisor) {
  131. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  132. static_assert(sizeof(DigitsT) == 4 || sizeof(DigitsT) == 8,
  133. "expected 32-bit or 64-bit digits");
  134. // Check for zero.
  135. if (!Dividend)
  136. return std::make_pair(0, 0);
  137. if (!Divisor)
  138. return std::make_pair(std::numeric_limits<DigitsT>::max(), MaxScale);
  139. if (getWidth<DigitsT>() == 64)
  140. return divide64(Dividend, Divisor);
  141. return divide32(Dividend, Divisor);
  142. }
  143. /// \brief Convenience helper for 32-bit quotient.
  144. inline std::pair<uint32_t, int16_t> getQuotient32(uint32_t Dividend,
  145. uint32_t Divisor) {
  146. return getQuotient(Dividend, Divisor);
  147. }
  148. /// \brief Convenience helper for 64-bit quotient.
  149. inline std::pair<uint64_t, int16_t> getQuotient64(uint64_t Dividend,
  150. uint64_t Divisor) {
  151. return getQuotient(Dividend, Divisor);
  152. }
  153. /// \brief Implementation of getLg() and friends.
  154. ///
  155. /// Returns the rounded lg of \c Digits*2^Scale and an int specifying whether
  156. /// this was rounded up (1), down (-1), or exact (0).
  157. ///
  158. /// Returns \c INT32_MIN when \c Digits is zero.
  159. template <class DigitsT>
  160. inline std::pair<int32_t, int> getLgImpl(DigitsT Digits, int16_t Scale) {
  161. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  162. if (!Digits)
  163. return std::make_pair(INT32_MIN, 0);
  164. // Get the floor of the lg of Digits.
  165. int32_t LocalFloor = sizeof(Digits) * 8 - countLeadingZeros(Digits) - 1;
  166. // Get the actual floor.
  167. int32_t Floor = Scale + LocalFloor;
  168. if (Digits == UINT64_C(1) << LocalFloor)
  169. return std::make_pair(Floor, 0);
  170. // Round based on the next digit.
  171. assert(LocalFloor >= 1);
  172. bool Round = Digits & UINT64_C(1) << (LocalFloor - 1);
  173. return std::make_pair(Floor + Round, Round ? 1 : -1);
  174. }
  175. /// \brief Get the lg (rounded) of a scaled number.
  176. ///
  177. /// Get the lg of \c Digits*2^Scale.
  178. ///
  179. /// Returns \c INT32_MIN when \c Digits is zero.
  180. template <class DigitsT> int32_t getLg(DigitsT Digits, int16_t Scale) {
  181. return getLgImpl(Digits, Scale).first;
  182. }
  183. /// \brief Get the lg floor of a scaled number.
  184. ///
  185. /// Get the floor of the lg of \c Digits*2^Scale.
  186. ///
  187. /// Returns \c INT32_MIN when \c Digits is zero.
  188. template <class DigitsT> int32_t getLgFloor(DigitsT Digits, int16_t Scale) {
  189. auto Lg = getLgImpl(Digits, Scale);
  190. return Lg.first - (Lg.second > 0);
  191. }
  192. /// \brief Get the lg ceiling of a scaled number.
  193. ///
  194. /// Get the ceiling of the lg of \c Digits*2^Scale.
  195. ///
  196. /// Returns \c INT32_MIN when \c Digits is zero.
  197. template <class DigitsT> int32_t getLgCeiling(DigitsT Digits, int16_t Scale) {
  198. auto Lg = getLgImpl(Digits, Scale);
  199. return Lg.first + (Lg.second < 0);
  200. }
  201. /// \brief Implementation for comparing scaled numbers.
  202. ///
  203. /// Compare two 64-bit numbers with different scales. Given that the scale of
  204. /// \c L is higher than that of \c R by \c ScaleDiff, compare them. Return -1,
  205. /// 1, and 0 for less than, greater than, and equal, respectively.
  206. ///
  207. /// \pre 0 <= ScaleDiff < 64.
  208. int compareImpl(uint64_t L, uint64_t R, int ScaleDiff);
  209. /// \brief Compare two scaled numbers.
  210. ///
  211. /// Compare two scaled numbers. Returns 0 for equal, -1 for less than, and 1
  212. /// for greater than.
  213. template <class DigitsT>
  214. int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale) {
  215. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  216. // Check for zero.
  217. if (!LDigits)
  218. return RDigits ? -1 : 0;
  219. if (!RDigits)
  220. return 1;
  221. // Check for the scale. Use getLgFloor to be sure that the scale difference
  222. // is always lower than 64.
  223. int32_t lgL = getLgFloor(LDigits, LScale), lgR = getLgFloor(RDigits, RScale);
  224. if (lgL != lgR)
  225. return lgL < lgR ? -1 : 1;
  226. // Compare digits.
  227. if (LScale < RScale)
  228. return compareImpl(LDigits, RDigits, RScale - LScale);
  229. return -compareImpl(RDigits, LDigits, LScale - RScale);
  230. }
  231. /// \brief Match scales of two numbers.
  232. ///
  233. /// Given two scaled numbers, match up their scales. Change the digits and
  234. /// scales in place. Shift the digits as necessary to form equivalent numbers,
  235. /// losing precision only when necessary.
  236. ///
  237. /// If the output value of \c LDigits (\c RDigits) is \c 0, the output value of
  238. /// \c LScale (\c RScale) is unspecified.
  239. ///
  240. /// As a convenience, returns the matching scale. If the output value of one
  241. /// number is zero, returns the scale of the other. If both are zero, which
  242. /// scale is returned is unspecifed.
  243. template <class DigitsT>
  244. int16_t matchScales(DigitsT &LDigits, int16_t &LScale, DigitsT &RDigits,
  245. int16_t &RScale) {
  246. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  247. if (LScale < RScale)
  248. // Swap arguments.
  249. return matchScales(RDigits, RScale, LDigits, LScale);
  250. if (!LDigits)
  251. return RScale;
  252. if (!RDigits || LScale == RScale)
  253. return LScale;
  254. // Now LScale > RScale. Get the difference.
  255. int32_t ScaleDiff = int32_t(LScale) - RScale;
  256. if (ScaleDiff >= 2 * getWidth<DigitsT>()) {
  257. // Don't bother shifting. RDigits will get zero-ed out anyway.
  258. RDigits = 0;
  259. return LScale;
  260. }
  261. // Shift LDigits left as much as possible, then shift RDigits right.
  262. int32_t ShiftL = std::min<int32_t>(countLeadingZeros(LDigits), ScaleDiff);
  263. assert(ShiftL < getWidth<DigitsT>() && "can't shift more than width");
  264. int32_t ShiftR = ScaleDiff - ShiftL;
  265. if (ShiftR >= getWidth<DigitsT>()) {
  266. // Don't bother shifting. RDigits will get zero-ed out anyway.
  267. RDigits = 0;
  268. return LScale;
  269. }
  270. LDigits <<= ShiftL;
  271. RDigits >>= ShiftR;
  272. LScale -= ShiftL;
  273. RScale += ShiftR;
  274. assert(LScale == RScale && "scales should match");
  275. return LScale;
  276. }
  277. /// \brief Get the sum of two scaled numbers.
  278. ///
  279. /// Get the sum of two scaled numbers with as much precision as possible.
  280. ///
  281. /// \pre Adding 1 to \c LScale (or \c RScale) will not overflow INT16_MAX.
  282. template <class DigitsT>
  283. std::pair<DigitsT, int16_t> getSum(DigitsT LDigits, int16_t LScale,
  284. DigitsT RDigits, int16_t RScale) {
  285. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  286. // Check inputs up front. This is only relevent if addition overflows, but
  287. // testing here should catch more bugs.
  288. assert(LScale < INT16_MAX && "scale too large");
  289. assert(RScale < INT16_MAX && "scale too large");
  290. // Normalize digits to match scales.
  291. int16_t Scale = matchScales(LDigits, LScale, RDigits, RScale);
  292. // Compute sum.
  293. DigitsT Sum = LDigits + RDigits;
  294. if (Sum >= RDigits)
  295. return std::make_pair(Sum, Scale);
  296. // Adjust sum after arithmetic overflow.
  297. DigitsT HighBit = DigitsT(1) << (getWidth<DigitsT>() - 1);
  298. return std::make_pair(HighBit | Sum >> 1, Scale + 1);
  299. }
  300. /// \brief Convenience helper for 32-bit sum.
  301. inline std::pair<uint32_t, int16_t> getSum32(uint32_t LDigits, int16_t LScale,
  302. uint32_t RDigits, int16_t RScale) {
  303. return getSum(LDigits, LScale, RDigits, RScale);
  304. }
  305. /// \brief Convenience helper for 64-bit sum.
  306. inline std::pair<uint64_t, int16_t> getSum64(uint64_t LDigits, int16_t LScale,
  307. uint64_t RDigits, int16_t RScale) {
  308. return getSum(LDigits, LScale, RDigits, RScale);
  309. }
  310. /// \brief Get the difference of two scaled numbers.
  311. ///
  312. /// Get LHS minus RHS with as much precision as possible.
  313. ///
  314. /// Returns \c (0, 0) if the RHS is larger than the LHS.
  315. template <class DigitsT>
  316. std::pair<DigitsT, int16_t> getDifference(DigitsT LDigits, int16_t LScale,
  317. DigitsT RDigits, int16_t RScale) {
  318. static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
  319. // Normalize digits to match scales.
  320. const DigitsT SavedRDigits = RDigits;
  321. const int16_t SavedRScale = RScale;
  322. matchScales(LDigits, LScale, RDigits, RScale);
  323. // Compute difference.
  324. if (LDigits <= RDigits)
  325. return std::make_pair(0, 0);
  326. if (RDigits || !SavedRDigits)
  327. return std::make_pair(LDigits - RDigits, LScale);
  328. // Check if RDigits just barely lost its last bit. E.g., for 32-bit:
  329. //
  330. // 1*2^32 - 1*2^0 == 0xffffffff != 1*2^32
  331. const auto RLgFloor = getLgFloor(SavedRDigits, SavedRScale);
  332. if (!compare(LDigits, LScale, DigitsT(1), RLgFloor + getWidth<DigitsT>()))
  333. return std::make_pair(std::numeric_limits<DigitsT>::max(), RLgFloor);
  334. return std::make_pair(LDigits, LScale);
  335. }
  336. /// \brief Convenience helper for 32-bit difference.
  337. inline std::pair<uint32_t, int16_t> getDifference32(uint32_t LDigits,
  338. int16_t LScale,
  339. uint32_t RDigits,
  340. int16_t RScale) {
  341. return getDifference(LDigits, LScale, RDigits, RScale);
  342. }
  343. /// \brief Convenience helper for 64-bit difference.
  344. inline std::pair<uint64_t, int16_t> getDifference64(uint64_t LDigits,
  345. int16_t LScale,
  346. uint64_t RDigits,
  347. int16_t RScale) {
  348. return getDifference(LDigits, LScale, RDigits, RScale);
  349. }
  350. } // end namespace ScaledNumbers
  351. } // end namespace llvm
  352. namespace llvm {
  353. class raw_ostream;
  354. class ScaledNumberBase {
  355. public:
  356. static const int DefaultPrecision = 10;
  357. static void dump(uint64_t D, int16_t E, int Width);
  358. static raw_ostream &print(raw_ostream &OS, uint64_t D, int16_t E, int Width,
  359. unsigned Precision);
  360. static std::string toString(uint64_t D, int16_t E, int Width,
  361. unsigned Precision);
  362. static int countLeadingZeros32(uint32_t N) { return countLeadingZeros(N); }
  363. static int countLeadingZeros64(uint64_t N) { return countLeadingZeros(N); }
  364. static uint64_t getHalf(uint64_t N) { return (N >> 1) + (N & 1); }
  365. static std::pair<uint64_t, bool> splitSigned(int64_t N) {
  366. if (N >= 0)
  367. return std::make_pair(N, false);
  368. uint64_t Unsigned = N == INT64_MIN ? UINT64_C(1) << 63 : uint64_t(-N);
  369. return std::make_pair(Unsigned, true);
  370. }
  371. static int64_t joinSigned(uint64_t U, bool IsNeg) {
  372. if (U > uint64_t(INT64_MAX))
  373. return IsNeg ? INT64_MIN : INT64_MAX;
  374. return IsNeg ? -int64_t(U) : int64_t(U);
  375. }
  376. };
  377. /// \brief Simple representation of a scaled number.
  378. ///
  379. /// ScaledNumber is a number represented by digits and a scale. It uses simple
  380. /// saturation arithmetic and every operation is well-defined for every value.
  381. /// It's somewhat similar in behaviour to a soft-float, but is *not* a
  382. /// replacement for one. If you're doing numerics, look at \a APFloat instead.
  383. /// Nevertheless, we've found these semantics useful for modelling certain cost
  384. /// metrics.
  385. ///
  386. /// The number is split into a signed scale and unsigned digits. The number
  387. /// represented is \c getDigits()*2^getScale(). In this way, the digits are
  388. /// much like the mantissa in the x87 long double, but there is no canonical
  389. /// form so the same number can be represented by many bit representations.
  390. ///
  391. /// ScaledNumber is templated on the underlying integer type for digits, which
  392. /// is expected to be unsigned.
  393. ///
  394. /// Unlike APFloat, ScaledNumber does not model architecture floating point
  395. /// behaviour -- while this might make it a little faster and easier to reason
  396. /// about, it certainly makes it more dangerous for general numerics.
  397. ///
  398. /// ScaledNumber is totally ordered. However, there is no canonical form, so
  399. /// there are multiple representations of most scalars. E.g.:
  400. ///
  401. /// ScaledNumber(8u, 0) == ScaledNumber(4u, 1)
  402. /// ScaledNumber(4u, 1) == ScaledNumber(2u, 2)
  403. /// ScaledNumber(2u, 2) == ScaledNumber(1u, 3)
  404. ///
  405. /// ScaledNumber implements most arithmetic operations. Precision is kept
  406. /// where possible. Uses simple saturation arithmetic, so that operations
  407. /// saturate to 0.0 or getLargest() rather than under or overflowing. It has
  408. /// some extra arithmetic for unit inversion. 0.0/0.0 is defined to be 0.0.
  409. /// Any other division by 0.0 is defined to be getLargest().
  410. ///
  411. /// As a convenience for modifying the exponent, left and right shifting are
  412. /// both implemented, and both interpret negative shifts as positive shifts in
  413. /// the opposite direction.
  414. ///
  415. /// Scales are limited to the range accepted by x87 long double. This makes
  416. /// it trivial to add functionality to convert to APFloat (this is already
  417. /// relied on for the implementation of printing).
  418. ///
  419. /// Possible (and conflicting) future directions:
  420. ///
  421. /// 1. Turn this into a wrapper around \a APFloat.
  422. /// 2. Share the algorithm implementations with \a APFloat.
  423. /// 3. Allow \a ScaledNumber to represent a signed number.
  424. template <class DigitsT> class ScaledNumber : ScaledNumberBase {
  425. public:
  426. static_assert(!std::numeric_limits<DigitsT>::is_signed,
  427. "only unsigned floats supported");
  428. typedef DigitsT DigitsType;
  429. private:
  430. typedef std::numeric_limits<DigitsType> DigitsLimits;
  431. static const int Width = sizeof(DigitsType) * 8;
  432. static_assert(Width <= 64, "invalid integer width for digits");
  433. private:
  434. DigitsType Digits;
  435. int16_t Scale;
  436. public:
  437. ScaledNumber() : Digits(0), Scale(0) {}
  438. ScaledNumber(DigitsType Digits, int16_t Scale)
  439. : Digits(Digits), Scale(Scale) {}
  440. private:
  441. ScaledNumber(const std::pair<DigitsT, int16_t> &X)
  442. : Digits(X.first), Scale(X.second) {}
  443. public:
  444. static ScaledNumber getZero() { return ScaledNumber(0, 0); }
  445. static ScaledNumber getOne() { return ScaledNumber(1, 0); }
  446. static ScaledNumber getLargest() {
  447. return ScaledNumber(DigitsLimits::max(), ScaledNumbers::MaxScale);
  448. }
  449. static ScaledNumber get(uint64_t N) { return adjustToWidth(N, 0); }
  450. static ScaledNumber getInverse(uint64_t N) {
  451. return get(N).invert();
  452. }
  453. static ScaledNumber getFraction(DigitsType N, DigitsType D) {
  454. return getQuotient(N, D);
  455. }
  456. int16_t getScale() const { return Scale; }
  457. DigitsType getDigits() const { return Digits; }
  458. /// \brief Convert to the given integer type.
  459. ///
  460. /// Convert to \c IntT using simple saturating arithmetic, truncating if
  461. /// necessary.
  462. template <class IntT> IntT toInt() const;
  463. bool isZero() const { return !Digits; }
  464. bool isLargest() const { return *this == getLargest(); }
  465. bool isOne() const {
  466. if (Scale > 0 || Scale <= -Width)
  467. return false;
  468. return Digits == DigitsType(1) << -Scale;
  469. }
  470. /// \brief The log base 2, rounded.
  471. ///
  472. /// Get the lg of the scalar. lg 0 is defined to be INT32_MIN.
  473. int32_t lg() const { return ScaledNumbers::getLg(Digits, Scale); }
  474. /// \brief The log base 2, rounded towards INT32_MIN.
  475. ///
  476. /// Get the lg floor. lg 0 is defined to be INT32_MIN.
  477. int32_t lgFloor() const { return ScaledNumbers::getLgFloor(Digits, Scale); }
  478. /// \brief The log base 2, rounded towards INT32_MAX.
  479. ///
  480. /// Get the lg ceiling. lg 0 is defined to be INT32_MIN.
  481. int32_t lgCeiling() const {
  482. return ScaledNumbers::getLgCeiling(Digits, Scale);
  483. }
  484. bool operator==(const ScaledNumber &X) const { return compare(X) == 0; }
  485. bool operator<(const ScaledNumber &X) const { return compare(X) < 0; }
  486. bool operator!=(const ScaledNumber &X) const { return compare(X) != 0; }
  487. bool operator>(const ScaledNumber &X) const { return compare(X) > 0; }
  488. bool operator<=(const ScaledNumber &X) const { return compare(X) <= 0; }
  489. bool operator>=(const ScaledNumber &X) const { return compare(X) >= 0; }
  490. bool operator!() const { return isZero(); }
  491. /// \brief Convert to a decimal representation in a string.
  492. ///
  493. /// Convert to a string. Uses scientific notation for very large/small
  494. /// numbers. Scientific notation is used roughly for numbers outside of the
  495. /// range 2^-64 through 2^64.
  496. ///
  497. /// \c Precision indicates the number of decimal digits of precision to use;
  498. /// 0 requests the maximum available.
  499. ///
  500. /// As a special case to make debugging easier, if the number is small enough
  501. /// to convert without scientific notation and has more than \c Precision
  502. /// digits before the decimal place, it's printed accurately to the first
  503. /// digit past zero. E.g., assuming 10 digits of precision:
  504. ///
  505. /// 98765432198.7654... => 98765432198.8
  506. /// 8765432198.7654... => 8765432198.8
  507. /// 765432198.7654... => 765432198.8
  508. /// 65432198.7654... => 65432198.77
  509. /// 5432198.7654... => 5432198.765
  510. std::string toString(unsigned Precision = DefaultPrecision) {
  511. return ScaledNumberBase::toString(Digits, Scale, Width, Precision);
  512. }
  513. /// \brief Print a decimal representation.
  514. ///
  515. /// Print a string. See toString for documentation.
  516. raw_ostream &print(raw_ostream &OS,
  517. unsigned Precision = DefaultPrecision) const {
  518. return ScaledNumberBase::print(OS, Digits, Scale, Width, Precision);
  519. }
  520. void dump() const { return ScaledNumberBase::dump(Digits, Scale, Width); }
  521. ScaledNumber &operator+=(const ScaledNumber &X) {
  522. std::tie(Digits, Scale) =
  523. ScaledNumbers::getSum(Digits, Scale, X.Digits, X.Scale);
  524. // Check for exponent past MaxScale.
  525. if (Scale > ScaledNumbers::MaxScale)
  526. *this = getLargest();
  527. return *this;
  528. }
  529. ScaledNumber &operator-=(const ScaledNumber &X) {
  530. std::tie(Digits, Scale) =
  531. ScaledNumbers::getDifference(Digits, Scale, X.Digits, X.Scale);
  532. return *this;
  533. }
  534. ScaledNumber &operator*=(const ScaledNumber &X);
  535. ScaledNumber &operator/=(const ScaledNumber &X);
  536. ScaledNumber &operator<<=(int16_t Shift) {
  537. shiftLeft(Shift);
  538. return *this;
  539. }
  540. ScaledNumber &operator>>=(int16_t Shift) {
  541. shiftRight(Shift);
  542. return *this;
  543. }
  544. private:
  545. void shiftLeft(int32_t Shift);
  546. void shiftRight(int32_t Shift);
  547. /// \brief Adjust two floats to have matching exponents.
  548. ///
  549. /// Adjust \c this and \c X to have matching exponents. Returns the new \c X
  550. /// by value. Does nothing if \a isZero() for either.
  551. ///
  552. /// The value that compares smaller will lose precision, and possibly become
  553. /// \a isZero().
  554. ScaledNumber matchScales(ScaledNumber X) {
  555. ScaledNumbers::matchScales(Digits, Scale, X.Digits, X.Scale);
  556. return X;
  557. }
  558. public:
  559. /// \brief Scale a large number accurately.
  560. ///
  561. /// Scale N (multiply it by this). Uses full precision multiplication, even
  562. /// if Width is smaller than 64, so information is not lost.
  563. uint64_t scale(uint64_t N) const;
  564. uint64_t scaleByInverse(uint64_t N) const {
  565. // TODO: implement directly, rather than relying on inverse. Inverse is
  566. // expensive.
  567. return inverse().scale(N);
  568. }
  569. int64_t scale(int64_t N) const {
  570. std::pair<uint64_t, bool> Unsigned = splitSigned(N);
  571. return joinSigned(scale(Unsigned.first), Unsigned.second);
  572. }
  573. int64_t scaleByInverse(int64_t N) const {
  574. std::pair<uint64_t, bool> Unsigned = splitSigned(N);
  575. return joinSigned(scaleByInverse(Unsigned.first), Unsigned.second);
  576. }
  577. int compare(const ScaledNumber &X) const {
  578. return ScaledNumbers::compare(Digits, Scale, X.Digits, X.Scale);
  579. }
  580. int compareTo(uint64_t N) const {
  581. return ScaledNumbers::compare<uint64_t>(Digits, Scale, N, 0);
  582. }
  583. int compareTo(int64_t N) const { return N < 0 ? 1 : compareTo(uint64_t(N)); }
  584. ScaledNumber &invert() { return *this = ScaledNumber::get(1) / *this; }
  585. ScaledNumber inverse() const { return ScaledNumber(*this).invert(); }
  586. private:
  587. static ScaledNumber getProduct(DigitsType LHS, DigitsType RHS) {
  588. return ScaledNumbers::getProduct(LHS, RHS);
  589. }
  590. static ScaledNumber getQuotient(DigitsType Dividend, DigitsType Divisor) {
  591. return ScaledNumbers::getQuotient(Dividend, Divisor);
  592. }
  593. static int countLeadingZerosWidth(DigitsType Digits) {
  594. if (Width == 64)
  595. return countLeadingZeros64(Digits);
  596. if (Width == 32)
  597. return countLeadingZeros32(Digits);
  598. return countLeadingZeros32(Digits) + Width - 32;
  599. }
  600. /// \brief Adjust a number to width, rounding up if necessary.
  601. ///
  602. /// Should only be called for \c Shift close to zero.
  603. ///
  604. /// \pre Shift >= MinScale && Shift + 64 <= MaxScale.
  605. static ScaledNumber adjustToWidth(uint64_t N, int32_t Shift) {
  606. assert(Shift >= ScaledNumbers::MinScale && "Shift should be close to 0");
  607. assert(Shift <= ScaledNumbers::MaxScale - 64 &&
  608. "Shift should be close to 0");
  609. auto Adjusted = ScaledNumbers::getAdjusted<DigitsT>(N, Shift);
  610. return Adjusted;
  611. }
  612. static ScaledNumber getRounded(ScaledNumber P, bool Round) {
  613. // Saturate.
  614. if (P.isLargest())
  615. return P;
  616. return ScaledNumbers::getRounded(P.Digits, P.Scale, Round);
  617. }
  618. };
  619. #define SCALED_NUMBER_BOP(op, base) \
  620. template <class DigitsT> \
  621. ScaledNumber<DigitsT> operator op(const ScaledNumber<DigitsT> &L, \
  622. const ScaledNumber<DigitsT> &R) { \
  623. return ScaledNumber<DigitsT>(L) base R; \
  624. }
  625. SCALED_NUMBER_BOP(+, += )
  626. SCALED_NUMBER_BOP(-, -= )
  627. SCALED_NUMBER_BOP(*, *= )
  628. SCALED_NUMBER_BOP(/, /= )
  629. #undef SCALED_NUMBER_BOP
  630. template <class DigitsT>
  631. ScaledNumber<DigitsT> operator<<(const ScaledNumber<DigitsT> &L,
  632. int16_t Shift) {
  633. return ScaledNumber<DigitsT>(L) <<= Shift;
  634. }
  635. template <class DigitsT>
  636. ScaledNumber<DigitsT> operator>>(const ScaledNumber<DigitsT> &L,
  637. int16_t Shift) {
  638. return ScaledNumber<DigitsT>(L) >>= Shift;
  639. }
  640. template <class DigitsT>
  641. raw_ostream &operator<<(raw_ostream &OS, const ScaledNumber<DigitsT> &X) {
  642. return X.print(OS, 10);
  643. }
  644. #define SCALED_NUMBER_COMPARE_TO_TYPE(op, T1, T2) \
  645. template <class DigitsT> \
  646. bool operator op(const ScaledNumber<DigitsT> &L, T1 R) { \
  647. return L.compareTo(T2(R)) op 0; \
  648. } \
  649. template <class DigitsT> \
  650. bool operator op(T1 L, const ScaledNumber<DigitsT> &R) { \
  651. return 0 op R.compareTo(T2(L)); \
  652. }
  653. #define SCALED_NUMBER_COMPARE_TO(op) \
  654. SCALED_NUMBER_COMPARE_TO_TYPE(op, uint64_t, uint64_t) \
  655. SCALED_NUMBER_COMPARE_TO_TYPE(op, uint32_t, uint64_t) \
  656. SCALED_NUMBER_COMPARE_TO_TYPE(op, int64_t, int64_t) \
  657. SCALED_NUMBER_COMPARE_TO_TYPE(op, int32_t, int64_t)
  658. SCALED_NUMBER_COMPARE_TO(< )
  659. SCALED_NUMBER_COMPARE_TO(> )
  660. SCALED_NUMBER_COMPARE_TO(== )
  661. SCALED_NUMBER_COMPARE_TO(!= )
  662. SCALED_NUMBER_COMPARE_TO(<= )
  663. SCALED_NUMBER_COMPARE_TO(>= )
  664. #undef SCALED_NUMBER_COMPARE_TO
  665. #undef SCALED_NUMBER_COMPARE_TO_TYPE
  666. template <class DigitsT>
  667. uint64_t ScaledNumber<DigitsT>::scale(uint64_t N) const {
  668. if (Width == 64 || N <= DigitsLimits::max())
  669. return (get(N) * *this).template toInt<uint64_t>();
  670. // Defer to the 64-bit version.
  671. return ScaledNumber<uint64_t>(Digits, Scale).scale(N);
  672. }
  673. template <class DigitsT>
  674. template <class IntT>
  675. IntT ScaledNumber<DigitsT>::toInt() const {
  676. typedef std::numeric_limits<IntT> Limits;
  677. if (*this < 1)
  678. return 0;
  679. if (*this >= Limits::max())
  680. return Limits::max();
  681. IntT N = Digits;
  682. if (Scale > 0) {
  683. assert(size_t(Scale) < sizeof(IntT) * 8);
  684. return N << Scale;
  685. }
  686. if (Scale < 0) {
  687. assert(size_t(-Scale) < sizeof(IntT) * 8);
  688. return N >> -Scale;
  689. }
  690. return N;
  691. }
  692. template <class DigitsT>
  693. ScaledNumber<DigitsT> &ScaledNumber<DigitsT>::
  694. operator*=(const ScaledNumber &X) {
  695. if (isZero())
  696. return *this;
  697. if (X.isZero())
  698. return *this = X;
  699. // Save the exponents.
  700. int32_t Scales = int32_t(Scale) + int32_t(X.Scale);
  701. // Get the raw product.
  702. *this = getProduct(Digits, X.Digits);
  703. // Combine with exponents.
  704. return *this <<= Scales;
  705. }
  706. template <class DigitsT>
  707. ScaledNumber<DigitsT> &ScaledNumber<DigitsT>::
  708. operator/=(const ScaledNumber &X) {
  709. if (isZero())
  710. return *this;
  711. if (X.isZero())
  712. return *this = getLargest();
  713. // Save the exponents.
  714. int32_t Scales = int32_t(Scale) - int32_t(X.Scale);
  715. // Get the raw quotient.
  716. *this = getQuotient(Digits, X.Digits);
  717. // Combine with exponents.
  718. return *this <<= Scales;
  719. }
  720. template <class DigitsT> void ScaledNumber<DigitsT>::shiftLeft(int32_t Shift) {
  721. if (!Shift || isZero())
  722. return;
  723. assert(Shift != INT32_MIN);
  724. if (Shift < 0) {
  725. shiftRight(-Shift);
  726. return;
  727. }
  728. // Shift as much as we can in the exponent.
  729. int32_t ScaleShift = std::min(Shift, ScaledNumbers::MaxScale - Scale);
  730. Scale += ScaleShift;
  731. if (ScaleShift == Shift)
  732. return;
  733. // Check this late, since it's rare.
  734. if (isLargest())
  735. return;
  736. // Shift the digits themselves.
  737. Shift -= ScaleShift;
  738. if (Shift > countLeadingZerosWidth(Digits)) {
  739. // Saturate.
  740. *this = getLargest();
  741. return;
  742. }
  743. Digits <<= Shift;
  744. return;
  745. }
  746. template <class DigitsT> void ScaledNumber<DigitsT>::shiftRight(int32_t Shift) {
  747. if (!Shift || isZero())
  748. return;
  749. assert(Shift != INT32_MIN);
  750. if (Shift < 0) {
  751. shiftLeft(-Shift);
  752. return;
  753. }
  754. // Shift as much as we can in the exponent.
  755. int32_t ScaleShift = std::min(Shift, Scale - ScaledNumbers::MinScale);
  756. Scale -= ScaleShift;
  757. if (ScaleShift == Shift)
  758. return;
  759. // Shift the digits themselves.
  760. Shift -= ScaleShift;
  761. if (Shift >= Width) {
  762. // Saturate.
  763. *this = getZero();
  764. return;
  765. }
  766. Digits >>= Shift;
  767. return;
  768. }
  769. template <typename T> struct isPodLike;
  770. template <typename T> struct isPodLike<ScaledNumber<T>> {
  771. static const bool value = true;
  772. };
  773. } // end namespace llvm
  774. #endif