LLVM API Documentation

ScaledNumber.h
Go to the documentation of this file.
00001 //===- llvm/Support/ScaledNumber.h - Support for scaled numbers -*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains functions (and a class) useful for working with scaled
00011 // numbers -- in particular, pairs of integers where one represents digits and
00012 // another represents a scale.  The functions are helpers and live in the
00013 // namespace ScaledNumbers.  The class ScaledNumber is useful for modelling
00014 // certain cost metrics that need simple, integer-like semantics that are easy
00015 // to reason about.
00016 //
00017 // These might remind you of soft-floats.  If you want one of those, you're in
00018 // the wrong place.  Look at include/llvm/ADT/APFloat.h instead.
00019 //
00020 //===----------------------------------------------------------------------===//
00021 
00022 #ifndef LLVM_SUPPORT_SCALEDNUMBER_H
00023 #define LLVM_SUPPORT_SCALEDNUMBER_H
00024 
00025 #include "llvm/Support/MathExtras.h"
00026 
00027 #include <algorithm>
00028 #include <cstdint>
00029 #include <limits>
00030 #include <string>
00031 #include <tuple>
00032 #include <utility>
00033 
00034 namespace llvm {
00035 namespace ScaledNumbers {
00036 
00037 /// \brief Maximum scale; same as APFloat for easy debug printing.
00038 const int32_t MaxScale = 16383;
00039 
00040 /// \brief Maximum scale; same as APFloat for easy debug printing.
00041 const int32_t MinScale = -16382;
00042 
00043 /// \brief Get the width of a number.
00044 template <class DigitsT> inline int getWidth() { return sizeof(DigitsT) * 8; }
00045 
00046 /// \brief Conditionally round up a scaled number.
00047 ///
00048 /// Given \c Digits and \c Scale, round up iff \c ShouldRound is \c true.
00049 /// Always returns \c Scale unless there's an overflow, in which case it
00050 /// returns \c 1+Scale.
00051 ///
00052 /// \pre adding 1 to \c Scale will not overflow INT16_MAX.
00053 template <class DigitsT>
00054 inline std::pair<DigitsT, int16_t> getRounded(DigitsT Digits, int16_t Scale,
00055                                               bool ShouldRound) {
00056   static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
00057 
00058   if (ShouldRound)
00059     if (!++Digits)
00060       // Overflow.
00061       return std::make_pair(DigitsT(1) << (getWidth<DigitsT>() - 1), Scale + 1);
00062   return std::make_pair(Digits, Scale);
00063 }
00064 
00065 /// \brief Convenience helper for 32-bit rounding.
00066 inline std::pair<uint32_t, int16_t> getRounded32(uint32_t Digits, int16_t Scale,
00067                                                  bool ShouldRound) {
00068   return getRounded(Digits, Scale, ShouldRound);
00069 }
00070 
00071 /// \brief Convenience helper for 64-bit rounding.
00072 inline std::pair<uint64_t, int16_t> getRounded64(uint64_t Digits, int16_t Scale,
00073                                                  bool ShouldRound) {
00074   return getRounded(Digits, Scale, ShouldRound);
00075 }
00076 
00077 /// \brief Adjust a 64-bit scaled number down to the appropriate width.
00078 ///
00079 /// \pre Adding 64 to \c Scale will not overflow INT16_MAX.
00080 template <class DigitsT>
00081 inline std::pair<DigitsT, int16_t> getAdjusted(uint64_t Digits,
00082                                                int16_t Scale = 0) {
00083   static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
00084 
00085   const int Width = getWidth<DigitsT>();
00086   if (Width == 64 || Digits <= std::numeric_limits<DigitsT>::max())
00087     return std::make_pair(Digits, Scale);
00088 
00089   // Shift right and round.
00090   int Shift = 64 - Width - countLeadingZeros(Digits);
00091   return getRounded<DigitsT>(Digits >> Shift, Scale + Shift,
00092                              Digits & (UINT64_C(1) << (Shift - 1)));
00093 }
00094 
00095 /// \brief Convenience helper for adjusting to 32 bits.
00096 inline std::pair<uint32_t, int16_t> getAdjusted32(uint64_t Digits,
00097                                                   int16_t Scale = 0) {
00098   return getAdjusted<uint32_t>(Digits, Scale);
00099 }
00100 
00101 /// \brief Convenience helper for adjusting to 64 bits.
00102 inline std::pair<uint64_t, int16_t> getAdjusted64(uint64_t Digits,
00103                                                   int16_t Scale = 0) {
00104   return getAdjusted<uint64_t>(Digits, Scale);
00105 }
00106 
00107 /// \brief Multiply two 64-bit integers to create a 64-bit scaled number.
00108 ///
00109 /// Implemented with four 64-bit integer multiplies.
00110 std::pair<uint64_t, int16_t> multiply64(uint64_t LHS, uint64_t RHS);
00111 
00112 /// \brief Multiply two 32-bit integers to create a 32-bit scaled number.
00113 ///
00114 /// Implemented with one 64-bit integer multiply.
00115 template <class DigitsT>
00116 inline std::pair<DigitsT, int16_t> getProduct(DigitsT LHS, DigitsT RHS) {
00117   static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
00118 
00119   if (getWidth<DigitsT>() <= 32 || (LHS <= UINT32_MAX && RHS <= UINT32_MAX))
00120     return getAdjusted<DigitsT>(uint64_t(LHS) * RHS);
00121 
00122   return multiply64(LHS, RHS);
00123 }
00124 
00125 /// \brief Convenience helper for 32-bit product.
00126 inline std::pair<uint32_t, int16_t> getProduct32(uint32_t LHS, uint32_t RHS) {
00127   return getProduct(LHS, RHS);
00128 }
00129 
00130 /// \brief Convenience helper for 64-bit product.
00131 inline std::pair<uint64_t, int16_t> getProduct64(uint64_t LHS, uint64_t RHS) {
00132   return getProduct(LHS, RHS);
00133 }
00134 
00135 /// \brief Divide two 64-bit integers to create a 64-bit scaled number.
00136 ///
00137 /// Implemented with long division.
00138 ///
00139 /// \pre \c Dividend and \c Divisor are non-zero.
00140 std::pair<uint64_t, int16_t> divide64(uint64_t Dividend, uint64_t Divisor);
00141 
00142 /// \brief Divide two 32-bit integers to create a 32-bit scaled number.
00143 ///
00144 /// Implemented with one 64-bit integer divide/remainder pair.
00145 ///
00146 /// \pre \c Dividend and \c Divisor are non-zero.
00147 std::pair<uint32_t, int16_t> divide32(uint32_t Dividend, uint32_t Divisor);
00148 
00149 /// \brief Divide two 32-bit numbers to create a 32-bit scaled number.
00150 ///
00151 /// Implemented with one 64-bit integer divide/remainder pair.
00152 ///
00153 /// Returns \c (DigitsT_MAX, MaxScale) for divide-by-zero (0 for 0/0).
00154 template <class DigitsT>
00155 std::pair<DigitsT, int16_t> getQuotient(DigitsT Dividend, DigitsT Divisor) {
00156   static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
00157   static_assert(sizeof(DigitsT) == 4 || sizeof(DigitsT) == 8,
00158                 "expected 32-bit or 64-bit digits");
00159 
00160   // Check for zero.
00161   if (!Dividend)
00162     return std::make_pair(0, 0);
00163   if (!Divisor)
00164     return std::make_pair(std::numeric_limits<DigitsT>::max(), MaxScale);
00165 
00166   if (getWidth<DigitsT>() == 64)
00167     return divide64(Dividend, Divisor);
00168   return divide32(Dividend, Divisor);
00169 }
00170 
00171 /// \brief Convenience helper for 32-bit quotient.
00172 inline std::pair<uint32_t, int16_t> getQuotient32(uint32_t Dividend,
00173                                                   uint32_t Divisor) {
00174   return getQuotient(Dividend, Divisor);
00175 }
00176 
00177 /// \brief Convenience helper for 64-bit quotient.
00178 inline std::pair<uint64_t, int16_t> getQuotient64(uint64_t Dividend,
00179                                                   uint64_t Divisor) {
00180   return getQuotient(Dividend, Divisor);
00181 }
00182 
00183 /// \brief Implementation of getLg() and friends.
00184 ///
00185 /// Returns the rounded lg of \c Digits*2^Scale and an int specifying whether
00186 /// this was rounded up (1), down (-1), or exact (0).
00187 ///
00188 /// Returns \c INT32_MIN when \c Digits is zero.
00189 template <class DigitsT>
00190 inline std::pair<int32_t, int> getLgImpl(DigitsT Digits, int16_t Scale) {
00191   static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
00192 
00193   if (!Digits)
00194     return std::make_pair(INT32_MIN, 0);
00195 
00196   // Get the floor of the lg of Digits.
00197   int32_t LocalFloor = sizeof(Digits) * 8 - countLeadingZeros(Digits) - 1;
00198 
00199   // Get the actual floor.
00200   int32_t Floor = Scale + LocalFloor;
00201   if (Digits == UINT64_C(1) << LocalFloor)
00202     return std::make_pair(Floor, 0);
00203 
00204   // Round based on the next digit.
00205   assert(LocalFloor >= 1);
00206   bool Round = Digits & UINT64_C(1) << (LocalFloor - 1);
00207   return std::make_pair(Floor + Round, Round ? 1 : -1);
00208 }
00209 
00210 /// \brief Get the lg (rounded) of a scaled number.
00211 ///
00212 /// Get the lg of \c Digits*2^Scale.
00213 ///
00214 /// Returns \c INT32_MIN when \c Digits is zero.
00215 template <class DigitsT> int32_t getLg(DigitsT Digits, int16_t Scale) {
00216   return getLgImpl(Digits, Scale).first;
00217 }
00218 
00219 /// \brief Get the lg floor of a scaled number.
00220 ///
00221 /// Get the floor of the lg of \c Digits*2^Scale.
00222 ///
00223 /// Returns \c INT32_MIN when \c Digits is zero.
00224 template <class DigitsT> int32_t getLgFloor(DigitsT Digits, int16_t Scale) {
00225   auto Lg = getLgImpl(Digits, Scale);
00226   return Lg.first - (Lg.second > 0);
00227 }
00228 
00229 /// \brief Get the lg ceiling of a scaled number.
00230 ///
00231 /// Get the ceiling of the lg of \c Digits*2^Scale.
00232 ///
00233 /// Returns \c INT32_MIN when \c Digits is zero.
00234 template <class DigitsT> int32_t getLgCeiling(DigitsT Digits, int16_t Scale) {
00235   auto Lg = getLgImpl(Digits, Scale);
00236   return Lg.first + (Lg.second < 0);
00237 }
00238 
00239 /// \brief Implementation for comparing scaled numbers.
00240 ///
00241 /// Compare two 64-bit numbers with different scales.  Given that the scale of
00242 /// \c L is higher than that of \c R by \c ScaleDiff, compare them.  Return -1,
00243 /// 1, and 0 for less than, greater than, and equal, respectively.
00244 ///
00245 /// \pre 0 <= ScaleDiff < 64.
00246 int compareImpl(uint64_t L, uint64_t R, int ScaleDiff);
00247 
00248 /// \brief Compare two scaled numbers.
00249 ///
00250 /// Compare two scaled numbers.  Returns 0 for equal, -1 for less than, and 1
00251 /// for greater than.
00252 template <class DigitsT>
00253 int compare(DigitsT LDigits, int16_t LScale, DigitsT RDigits, int16_t RScale) {
00254   static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
00255 
00256   // Check for zero.
00257   if (!LDigits)
00258     return RDigits ? -1 : 0;
00259   if (!RDigits)
00260     return 1;
00261 
00262   // Check for the scale.  Use getLgFloor to be sure that the scale difference
00263   // is always lower than 64.
00264   int32_t lgL = getLgFloor(LDigits, LScale), lgR = getLgFloor(RDigits, RScale);
00265   if (lgL != lgR)
00266     return lgL < lgR ? -1 : 1;
00267 
00268   // Compare digits.
00269   if (LScale < RScale)
00270     return compareImpl(LDigits, RDigits, RScale - LScale);
00271 
00272   return -compareImpl(RDigits, LDigits, LScale - RScale);
00273 }
00274 
00275 /// \brief Match scales of two numbers.
00276 ///
00277 /// Given two scaled numbers, match up their scales.  Change the digits and
00278 /// scales in place.  Shift the digits as necessary to form equivalent numbers,
00279 /// losing precision only when necessary.
00280 ///
00281 /// If the output value of \c LDigits (\c RDigits) is \c 0, the output value of
00282 /// \c LScale (\c RScale) is unspecified.
00283 ///
00284 /// As a convenience, returns the matching scale.  If the output value of one
00285 /// number is zero, returns the scale of the other.  If both are zero, which
00286 /// scale is returned is unspecifed.
00287 template <class DigitsT>
00288 int16_t matchScales(DigitsT &LDigits, int16_t &LScale, DigitsT &RDigits,
00289                     int16_t &RScale) {
00290   static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
00291 
00292   if (LScale < RScale)
00293     // Swap arguments.
00294     return matchScales(RDigits, RScale, LDigits, LScale);
00295   if (!LDigits)
00296     return RScale;
00297   if (!RDigits || LScale == RScale)
00298     return LScale;
00299 
00300   // Now LScale > RScale.  Get the difference.
00301   int32_t ScaleDiff = int32_t(LScale) - RScale;
00302   if (ScaleDiff >= 2 * getWidth<DigitsT>()) {
00303     // Don't bother shifting.  RDigits will get zero-ed out anyway.
00304     RDigits = 0;
00305     return LScale;
00306   }
00307 
00308   // Shift LDigits left as much as possible, then shift RDigits right.
00309   int32_t ShiftL = std::min<int32_t>(countLeadingZeros(LDigits), ScaleDiff);
00310   assert(ShiftL < getWidth<DigitsT>() && "can't shift more than width");
00311 
00312   int32_t ShiftR = ScaleDiff - ShiftL;
00313   if (ShiftR >= getWidth<DigitsT>()) {
00314     // Don't bother shifting.  RDigits will get zero-ed out anyway.
00315     RDigits = 0;
00316     return LScale;
00317   }
00318 
00319   LDigits <<= ShiftL;
00320   RDigits >>= ShiftR;
00321 
00322   LScale -= ShiftL;
00323   RScale += ShiftR;
00324   assert(LScale == RScale && "scales should match");
00325   return LScale;
00326 }
00327 
00328 /// \brief Get the sum of two scaled numbers.
00329 ///
00330 /// Get the sum of two scaled numbers with as much precision as possible.
00331 ///
00332 /// \pre Adding 1 to \c LScale (or \c RScale) will not overflow INT16_MAX.
00333 template <class DigitsT>
00334 std::pair<DigitsT, int16_t> getSum(DigitsT LDigits, int16_t LScale,
00335                                    DigitsT RDigits, int16_t RScale) {
00336   static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
00337 
00338   // Check inputs up front.  This is only relevent if addition overflows, but
00339   // testing here should catch more bugs.
00340   assert(LScale < INT16_MAX && "scale too large");
00341   assert(RScale < INT16_MAX && "scale too large");
00342 
00343   // Normalize digits to match scales.
00344   int16_t Scale = matchScales(LDigits, LScale, RDigits, RScale);
00345 
00346   // Compute sum.
00347   DigitsT Sum = LDigits + RDigits;
00348   if (Sum >= RDigits)
00349     return std::make_pair(Sum, Scale);
00350 
00351   // Adjust sum after arithmetic overflow.
00352   DigitsT HighBit = DigitsT(1) << (getWidth<DigitsT>() - 1);
00353   return std::make_pair(HighBit | Sum >> 1, Scale + 1);
00354 }
00355 
00356 /// \brief Convenience helper for 32-bit sum.
00357 inline std::pair<uint32_t, int16_t> getSum32(uint32_t LDigits, int16_t LScale,
00358                                              uint32_t RDigits, int16_t RScale) {
00359   return getSum(LDigits, LScale, RDigits, RScale);
00360 }
00361 
00362 /// \brief Convenience helper for 64-bit sum.
00363 inline std::pair<uint64_t, int16_t> getSum64(uint64_t LDigits, int16_t LScale,
00364                                              uint64_t RDigits, int16_t RScale) {
00365   return getSum(LDigits, LScale, RDigits, RScale);
00366 }
00367 
00368 /// \brief Get the difference of two scaled numbers.
00369 ///
00370 /// Get LHS minus RHS with as much precision as possible.
00371 ///
00372 /// Returns \c (0, 0) if the RHS is larger than the LHS.
00373 template <class DigitsT>
00374 std::pair<DigitsT, int16_t> getDifference(DigitsT LDigits, int16_t LScale,
00375                                           DigitsT RDigits, int16_t RScale) {
00376   static_assert(!std::numeric_limits<DigitsT>::is_signed, "expected unsigned");
00377 
00378   // Normalize digits to match scales.
00379   const DigitsT SavedRDigits = RDigits;
00380   const int16_t SavedRScale = RScale;
00381   matchScales(LDigits, LScale, RDigits, RScale);
00382 
00383   // Compute difference.
00384   if (LDigits <= RDigits)
00385     return std::make_pair(0, 0);
00386   if (RDigits || !SavedRDigits)
00387     return std::make_pair(LDigits - RDigits, LScale);
00388 
00389   // Check if RDigits just barely lost its last bit.  E.g., for 32-bit:
00390   //
00391   //   1*2^32 - 1*2^0 == 0xffffffff != 1*2^32
00392   const auto RLgFloor = getLgFloor(SavedRDigits, SavedRScale);
00393   if (!compare(LDigits, LScale, DigitsT(1), RLgFloor + getWidth<DigitsT>()))
00394     return std::make_pair(std::numeric_limits<DigitsT>::max(), RLgFloor);
00395 
00396   return std::make_pair(LDigits, LScale);
00397 }
00398 
00399 /// \brief Convenience helper for 32-bit difference.
00400 inline std::pair<uint32_t, int16_t> getDifference32(uint32_t LDigits,
00401                                                     int16_t LScale,
00402                                                     uint32_t RDigits,
00403                                                     int16_t RScale) {
00404   return getDifference(LDigits, LScale, RDigits, RScale);
00405 }
00406 
00407 /// \brief Convenience helper for 64-bit difference.
00408 inline std::pair<uint64_t, int16_t> getDifference64(uint64_t LDigits,
00409                                                     int16_t LScale,
00410                                                     uint64_t RDigits,
00411                                                     int16_t RScale) {
00412   return getDifference(LDigits, LScale, RDigits, RScale);
00413 }
00414 
00415 } // end namespace ScaledNumbers
00416 } // end namespace llvm
00417 
00418 namespace llvm {
00419 
00420 class raw_ostream;
00421 class ScaledNumberBase {
00422 public:
00423   static const int DefaultPrecision = 10;
00424 
00425   static void dump(uint64_t D, int16_t E, int Width);
00426   static raw_ostream &print(raw_ostream &OS, uint64_t D, int16_t E, int Width,
00427                             unsigned Precision);
00428   static std::string toString(uint64_t D, int16_t E, int Width,
00429                               unsigned Precision);
00430   static int countLeadingZeros32(uint32_t N) { return countLeadingZeros(N); }
00431   static int countLeadingZeros64(uint64_t N) { return countLeadingZeros(N); }
00432   static uint64_t getHalf(uint64_t N) { return (N >> 1) + (N & 1); }
00433 
00434   static std::pair<uint64_t, bool> splitSigned(int64_t N) {
00435     if (N >= 0)
00436       return std::make_pair(N, false);
00437     uint64_t Unsigned = N == INT64_MIN ? UINT64_C(1) << 63 : uint64_t(-N);
00438     return std::make_pair(Unsigned, true);
00439   }
00440   static int64_t joinSigned(uint64_t U, bool IsNeg) {
00441     if (U > uint64_t(INT64_MAX))
00442       return IsNeg ? INT64_MIN : INT64_MAX;
00443     return IsNeg ? -int64_t(U) : int64_t(U);
00444   }
00445 };
00446 
00447 /// \brief Simple representation of a scaled number.
00448 ///
00449 /// ScaledNumber is a number represented by digits and a scale.  It uses simple
00450 /// saturation arithmetic and every operation is well-defined for every value.
00451 /// It's somewhat similar in behaviour to a soft-float, but is *not* a
00452 /// replacement for one.  If you're doing numerics, look at \a APFloat instead.
00453 /// Nevertheless, we've found these semantics useful for modelling certain cost
00454 /// metrics.
00455 ///
00456 /// The number is split into a signed scale and unsigned digits.  The number
00457 /// represented is \c getDigits()*2^getScale().  In this way, the digits are
00458 /// much like the mantissa in the x87 long double, but there is no canonical
00459 /// form so the same number can be represented by many bit representations.
00460 ///
00461 /// ScaledNumber is templated on the underlying integer type for digits, which
00462 /// is expected to be unsigned.
00463 ///
00464 /// Unlike APFloat, ScaledNumber does not model architecture floating point
00465 /// behaviour -- while this might make it a little faster and easier to reason
00466 /// about, it certainly makes it more dangerous for general numerics.
00467 ///
00468 /// ScaledNumber is totally ordered.  However, there is no canonical form, so
00469 /// there are multiple representations of most scalars.  E.g.:
00470 ///
00471 ///     ScaledNumber(8u, 0) == ScaledNumber(4u, 1)
00472 ///     ScaledNumber(4u, 1) == ScaledNumber(2u, 2)
00473 ///     ScaledNumber(2u, 2) == ScaledNumber(1u, 3)
00474 ///
00475 /// ScaledNumber implements most arithmetic operations.  Precision is kept
00476 /// where possible.  Uses simple saturation arithmetic, so that operations
00477 /// saturate to 0.0 or getLargest() rather than under or overflowing.  It has
00478 /// some extra arithmetic for unit inversion.  0.0/0.0 is defined to be 0.0.
00479 /// Any other division by 0.0 is defined to be getLargest().
00480 ///
00481 /// As a convenience for modifying the exponent, left and right shifting are
00482 /// both implemented, and both interpret negative shifts as positive shifts in
00483 /// the opposite direction.
00484 ///
00485 /// Scales are limited to the range accepted by x87 long double.  This makes
00486 /// it trivial to add functionality to convert to APFloat (this is already
00487 /// relied on for the implementation of printing).
00488 ///
00489 /// Possible (and conflicting) future directions:
00490 ///
00491 ///  1. Turn this into a wrapper around \a APFloat.
00492 ///  2. Share the algorithm implementations with \a APFloat.
00493 ///  3. Allow \a ScaledNumber to represent a signed number.
00494 template <class DigitsT> class ScaledNumber : ScaledNumberBase {
00495 public:
00496   static_assert(!std::numeric_limits<DigitsT>::is_signed,
00497                 "only unsigned floats supported");
00498 
00499   typedef DigitsT DigitsType;
00500 
00501 private:
00502   typedef std::numeric_limits<DigitsType> DigitsLimits;
00503 
00504   static const int Width = sizeof(DigitsType) * 8;
00505   static_assert(Width <= 64, "invalid integer width for digits");
00506 
00507 private:
00508   DigitsType Digits;
00509   int16_t Scale;
00510 
00511 public:
00512   ScaledNumber() : Digits(0), Scale(0) {}
00513 
00514   ScaledNumber(DigitsType Digits, int16_t Scale)
00515       : Digits(Digits), Scale(Scale) {}
00516 
00517 private:
00518   ScaledNumber(const std::pair<uint64_t, int16_t> &X)
00519       : Digits(X.first), Scale(X.second) {}
00520 
00521 public:
00522   static ScaledNumber getZero() { return ScaledNumber(0, 0); }
00523   static ScaledNumber getOne() { return ScaledNumber(1, 0); }
00524   static ScaledNumber getLargest() {
00525     return ScaledNumber(DigitsLimits::max(), ScaledNumbers::MaxScale);
00526   }
00527   static ScaledNumber get(uint64_t N) { return adjustToWidth(N, 0); }
00528   static ScaledNumber getInverse(uint64_t N) {
00529     return get(N).invert();
00530   }
00531   static ScaledNumber getFraction(DigitsType N, DigitsType D) {
00532     return getQuotient(N, D);
00533   }
00534 
00535   int16_t getScale() const { return Scale; }
00536   DigitsType getDigits() const { return Digits; }
00537 
00538   /// \brief Convert to the given integer type.
00539   ///
00540   /// Convert to \c IntT using simple saturating arithmetic, truncating if
00541   /// necessary.
00542   template <class IntT> IntT toInt() const;
00543 
00544   bool isZero() const { return !Digits; }
00545   bool isLargest() const { return *this == getLargest(); }
00546   bool isOne() const {
00547     if (Scale > 0 || Scale <= -Width)
00548       return false;
00549     return Digits == DigitsType(1) << -Scale;
00550   }
00551 
00552   /// \brief The log base 2, rounded.
00553   ///
00554   /// Get the lg of the scalar.  lg 0 is defined to be INT32_MIN.
00555   int32_t lg() const { return ScaledNumbers::getLg(Digits, Scale); }
00556 
00557   /// \brief The log base 2, rounded towards INT32_MIN.
00558   ///
00559   /// Get the lg floor.  lg 0 is defined to be INT32_MIN.
00560   int32_t lgFloor() const { return ScaledNumbers::getLgFloor(Digits, Scale); }
00561 
00562   /// \brief The log base 2, rounded towards INT32_MAX.
00563   ///
00564   /// Get the lg ceiling.  lg 0 is defined to be INT32_MIN.
00565   int32_t lgCeiling() const {
00566     return ScaledNumbers::getLgCeiling(Digits, Scale);
00567   }
00568 
00569   bool operator==(const ScaledNumber &X) const { return compare(X) == 0; }
00570   bool operator<(const ScaledNumber &X) const { return compare(X) < 0; }
00571   bool operator!=(const ScaledNumber &X) const { return compare(X) != 0; }
00572   bool operator>(const ScaledNumber &X) const { return compare(X) > 0; }
00573   bool operator<=(const ScaledNumber &X) const { return compare(X) <= 0; }
00574   bool operator>=(const ScaledNumber &X) const { return compare(X) >= 0; }
00575 
00576   bool operator!() const { return isZero(); }
00577 
00578   /// \brief Convert to a decimal representation in a string.
00579   ///
00580   /// Convert to a string.  Uses scientific notation for very large/small
00581   /// numbers.  Scientific notation is used roughly for numbers outside of the
00582   /// range 2^-64 through 2^64.
00583   ///
00584   /// \c Precision indicates the number of decimal digits of precision to use;
00585   /// 0 requests the maximum available.
00586   ///
00587   /// As a special case to make debugging easier, if the number is small enough
00588   /// to convert without scientific notation and has more than \c Precision
00589   /// digits before the decimal place, it's printed accurately to the first
00590   /// digit past zero.  E.g., assuming 10 digits of precision:
00591   ///
00592   ///     98765432198.7654... => 98765432198.8
00593   ///      8765432198.7654... =>  8765432198.8
00594   ///       765432198.7654... =>   765432198.8
00595   ///        65432198.7654... =>    65432198.77
00596   ///         5432198.7654... =>     5432198.765
00597   std::string toString(unsigned Precision = DefaultPrecision) {
00598     return ScaledNumberBase::toString(Digits, Scale, Width, Precision);
00599   }
00600 
00601   /// \brief Print a decimal representation.
00602   ///
00603   /// Print a string.  See toString for documentation.
00604   raw_ostream &print(raw_ostream &OS,
00605                      unsigned Precision = DefaultPrecision) const {
00606     return ScaledNumberBase::print(OS, Digits, Scale, Width, Precision);
00607   }
00608   void dump() const { return ScaledNumberBase::dump(Digits, Scale, Width); }
00609 
00610   ScaledNumber &operator+=(const ScaledNumber &X) {
00611     std::tie(Digits, Scale) =
00612         ScaledNumbers::getSum(Digits, Scale, X.Digits, X.Scale);
00613     // Check for exponent past MaxScale.
00614     if (Scale > ScaledNumbers::MaxScale)
00615       *this = getLargest();
00616     return *this;
00617   }
00618   ScaledNumber &operator-=(const ScaledNumber &X) {
00619     std::tie(Digits, Scale) =
00620         ScaledNumbers::getDifference(Digits, Scale, X.Digits, X.Scale);
00621     return *this;
00622   }
00623   ScaledNumber &operator*=(const ScaledNumber &X);
00624   ScaledNumber &operator/=(const ScaledNumber &X);
00625   ScaledNumber &operator<<=(int16_t Shift) {
00626     shiftLeft(Shift);
00627     return *this;
00628   }
00629   ScaledNumber &operator>>=(int16_t Shift) {
00630     shiftRight(Shift);
00631     return *this;
00632   }
00633 
00634 private:
00635   void shiftLeft(int32_t Shift);
00636   void shiftRight(int32_t Shift);
00637 
00638   /// \brief Adjust two floats to have matching exponents.
00639   ///
00640   /// Adjust \c this and \c X to have matching exponents.  Returns the new \c X
00641   /// by value.  Does nothing if \a isZero() for either.
00642   ///
00643   /// The value that compares smaller will lose precision, and possibly become
00644   /// \a isZero().
00645   ScaledNumber matchScales(ScaledNumber X) {
00646     ScaledNumbers::matchScales(Digits, Scale, X.Digits, X.Scale);
00647     return X;
00648   }
00649 
00650 public:
00651   /// \brief Scale a large number accurately.
00652   ///
00653   /// Scale N (multiply it by this).  Uses full precision multiplication, even
00654   /// if Width is smaller than 64, so information is not lost.
00655   uint64_t scale(uint64_t N) const;
00656   uint64_t scaleByInverse(uint64_t N) const {
00657     // TODO: implement directly, rather than relying on inverse.  Inverse is
00658     // expensive.
00659     return inverse().scale(N);
00660   }
00661   int64_t scale(int64_t N) const {
00662     std::pair<uint64_t, bool> Unsigned = splitSigned(N);
00663     return joinSigned(scale(Unsigned.first), Unsigned.second);
00664   }
00665   int64_t scaleByInverse(int64_t N) const {
00666     std::pair<uint64_t, bool> Unsigned = splitSigned(N);
00667     return joinSigned(scaleByInverse(Unsigned.first), Unsigned.second);
00668   }
00669 
00670   int compare(const ScaledNumber &X) const {
00671     return ScaledNumbers::compare(Digits, Scale, X.Digits, X.Scale);
00672   }
00673   int compareTo(uint64_t N) const {
00674     ScaledNumber Scaled = get(N);
00675     int Compare = compare(Scaled);
00676     if (Width == 64 || Compare != 0)
00677       return Compare;
00678 
00679     // Check for precision loss.  We know *this == RoundTrip.
00680     uint64_t RoundTrip = Scaled.template toInt<uint64_t>();
00681     return N == RoundTrip ? 0 : RoundTrip < N ? -1 : 1;
00682   }
00683   int compareTo(int64_t N) const { return N < 0 ? 1 : compareTo(uint64_t(N)); }
00684 
00685   ScaledNumber &invert() { return *this = ScaledNumber::get(1) / *this; }
00686   ScaledNumber inverse() const { return ScaledNumber(*this).invert(); }
00687 
00688 private:
00689   static ScaledNumber getProduct(DigitsType LHS, DigitsType RHS) {
00690     return ScaledNumbers::getProduct(LHS, RHS);
00691   }
00692   static ScaledNumber getQuotient(DigitsType Dividend, DigitsType Divisor) {
00693     return ScaledNumbers::getQuotient(Dividend, Divisor);
00694   }
00695 
00696   static int countLeadingZerosWidth(DigitsType Digits) {
00697     if (Width == 64)
00698       return countLeadingZeros64(Digits);
00699     if (Width == 32)
00700       return countLeadingZeros32(Digits);
00701     return countLeadingZeros32(Digits) + Width - 32;
00702   }
00703 
00704   /// \brief Adjust a number to width, rounding up if necessary.
00705   ///
00706   /// Should only be called for \c Shift close to zero.
00707   ///
00708   /// \pre Shift >= MinScale && Shift + 64 <= MaxScale.
00709   static ScaledNumber adjustToWidth(uint64_t N, int32_t Shift) {
00710     assert(Shift >= ScaledNumbers::MinScale && "Shift should be close to 0");
00711     assert(Shift <= ScaledNumbers::MaxScale - 64 &&
00712            "Shift should be close to 0");
00713     auto Adjusted = ScaledNumbers::getAdjusted<DigitsT>(N, Shift);
00714     return Adjusted;
00715   }
00716 
00717   static ScaledNumber getRounded(ScaledNumber P, bool Round) {
00718     // Saturate.
00719     if (P.isLargest())
00720       return P;
00721 
00722     return ScaledNumbers::getRounded(P.Digits, P.Scale, Round);
00723   }
00724 };
00725 
00726 #define SCALED_NUMBER_BOP(op, base)                                            \
00727   template <class DigitsT>                                                     \
00728   ScaledNumber<DigitsT> operator op(const ScaledNumber<DigitsT> &L,            \
00729                                     const ScaledNumber<DigitsT> &R) {          \
00730     return ScaledNumber<DigitsT>(L) base R;                                    \
00731   }
00732 SCALED_NUMBER_BOP(+, += )
00733 SCALED_NUMBER_BOP(-, -= )
00734 SCALED_NUMBER_BOP(*, *= )
00735 SCALED_NUMBER_BOP(/, /= )
00736 SCALED_NUMBER_BOP(<<, <<= )
00737 SCALED_NUMBER_BOP(>>, >>= )
00738 #undef SCALED_NUMBER_BOP
00739 
00740 template <class DigitsT>
00741 raw_ostream &operator<<(raw_ostream &OS, const ScaledNumber<DigitsT> &X) {
00742   return X.print(OS, 10);
00743 }
00744 
00745 #define SCALED_NUMBER_COMPARE_TO_TYPE(op, T1, T2)                              \
00746   template <class DigitsT>                                                     \
00747   bool operator op(const ScaledNumber<DigitsT> &L, T1 R) {                     \
00748     return L.compareTo(T2(R)) op 0;                                            \
00749   }                                                                            \
00750   template <class DigitsT>                                                     \
00751   bool operator op(T1 L, const ScaledNumber<DigitsT> &R) {                     \
00752     return 0 op R.compareTo(T2(L));                                            \
00753   }
00754 #define SCALED_NUMBER_COMPARE_TO(op)                                           \
00755   SCALED_NUMBER_COMPARE_TO_TYPE(op, uint64_t, uint64_t)                        \
00756   SCALED_NUMBER_COMPARE_TO_TYPE(op, uint32_t, uint64_t)                        \
00757   SCALED_NUMBER_COMPARE_TO_TYPE(op, int64_t, int64_t)                          \
00758   SCALED_NUMBER_COMPARE_TO_TYPE(op, int32_t, int64_t)
00759 SCALED_NUMBER_COMPARE_TO(< )
00760 SCALED_NUMBER_COMPARE_TO(> )
00761 SCALED_NUMBER_COMPARE_TO(== )
00762 SCALED_NUMBER_COMPARE_TO(!= )
00763 SCALED_NUMBER_COMPARE_TO(<= )
00764 SCALED_NUMBER_COMPARE_TO(>= )
00765 #undef SCALED_NUMBER_COMPARE_TO
00766 #undef SCALED_NUMBER_COMPARE_TO_TYPE
00767 
00768 template <class DigitsT>
00769 uint64_t ScaledNumber<DigitsT>::scale(uint64_t N) const {
00770   if (Width == 64 || N <= DigitsLimits::max())
00771     return (get(N) * *this).template toInt<uint64_t>();
00772 
00773   // Defer to the 64-bit version.
00774   return ScaledNumber<uint64_t>(Digits, Scale).scale(N);
00775 }
00776 
00777 template <class DigitsT>
00778 template <class IntT>
00779 IntT ScaledNumber<DigitsT>::toInt() const {
00780   typedef std::numeric_limits<IntT> Limits;
00781   if (*this < 1)
00782     return 0;
00783   if (*this >= Limits::max())
00784     return Limits::max();
00785 
00786   IntT N = Digits;
00787   if (Scale > 0) {
00788     assert(size_t(Scale) < sizeof(IntT) * 8);
00789     return N << Scale;
00790   }
00791   if (Scale < 0) {
00792     assert(size_t(-Scale) < sizeof(IntT) * 8);
00793     return N >> -Scale;
00794   }
00795   return N;
00796 }
00797 
00798 template <class DigitsT>
00799 ScaledNumber<DigitsT> &ScaledNumber<DigitsT>::
00800 operator*=(const ScaledNumber &X) {
00801   if (isZero())
00802     return *this;
00803   if (X.isZero())
00804     return *this = X;
00805 
00806   // Save the exponents.
00807   int32_t Scales = int32_t(Scale) + int32_t(X.Scale);
00808 
00809   // Get the raw product.
00810   *this = getProduct(Digits, X.Digits);
00811 
00812   // Combine with exponents.
00813   return *this <<= Scales;
00814 }
00815 template <class DigitsT>
00816 ScaledNumber<DigitsT> &ScaledNumber<DigitsT>::
00817 operator/=(const ScaledNumber &X) {
00818   if (isZero())
00819     return *this;
00820   if (X.isZero())
00821     return *this = getLargest();
00822 
00823   // Save the exponents.
00824   int32_t Scales = int32_t(Scale) - int32_t(X.Scale);
00825 
00826   // Get the raw quotient.
00827   *this = getQuotient(Digits, X.Digits);
00828 
00829   // Combine with exponents.
00830   return *this <<= Scales;
00831 }
00832 template <class DigitsT> void ScaledNumber<DigitsT>::shiftLeft(int32_t Shift) {
00833   if (!Shift || isZero())
00834     return;
00835   assert(Shift != INT32_MIN);
00836   if (Shift < 0) {
00837     shiftRight(-Shift);
00838     return;
00839   }
00840 
00841   // Shift as much as we can in the exponent.
00842   int32_t ScaleShift = std::min(Shift, ScaledNumbers::MaxScale - Scale);
00843   Scale += ScaleShift;
00844   if (ScaleShift == Shift)
00845     return;
00846 
00847   // Check this late, since it's rare.
00848   if (isLargest())
00849     return;
00850 
00851   // Shift the digits themselves.
00852   Shift -= ScaleShift;
00853   if (Shift > countLeadingZerosWidth(Digits)) {
00854     // Saturate.
00855     *this = getLargest();
00856     return;
00857   }
00858 
00859   Digits <<= Shift;
00860   return;
00861 }
00862 
00863 template <class DigitsT> void ScaledNumber<DigitsT>::shiftRight(int32_t Shift) {
00864   if (!Shift || isZero())
00865     return;
00866   assert(Shift != INT32_MIN);
00867   if (Shift < 0) {
00868     shiftLeft(-Shift);
00869     return;
00870   }
00871 
00872   // Shift as much as we can in the exponent.
00873   int32_t ScaleShift = std::min(Shift, Scale - ScaledNumbers::MinScale);
00874   Scale -= ScaleShift;
00875   if (ScaleShift == Shift)
00876     return;
00877 
00878   // Shift the digits themselves.
00879   Shift -= ScaleShift;
00880   if (Shift >= Width) {
00881     // Saturate.
00882     *this = getZero();
00883     return;
00884   }
00885 
00886   Digits >>= Shift;
00887   return;
00888 }
00889 
00890 template <typename T> struct isPodLike;
00891 template <typename T> struct isPodLike<ScaledNumber<T>> {
00892   static const bool value = true;
00893 };
00894 
00895 } // end namespace llvm
00896 
00897 #endif