1 //===- llvm/ADT/APFloat.h - Arbitrary Precision Floating Point ---*- 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 /// \file 11 /// \brief 12 /// This file declares a class to represent arbitrary precision floating point 13 /// values and provide a variety of arithmetic operations on them. 14 /// 15 //===----------------------------------------------------------------------===// 16 17 #ifndef LLVM_ADT_APFLOAT_H 18 #define LLVM_ADT_APFLOAT_H 19 20 #include "llvm/ADT/APInt.h" 21 #include "llvm/ADT/ArrayRef.h" 22 #include "llvm/Support/ErrorHandling.h" 23 #include <memory> 24 25 #define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \ 26 do { \ 27 if (usesLayout<IEEEFloat>(getSemantics())) \ 28 return U.IEEE.METHOD_CALL; \ 29 if (usesLayout<DoubleAPFloat>(getSemantics())) \ 30 return U.Double.METHOD_CALL; \ 31 llvm_unreachable("Unexpected semantics"); \ 32 } while (false) 33 34 namespace llvm { 35 36 struct fltSemantics; 37 class APSInt; 38 class StringRef; 39 class APFloat; 40 class raw_ostream; 41 42 template <typename T> class SmallVectorImpl; 43 44 /// Enum that represents what fraction of the LSB truncated bits of an fp number 45 /// represent. 46 /// 47 /// This essentially combines the roles of guard and sticky bits. 48 enum lostFraction { // Example of truncated bits: 49 lfExactlyZero, // 000000 50 lfLessThanHalf, // 0xxxxx x's not all zero 51 lfExactlyHalf, // 100000 52 lfMoreThanHalf // 1xxxxx x's not all zero 53 }; 54 55 /// A self-contained host- and target-independent arbitrary-precision 56 /// floating-point software implementation. 57 /// 58 /// APFloat uses bignum integer arithmetic as provided by static functions in 59 /// the APInt class. The library will work with bignum integers whose parts are 60 /// any unsigned type at least 16 bits wide, but 64 bits is recommended. 61 /// 62 /// Written for clarity rather than speed, in particular with a view to use in 63 /// the front-end of a cross compiler so that target arithmetic can be correctly 64 /// performed on the host. Performance should nonetheless be reasonable, 65 /// particularly for its intended use. It may be useful as a base 66 /// implementation for a run-time library during development of a faster 67 /// target-specific one. 68 /// 69 /// All 5 rounding modes in the IEEE-754R draft are handled correctly for all 70 /// implemented operations. Currently implemented operations are add, subtract, 71 /// multiply, divide, fused-multiply-add, conversion-to-float, 72 /// conversion-to-integer and conversion-from-integer. New rounding modes 73 /// (e.g. away from zero) can be added with three or four lines of code. 74 /// 75 /// Four formats are built-in: IEEE single precision, double precision, 76 /// quadruple precision, and x87 80-bit extended double (when operating with 77 /// full extended precision). Adding a new format that obeys IEEE semantics 78 /// only requires adding two lines of code: a declaration and definition of the 79 /// format. 80 /// 81 /// All operations return the status of that operation as an exception bit-mask, 82 /// so multiple operations can be done consecutively with their results or-ed 83 /// together. The returned status can be useful for compiler diagnostics; e.g., 84 /// inexact, underflow and overflow can be easily diagnosed on constant folding, 85 /// and compiler optimizers can determine what exceptions would be raised by 86 /// folding operations and optimize, or perhaps not optimize, accordingly. 87 /// 88 /// At present, underflow tininess is detected after rounding; it should be 89 /// straight forward to add support for the before-rounding case too. 90 /// 91 /// The library reads hexadecimal floating point numbers as per C99, and 92 /// correctly rounds if necessary according to the specified rounding mode. 93 /// Syntax is required to have been validated by the caller. It also converts 94 /// floating point numbers to hexadecimal text as per the C99 %a and %A 95 /// conversions. The output precision (or alternatively the natural minimal 96 /// precision) can be specified; if the requested precision is less than the 97 /// natural precision the output is correctly rounded for the specified rounding 98 /// mode. 99 /// 100 /// It also reads decimal floating point numbers and correctly rounds according 101 /// to the specified rounding mode. 102 /// 103 /// Conversion to decimal text is not currently implemented. 104 /// 105 /// Non-zero finite numbers are represented internally as a sign bit, a 16-bit 106 /// signed exponent, and the significand as an array of integer parts. After 107 /// normalization of a number of precision P the exponent is within the range of 108 /// the format, and if the number is not denormal the P-th bit of the 109 /// significand is set as an explicit integer bit. For denormals the most 110 /// significant bit is shifted right so that the exponent is maintained at the 111 /// format's minimum, so that the smallest denormal has just the least 112 /// significant bit of the significand set. The sign of zeroes and infinities 113 /// is significant; the exponent and significand of such numbers is not stored, 114 /// but has a known implicit (deterministic) value: 0 for the significands, 0 115 /// for zero exponent, all 1 bits for infinity exponent. For NaNs the sign and 116 /// significand are deterministic, although not really meaningful, and preserved 117 /// in non-conversion operations. The exponent is implicitly all 1 bits. 118 /// 119 /// APFloat does not provide any exception handling beyond default exception 120 /// handling. We represent Signaling NaNs via IEEE-754R 2008 6.2.1 should clause 121 /// by encoding Signaling NaNs with the first bit of its trailing significand as 122 /// 0. 123 /// 124 /// TODO 125 /// ==== 126 /// 127 /// Some features that may or may not be worth adding: 128 /// 129 /// Binary to decimal conversion (hard). 130 /// 131 /// Optional ability to detect underflow tininess before rounding. 132 /// 133 /// New formats: x87 in single and double precision mode (IEEE apart from 134 /// extended exponent range) (hard). 135 /// 136 /// New operations: sqrt, IEEE remainder, C90 fmod, nexttoward. 137 /// 138 139 // This is the common type definitions shared by APFloat and its internal 140 // implementation classes. This struct should not define any non-static data 141 // members. 142 struct APFloatBase { 143 // TODO remove this and use APInt typedef directly. 144 typedef APInt::WordType integerPart; 145 146 /// A signed type to represent a floating point numbers unbiased exponent. 147 typedef signed short ExponentType; 148 149 /// \name Floating Point Semantics. 150 /// @{ 151 152 static const fltSemantics &IEEEhalf() LLVM_READNONE; 153 static const fltSemantics &IEEEsingle() LLVM_READNONE; 154 static const fltSemantics &IEEEdouble() LLVM_READNONE; 155 static const fltSemantics &IEEEquad() LLVM_READNONE; 156 static const fltSemantics &PPCDoubleDouble() LLVM_READNONE; 157 static const fltSemantics &x87DoubleExtended() LLVM_READNONE; 158 159 /// A Pseudo fltsemantic used to construct APFloats that cannot conflict with 160 /// anything real. 161 static const fltSemantics &Bogus() LLVM_READNONE; 162 163 /// @} 164 165 /// IEEE-754R 5.11: Floating Point Comparison Relations. 166 enum cmpResult { 167 cmpLessThan, 168 cmpEqual, 169 cmpGreaterThan, 170 cmpUnordered 171 }; 172 173 /// IEEE-754R 4.3: Rounding-direction attributes. 174 enum roundingMode { 175 rmNearestTiesToEven, 176 rmTowardPositive, 177 rmTowardNegative, 178 rmTowardZero, 179 rmNearestTiesToAway 180 }; 181 182 /// IEEE-754R 7: Default exception handling. 183 /// 184 /// opUnderflow or opOverflow are always returned or-ed with opInexact. 185 enum opStatus { 186 opOK = 0x00, 187 opInvalidOp = 0x01, 188 opDivByZero = 0x02, 189 opOverflow = 0x04, 190 opUnderflow = 0x08, 191 opInexact = 0x10 192 }; 193 194 /// Category of internally-represented number. 195 enum fltCategory { 196 fcInfinity, 197 fcNaN, 198 fcNormal, 199 fcZero 200 }; 201 202 /// Convenience enum used to construct an uninitialized APFloat. 203 enum uninitializedTag { 204 uninitialized 205 }; 206 207 /// Enumeration of \c ilogb error results. 208 enum IlogbErrorKinds { 209 IEK_Zero = INT_MIN + 1, 210 IEK_NaN = INT_MIN, 211 IEK_Inf = INT_MAX 212 }; 213 214 static unsigned int semanticsPrecision(const fltSemantics &); 215 static ExponentType semanticsMinExponent(const fltSemantics &); 216 static ExponentType semanticsMaxExponent(const fltSemantics &); 217 static unsigned int semanticsSizeInBits(const fltSemantics &); 218 219 /// Returns the size of the floating point number (in bits) in the given 220 /// semantics. 221 static unsigned getSizeInBits(const fltSemantics &Sem); 222 }; 223 224 namespace detail { 225 226 class IEEEFloat final : public APFloatBase { 227 public: 228 /// \name Constructors 229 /// @{ 230 231 IEEEFloat(const fltSemantics &); // Default construct to 0.0 232 IEEEFloat(const fltSemantics &, integerPart); 233 IEEEFloat(const fltSemantics &, uninitializedTag); 234 IEEEFloat(const fltSemantics &, const APInt &); 235 explicit IEEEFloat(double d); 236 explicit IEEEFloat(float f); 237 IEEEFloat(const IEEEFloat &); 238 IEEEFloat(IEEEFloat &&); 239 ~IEEEFloat(); 240 241 /// @} 242 243 /// Returns whether this instance allocated memory. 244 bool needsCleanup() const { return partCount() > 1; } 245 246 /// \name Convenience "constructors" 247 /// @{ 248 249 /// @} 250 251 /// \name Arithmetic 252 /// @{ 253 254 opStatus add(const IEEEFloat &, roundingMode); 255 opStatus subtract(const IEEEFloat &, roundingMode); 256 opStatus multiply(const IEEEFloat &, roundingMode); 257 opStatus divide(const IEEEFloat &, roundingMode); 258 /// IEEE remainder. 259 opStatus remainder(const IEEEFloat &); 260 /// C fmod, or llvm frem. 261 opStatus mod(const IEEEFloat &); 262 opStatus fusedMultiplyAdd(const IEEEFloat &, const IEEEFloat &, roundingMode); 263 opStatus roundToIntegral(roundingMode); 264 /// IEEE-754R 5.3.1: nextUp/nextDown. 265 opStatus next(bool nextDown); 266 267 /// @} 268 269 /// \name Sign operations. 270 /// @{ 271 272 void changeSign(); 273 274 /// @} 275 276 /// \name Conversions 277 /// @{ 278 279 opStatus convert(const fltSemantics &, roundingMode, bool *); 280 opStatus convertToInteger(MutableArrayRef<integerPart>, unsigned int, bool, 281 roundingMode, bool *) const; 282 opStatus convertFromAPInt(const APInt &, bool, roundingMode); 283 opStatus convertFromSignExtendedInteger(const integerPart *, unsigned int, 284 bool, roundingMode); 285 opStatus convertFromZeroExtendedInteger(const integerPart *, unsigned int, 286 bool, roundingMode); 287 opStatus convertFromString(StringRef, roundingMode); 288 APInt bitcastToAPInt() const; 289 double convertToDouble() const; 290 float convertToFloat() const; 291 292 /// @} 293 294 /// The definition of equality is not straightforward for floating point, so 295 /// we won't use operator==. Use one of the following, or write whatever it 296 /// is you really mean. 297 bool operator==(const IEEEFloat &) const = delete; 298 299 /// IEEE comparison with another floating point number (NaNs compare 300 /// unordered, 0==-0). 301 cmpResult compare(const IEEEFloat &) const; 302 303 /// Bitwise comparison for equality (QNaNs compare equal, 0!=-0). 304 bool bitwiseIsEqual(const IEEEFloat &) const; 305 306 /// Write out a hexadecimal representation of the floating point value to DST, 307 /// which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d. 308 /// Return the number of characters written, excluding the terminating NUL. 309 unsigned int convertToHexString(char *dst, unsigned int hexDigits, 310 bool upperCase, roundingMode) const; 311 312 /// \name IEEE-754R 5.7.2 General operations. 313 /// @{ 314 315 /// IEEE-754R isSignMinus: Returns true if and only if the current value is 316 /// negative. 317 /// 318 /// This applies to zeros and NaNs as well. 319 bool isNegative() const { return sign; } 320 321 /// IEEE-754R isNormal: Returns true if and only if the current value is normal. 322 /// 323 /// This implies that the current value of the float is not zero, subnormal, 324 /// infinite, or NaN following the definition of normality from IEEE-754R. 325 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); } 326 327 /// Returns true if and only if the current value is zero, subnormal, or 328 /// normal. 329 /// 330 /// This means that the value is not infinite or NaN. 331 bool isFinite() const { return !isNaN() && !isInfinity(); } 332 333 /// Returns true if and only if the float is plus or minus zero. 334 bool isZero() const { return category == fcZero; } 335 336 /// IEEE-754R isSubnormal(): Returns true if and only if the float is a 337 /// denormal. 338 bool isDenormal() const; 339 340 /// IEEE-754R isInfinite(): Returns true if and only if the float is infinity. 341 bool isInfinity() const { return category == fcInfinity; } 342 343 /// Returns true if and only if the float is a quiet or signaling NaN. 344 bool isNaN() const { return category == fcNaN; } 345 346 /// Returns true if and only if the float is a signaling NaN. 347 bool isSignaling() const; 348 349 /// @} 350 351 /// \name Simple Queries 352 /// @{ 353 354 fltCategory getCategory() const { return category; } 355 const fltSemantics &getSemantics() const { return *semantics; } 356 bool isNonZero() const { return category != fcZero; } 357 bool isFiniteNonZero() const { return isFinite() && !isZero(); } 358 bool isPosZero() const { return isZero() && !isNegative(); } 359 bool isNegZero() const { return isZero() && isNegative(); } 360 361 /// Returns true if and only if the number has the smallest possible non-zero 362 /// magnitude in the current semantics. 363 bool isSmallest() const; 364 365 /// Returns true if and only if the number has the largest possible finite 366 /// magnitude in the current semantics. 367 bool isLargest() const; 368 369 /// Returns true if and only if the number is an exact integer. 370 bool isInteger() const; 371 372 /// @} 373 374 IEEEFloat &operator=(const IEEEFloat &); 375 IEEEFloat &operator=(IEEEFloat &&); 376 377 /// Overload to compute a hash code for an APFloat value. 378 /// 379 /// Note that the use of hash codes for floating point values is in general 380 /// frought with peril. Equality is hard to define for these values. For 381 /// example, should negative and positive zero hash to different codes? Are 382 /// they equal or not? This hash value implementation specifically 383 /// emphasizes producing different codes for different inputs in order to 384 /// be used in canonicalization and memoization. As such, equality is 385 /// bitwiseIsEqual, and 0 != -0. 386 friend hash_code hash_value(const IEEEFloat &Arg); 387 388 /// Converts this value into a decimal string. 389 /// 390 /// \param FormatPrecision The maximum number of digits of 391 /// precision to output. If there are fewer digits available, 392 /// zero padding will not be used unless the value is 393 /// integral and small enough to be expressed in 394 /// FormatPrecision digits. 0 means to use the natural 395 /// precision of the number. 396 /// \param FormatMaxPadding The maximum number of zeros to 397 /// consider inserting before falling back to scientific 398 /// notation. 0 means to always use scientific notation. 399 /// 400 /// Number Precision MaxPadding Result 401 /// ------ --------- ---------- ------ 402 /// 1.01E+4 5 2 10100 403 /// 1.01E+4 4 2 1.01E+4 404 /// 1.01E+4 5 1 1.01E+4 405 /// 1.01E-2 5 2 0.0101 406 /// 1.01E-2 4 2 0.0101 407 /// 1.01E-2 4 1 1.01E-2 408 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0, 409 unsigned FormatMaxPadding = 3) const; 410 411 /// If this value has an exact multiplicative inverse, store it in inv and 412 /// return true. 413 bool getExactInverse(APFloat *inv) const; 414 415 /// Returns the exponent of the internal representation of the APFloat. 416 /// 417 /// Because the radix of APFloat is 2, this is equivalent to floor(log2(x)). 418 /// For special APFloat values, this returns special error codes: 419 /// 420 /// NaN -> \c IEK_NaN 421 /// 0 -> \c IEK_Zero 422 /// Inf -> \c IEK_Inf 423 /// 424 friend int ilogb(const IEEEFloat &Arg); 425 426 /// Returns: X * 2^Exp for integral exponents. 427 friend IEEEFloat scalbn(IEEEFloat X, int Exp, roundingMode); 428 429 friend IEEEFloat frexp(const IEEEFloat &X, int &Exp, roundingMode); 430 431 /// \name Special value setters. 432 /// @{ 433 434 void makeLargest(bool Neg = false); 435 void makeSmallest(bool Neg = false); 436 void makeNaN(bool SNaN = false, bool Neg = false, 437 const APInt *fill = nullptr); 438 void makeInf(bool Neg = false); 439 void makeZero(bool Neg = false); 440 void makeQuiet(); 441 442 /// Returns the smallest (by magnitude) normalized finite number in the given 443 /// semantics. 444 /// 445 /// \param Negative - True iff the number should be negative 446 void makeSmallestNormalized(bool Negative = false); 447 448 /// @} 449 450 cmpResult compareAbsoluteValue(const IEEEFloat &) const; 451 452 private: 453 /// \name Simple Queries 454 /// @{ 455 456 integerPart *significandParts(); 457 const integerPart *significandParts() const; 458 unsigned int partCount() const; 459 460 /// @} 461 462 /// \name Significand operations. 463 /// @{ 464 465 integerPart addSignificand(const IEEEFloat &); 466 integerPart subtractSignificand(const IEEEFloat &, integerPart); 467 lostFraction addOrSubtractSignificand(const IEEEFloat &, bool subtract); 468 lostFraction multiplySignificand(const IEEEFloat &, const IEEEFloat *); 469 lostFraction divideSignificand(const IEEEFloat &); 470 void incrementSignificand(); 471 void initialize(const fltSemantics *); 472 void shiftSignificandLeft(unsigned int); 473 lostFraction shiftSignificandRight(unsigned int); 474 unsigned int significandLSB() const; 475 unsigned int significandMSB() const; 476 void zeroSignificand(); 477 /// Return true if the significand excluding the integral bit is all ones. 478 bool isSignificandAllOnes() const; 479 /// Return true if the significand excluding the integral bit is all zeros. 480 bool isSignificandAllZeros() const; 481 482 /// @} 483 484 /// \name Arithmetic on special values. 485 /// @{ 486 487 opStatus addOrSubtractSpecials(const IEEEFloat &, bool subtract); 488 opStatus divideSpecials(const IEEEFloat &); 489 opStatus multiplySpecials(const IEEEFloat &); 490 opStatus modSpecials(const IEEEFloat &); 491 492 /// @} 493 494 /// \name Miscellany 495 /// @{ 496 497 bool convertFromStringSpecials(StringRef str); 498 opStatus normalize(roundingMode, lostFraction); 499 opStatus addOrSubtract(const IEEEFloat &, roundingMode, bool subtract); 500 opStatus handleOverflow(roundingMode); 501 bool roundAwayFromZero(roundingMode, lostFraction, unsigned int) const; 502 opStatus convertToSignExtendedInteger(MutableArrayRef<integerPart>, 503 unsigned int, bool, roundingMode, 504 bool *) const; 505 opStatus convertFromUnsignedParts(const integerPart *, unsigned int, 506 roundingMode); 507 opStatus convertFromHexadecimalString(StringRef, roundingMode); 508 opStatus convertFromDecimalString(StringRef, roundingMode); 509 char *convertNormalToHexString(char *, unsigned int, bool, 510 roundingMode) const; 511 opStatus roundSignificandWithExponent(const integerPart *, unsigned int, int, 512 roundingMode); 513 514 /// @} 515 516 APInt convertHalfAPFloatToAPInt() const; 517 APInt convertFloatAPFloatToAPInt() const; 518 APInt convertDoubleAPFloatToAPInt() const; 519 APInt convertQuadrupleAPFloatToAPInt() const; 520 APInt convertF80LongDoubleAPFloatToAPInt() const; 521 APInt convertPPCDoubleDoubleAPFloatToAPInt() const; 522 void initFromAPInt(const fltSemantics *Sem, const APInt &api); 523 void initFromHalfAPInt(const APInt &api); 524 void initFromFloatAPInt(const APInt &api); 525 void initFromDoubleAPInt(const APInt &api); 526 void initFromQuadrupleAPInt(const APInt &api); 527 void initFromF80LongDoubleAPInt(const APInt &api); 528 void initFromPPCDoubleDoubleAPInt(const APInt &api); 529 530 void assign(const IEEEFloat &); 531 void copySignificand(const IEEEFloat &); 532 void freeSignificand(); 533 534 /// Note: this must be the first data member. 535 /// The semantics that this value obeys. 536 const fltSemantics *semantics; 537 538 /// A binary fraction with an explicit integer bit. 539 /// 540 /// The significand must be at least one bit wider than the target precision. 541 union Significand { 542 integerPart part; 543 integerPart *parts; 544 } significand; 545 546 /// The signed unbiased exponent of the value. 547 ExponentType exponent; 548 549 /// What kind of floating point number this is. 550 /// 551 /// Only 2 bits are required, but VisualStudio incorrectly sign extends it. 552 /// Using the extra bit keeps it from failing under VisualStudio. 553 fltCategory category : 3; 554 555 /// Sign bit of the number. 556 unsigned int sign : 1; 557 }; 558 559 hash_code hash_value(const IEEEFloat &Arg); 560 int ilogb(const IEEEFloat &Arg); 561 IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode); 562 IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM); 563 564 // This mode implements more precise float in terms of two APFloats. 565 // The interface and layout is designed for arbitray underlying semantics, 566 // though currently only PPCDoubleDouble semantics are supported, whose 567 // corresponding underlying semantics are IEEEdouble. 568 class DoubleAPFloat final : public APFloatBase { 569 // Note: this must be the first data member. 570 const fltSemantics *Semantics; 571 std::unique_ptr<APFloat[]> Floats; 572 573 opStatus addImpl(const APFloat &a, const APFloat &aa, const APFloat &c, 574 const APFloat &cc, roundingMode RM); 575 576 opStatus addWithSpecial(const DoubleAPFloat &LHS, const DoubleAPFloat &RHS, 577 DoubleAPFloat &Out, roundingMode RM); 578 579 public: 580 DoubleAPFloat(const fltSemantics &S); 581 DoubleAPFloat(const fltSemantics &S, uninitializedTag); 582 DoubleAPFloat(const fltSemantics &S, integerPart); 583 DoubleAPFloat(const fltSemantics &S, const APInt &I); 584 DoubleAPFloat(const fltSemantics &S, APFloat &&First, APFloat &&Second); 585 DoubleAPFloat(const DoubleAPFloat &RHS); 586 DoubleAPFloat(DoubleAPFloat &&RHS); 587 588 DoubleAPFloat &operator=(const DoubleAPFloat &RHS); 589 590 DoubleAPFloat &operator=(DoubleAPFloat &&RHS) { 591 if (this != &RHS) { 592 this->~DoubleAPFloat(); 593 new (this) DoubleAPFloat(std::move(RHS)); 594 } 595 return *this; 596 } 597 598 bool needsCleanup() const { return Floats != nullptr; } 599 600 APFloat &getFirst() { return Floats[0]; } 601 const APFloat &getFirst() const { return Floats[0]; } 602 APFloat &getSecond() { return Floats[1]; } 603 const APFloat &getSecond() const { return Floats[1]; } 604 605 opStatus add(const DoubleAPFloat &RHS, roundingMode RM); 606 opStatus subtract(const DoubleAPFloat &RHS, roundingMode RM); 607 opStatus multiply(const DoubleAPFloat &RHS, roundingMode RM); 608 opStatus divide(const DoubleAPFloat &RHS, roundingMode RM); 609 opStatus remainder(const DoubleAPFloat &RHS); 610 opStatus mod(const DoubleAPFloat &RHS); 611 opStatus fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, 612 const DoubleAPFloat &Addend, roundingMode RM); 613 opStatus roundToIntegral(roundingMode RM); 614 void changeSign(); 615 cmpResult compareAbsoluteValue(const DoubleAPFloat &RHS) const; 616 617 fltCategory getCategory() const; 618 bool isNegative() const; 619 620 void makeInf(bool Neg); 621 void makeZero(bool Neg); 622 void makeLargest(bool Neg); 623 void makeSmallest(bool Neg); 624 void makeSmallestNormalized(bool Neg); 625 void makeNaN(bool SNaN, bool Neg, const APInt *fill); 626 627 cmpResult compare(const DoubleAPFloat &RHS) const; 628 bool bitwiseIsEqual(const DoubleAPFloat &RHS) const; 629 APInt bitcastToAPInt() const; 630 opStatus convertFromString(StringRef, roundingMode); 631 opStatus next(bool nextDown); 632 633 opStatus convertToInteger(MutableArrayRef<integerPart> Input, 634 unsigned int Width, bool IsSigned, roundingMode RM, 635 bool *IsExact) const; 636 opStatus convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM); 637 opStatus convertFromSignExtendedInteger(const integerPart *Input, 638 unsigned int InputSize, bool IsSigned, 639 roundingMode RM); 640 opStatus convertFromZeroExtendedInteger(const integerPart *Input, 641 unsigned int InputSize, bool IsSigned, 642 roundingMode RM); 643 unsigned int convertToHexString(char *DST, unsigned int HexDigits, 644 bool UpperCase, roundingMode RM) const; 645 646 bool isDenormal() const; 647 bool isSmallest() const; 648 bool isLargest() const; 649 bool isInteger() const; 650 651 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision, 652 unsigned FormatMaxPadding) const; 653 654 bool getExactInverse(APFloat *inv) const; 655 656 friend int ilogb(const DoubleAPFloat &Arg); 657 friend DoubleAPFloat scalbn(DoubleAPFloat X, int Exp, roundingMode); 658 friend DoubleAPFloat frexp(const DoubleAPFloat &X, int &Exp, roundingMode); 659 friend hash_code hash_value(const DoubleAPFloat &Arg); 660 }; 661 662 hash_code hash_value(const DoubleAPFloat &Arg); 663 664 } // End detail namespace 665 666 // This is a interface class that is currently forwarding functionalities from 667 // detail::IEEEFloat. 668 class APFloat : public APFloatBase { 669 typedef detail::IEEEFloat IEEEFloat; 670 typedef detail::DoubleAPFloat DoubleAPFloat; 671 672 static_assert(std::is_standard_layout<IEEEFloat>::value, ""); 673 674 union Storage { 675 const fltSemantics *semantics; 676 IEEEFloat IEEE; 677 DoubleAPFloat Double; 678 679 explicit Storage(IEEEFloat F, const fltSemantics &S); 680 explicit Storage(DoubleAPFloat F, const fltSemantics &S) 681 : Double(std::move(F)) { 682 assert(&S == &PPCDoubleDouble()); 683 } 684 685 template <typename... ArgTypes> 686 Storage(const fltSemantics &Semantics, ArgTypes &&... Args) { 687 if (usesLayout<IEEEFloat>(Semantics)) { 688 new (&IEEE) IEEEFloat(Semantics, std::forward<ArgTypes>(Args)...); 689 return; 690 } 691 if (usesLayout<DoubleAPFloat>(Semantics)) { 692 new (&Double) DoubleAPFloat(Semantics, std::forward<ArgTypes>(Args)...); 693 return; 694 } 695 llvm_unreachable("Unexpected semantics"); 696 } 697 698 ~Storage() { 699 if (usesLayout<IEEEFloat>(*semantics)) { 700 IEEE.~IEEEFloat(); 701 return; 702 } 703 if (usesLayout<DoubleAPFloat>(*semantics)) { 704 Double.~DoubleAPFloat(); 705 return; 706 } 707 llvm_unreachable("Unexpected semantics"); 708 } 709 710 Storage(const Storage &RHS) { 711 if (usesLayout<IEEEFloat>(*RHS.semantics)) { 712 new (this) IEEEFloat(RHS.IEEE); 713 return; 714 } 715 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) { 716 new (this) DoubleAPFloat(RHS.Double); 717 return; 718 } 719 llvm_unreachable("Unexpected semantics"); 720 } 721 722 Storage(Storage &&RHS) { 723 if (usesLayout<IEEEFloat>(*RHS.semantics)) { 724 new (this) IEEEFloat(std::move(RHS.IEEE)); 725 return; 726 } 727 if (usesLayout<DoubleAPFloat>(*RHS.semantics)) { 728 new (this) DoubleAPFloat(std::move(RHS.Double)); 729 return; 730 } 731 llvm_unreachable("Unexpected semantics"); 732 } 733 734 Storage &operator=(const Storage &RHS) { 735 if (usesLayout<IEEEFloat>(*semantics) && 736 usesLayout<IEEEFloat>(*RHS.semantics)) { 737 IEEE = RHS.IEEE; 738 } else if (usesLayout<DoubleAPFloat>(*semantics) && 739 usesLayout<DoubleAPFloat>(*RHS.semantics)) { 740 Double = RHS.Double; 741 } else if (this != &RHS) { 742 this->~Storage(); 743 new (this) Storage(RHS); 744 } 745 return *this; 746 } 747 748 Storage &operator=(Storage &&RHS) { 749 if (usesLayout<IEEEFloat>(*semantics) && 750 usesLayout<IEEEFloat>(*RHS.semantics)) { 751 IEEE = std::move(RHS.IEEE); 752 } else if (usesLayout<DoubleAPFloat>(*semantics) && 753 usesLayout<DoubleAPFloat>(*RHS.semantics)) { 754 Double = std::move(RHS.Double); 755 } else if (this != &RHS) { 756 this->~Storage(); 757 new (this) Storage(std::move(RHS)); 758 } 759 return *this; 760 } 761 } U; 762 763 template <typename T> static bool usesLayout(const fltSemantics &Semantics) { 764 static_assert(std::is_same<T, IEEEFloat>::value || 765 std::is_same<T, DoubleAPFloat>::value, ""); 766 if (std::is_same<T, DoubleAPFloat>::value) { 767 return &Semantics == &PPCDoubleDouble(); 768 } 769 return &Semantics != &PPCDoubleDouble(); 770 } 771 772 IEEEFloat &getIEEE() { 773 if (usesLayout<IEEEFloat>(*U.semantics)) 774 return U.IEEE; 775 if (usesLayout<DoubleAPFloat>(*U.semantics)) 776 return U.Double.getFirst().U.IEEE; 777 llvm_unreachable("Unexpected semantics"); 778 } 779 780 const IEEEFloat &getIEEE() const { 781 if (usesLayout<IEEEFloat>(*U.semantics)) 782 return U.IEEE; 783 if (usesLayout<DoubleAPFloat>(*U.semantics)) 784 return U.Double.getFirst().U.IEEE; 785 llvm_unreachable("Unexpected semantics"); 786 } 787 788 void makeZero(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeZero(Neg)); } 789 790 void makeInf(bool Neg) { APFLOAT_DISPATCH_ON_SEMANTICS(makeInf(Neg)); } 791 792 void makeNaN(bool SNaN, bool Neg, const APInt *fill) { 793 APFLOAT_DISPATCH_ON_SEMANTICS(makeNaN(SNaN, Neg, fill)); 794 } 795 796 void makeLargest(bool Neg) { 797 APFLOAT_DISPATCH_ON_SEMANTICS(makeLargest(Neg)); 798 } 799 800 void makeSmallest(bool Neg) { 801 APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallest(Neg)); 802 } 803 804 void makeSmallestNormalized(bool Neg) { 805 APFLOAT_DISPATCH_ON_SEMANTICS(makeSmallestNormalized(Neg)); 806 } 807 808 // FIXME: This is due to clang 3.3 (or older version) always checks for the 809 // default constructor in an array aggregate initialization, even if no 810 // elements in the array is default initialized. 811 APFloat() : U(IEEEdouble()) { 812 llvm_unreachable("This is a workaround for old clang."); 813 } 814 815 explicit APFloat(IEEEFloat F, const fltSemantics &S) : U(std::move(F), S) {} 816 explicit APFloat(DoubleAPFloat F, const fltSemantics &S) 817 : U(std::move(F), S) {} 818 819 cmpResult compareAbsoluteValue(const APFloat &RHS) const { 820 assert(&getSemantics() == &RHS.getSemantics() && 821 "Should only compare APFloats with the same semantics"); 822 if (usesLayout<IEEEFloat>(getSemantics())) 823 return U.IEEE.compareAbsoluteValue(RHS.U.IEEE); 824 if (usesLayout<DoubleAPFloat>(getSemantics())) 825 return U.Double.compareAbsoluteValue(RHS.U.Double); 826 llvm_unreachable("Unexpected semantics"); 827 } 828 829 public: 830 APFloat(const fltSemantics &Semantics) : U(Semantics) {} 831 APFloat(const fltSemantics &Semantics, StringRef S); 832 APFloat(const fltSemantics &Semantics, integerPart I) : U(Semantics, I) {} 833 // TODO: Remove this constructor. This isn't faster than the first one. 834 APFloat(const fltSemantics &Semantics, uninitializedTag) 835 : U(Semantics, uninitialized) {} 836 APFloat(const fltSemantics &Semantics, const APInt &I) : U(Semantics, I) {} 837 explicit APFloat(double d) : U(IEEEFloat(d), IEEEdouble()) {} 838 explicit APFloat(float f) : U(IEEEFloat(f), IEEEsingle()) {} 839 APFloat(const APFloat &RHS) = default; 840 APFloat(APFloat &&RHS) = default; 841 842 ~APFloat() = default; 843 844 bool needsCleanup() const { APFLOAT_DISPATCH_ON_SEMANTICS(needsCleanup()); } 845 846 /// Factory for Positive and Negative Zero. 847 /// 848 /// \param Negative True iff the number should be negative. 849 static APFloat getZero(const fltSemantics &Sem, bool Negative = false) { 850 APFloat Val(Sem, uninitialized); 851 Val.makeZero(Negative); 852 return Val; 853 } 854 855 /// Factory for Positive and Negative Infinity. 856 /// 857 /// \param Negative True iff the number should be negative. 858 static APFloat getInf(const fltSemantics &Sem, bool Negative = false) { 859 APFloat Val(Sem, uninitialized); 860 Val.makeInf(Negative); 861 return Val; 862 } 863 864 /// Factory for NaN values. 865 /// 866 /// \param Negative - True iff the NaN generated should be negative. 867 /// \param type - The unspecified fill bits for creating the NaN, 0 by 868 /// default. The value is truncated as necessary. 869 static APFloat getNaN(const fltSemantics &Sem, bool Negative = false, 870 unsigned type = 0) { 871 if (type) { 872 APInt fill(64, type); 873 return getQNaN(Sem, Negative, &fill); 874 } else { 875 return getQNaN(Sem, Negative, nullptr); 876 } 877 } 878 879 /// Factory for QNaN values. 880 static APFloat getQNaN(const fltSemantics &Sem, bool Negative = false, 881 const APInt *payload = nullptr) { 882 APFloat Val(Sem, uninitialized); 883 Val.makeNaN(false, Negative, payload); 884 return Val; 885 } 886 887 /// Factory for SNaN values. 888 static APFloat getSNaN(const fltSemantics &Sem, bool Negative = false, 889 const APInt *payload = nullptr) { 890 APFloat Val(Sem, uninitialized); 891 Val.makeNaN(true, Negative, payload); 892 return Val; 893 } 894 895 /// Returns the largest finite number in the given semantics. 896 /// 897 /// \param Negative - True iff the number should be negative 898 static APFloat getLargest(const fltSemantics &Sem, bool Negative = false) { 899 APFloat Val(Sem, uninitialized); 900 Val.makeLargest(Negative); 901 return Val; 902 } 903 904 /// Returns the smallest (by magnitude) finite number in the given semantics. 905 /// Might be denormalized, which implies a relative loss of precision. 906 /// 907 /// \param Negative - True iff the number should be negative 908 static APFloat getSmallest(const fltSemantics &Sem, bool Negative = false) { 909 APFloat Val(Sem, uninitialized); 910 Val.makeSmallest(Negative); 911 return Val; 912 } 913 914 /// Returns the smallest (by magnitude) normalized finite number in the given 915 /// semantics. 916 /// 917 /// \param Negative - True iff the number should be negative 918 static APFloat getSmallestNormalized(const fltSemantics &Sem, 919 bool Negative = false) { 920 APFloat Val(Sem, uninitialized); 921 Val.makeSmallestNormalized(Negative); 922 return Val; 923 } 924 925 /// Returns a float which is bitcasted from an all one value int. 926 /// 927 /// \param BitWidth - Select float type 928 /// \param isIEEE - If 128 bit number, select between PPC and IEEE 929 static APFloat getAllOnesValue(unsigned BitWidth, bool isIEEE = false); 930 931 /// Used to insert APFloat objects, or objects that contain APFloat objects, 932 /// into FoldingSets. 933 void Profile(FoldingSetNodeID &NID) const; 934 935 opStatus add(const APFloat &RHS, roundingMode RM) { 936 assert(&getSemantics() == &RHS.getSemantics() && 937 "Should only call on two APFloats with the same semantics"); 938 if (usesLayout<IEEEFloat>(getSemantics())) 939 return U.IEEE.add(RHS.U.IEEE, RM); 940 if (usesLayout<DoubleAPFloat>(getSemantics())) 941 return U.Double.add(RHS.U.Double, RM); 942 llvm_unreachable("Unexpected semantics"); 943 } 944 opStatus subtract(const APFloat &RHS, roundingMode RM) { 945 assert(&getSemantics() == &RHS.getSemantics() && 946 "Should only call on two APFloats with the same semantics"); 947 if (usesLayout<IEEEFloat>(getSemantics())) 948 return U.IEEE.subtract(RHS.U.IEEE, RM); 949 if (usesLayout<DoubleAPFloat>(getSemantics())) 950 return U.Double.subtract(RHS.U.Double, RM); 951 llvm_unreachable("Unexpected semantics"); 952 } 953 opStatus multiply(const APFloat &RHS, roundingMode RM) { 954 assert(&getSemantics() == &RHS.getSemantics() && 955 "Should only call on two APFloats with the same semantics"); 956 if (usesLayout<IEEEFloat>(getSemantics())) 957 return U.IEEE.multiply(RHS.U.IEEE, RM); 958 if (usesLayout<DoubleAPFloat>(getSemantics())) 959 return U.Double.multiply(RHS.U.Double, RM); 960 llvm_unreachable("Unexpected semantics"); 961 } 962 opStatus divide(const APFloat &RHS, roundingMode RM) { 963 assert(&getSemantics() == &RHS.getSemantics() && 964 "Should only call on two APFloats with the same semantics"); 965 if (usesLayout<IEEEFloat>(getSemantics())) 966 return U.IEEE.divide(RHS.U.IEEE, RM); 967 if (usesLayout<DoubleAPFloat>(getSemantics())) 968 return U.Double.divide(RHS.U.Double, RM); 969 llvm_unreachable("Unexpected semantics"); 970 } 971 opStatus remainder(const APFloat &RHS) { 972 assert(&getSemantics() == &RHS.getSemantics() && 973 "Should only call on two APFloats with the same semantics"); 974 if (usesLayout<IEEEFloat>(getSemantics())) 975 return U.IEEE.remainder(RHS.U.IEEE); 976 if (usesLayout<DoubleAPFloat>(getSemantics())) 977 return U.Double.remainder(RHS.U.Double); 978 llvm_unreachable("Unexpected semantics"); 979 } 980 opStatus mod(const APFloat &RHS) { 981 assert(&getSemantics() == &RHS.getSemantics() && 982 "Should only call on two APFloats with the same semantics"); 983 if (usesLayout<IEEEFloat>(getSemantics())) 984 return U.IEEE.mod(RHS.U.IEEE); 985 if (usesLayout<DoubleAPFloat>(getSemantics())) 986 return U.Double.mod(RHS.U.Double); 987 llvm_unreachable("Unexpected semantics"); 988 } 989 opStatus fusedMultiplyAdd(const APFloat &Multiplicand, const APFloat &Addend, 990 roundingMode RM) { 991 assert(&getSemantics() == &Multiplicand.getSemantics() && 992 "Should only call on APFloats with the same semantics"); 993 assert(&getSemantics() == &Addend.getSemantics() && 994 "Should only call on APFloats with the same semantics"); 995 if (usesLayout<IEEEFloat>(getSemantics())) 996 return U.IEEE.fusedMultiplyAdd(Multiplicand.U.IEEE, Addend.U.IEEE, RM); 997 if (usesLayout<DoubleAPFloat>(getSemantics())) 998 return U.Double.fusedMultiplyAdd(Multiplicand.U.Double, Addend.U.Double, 999 RM); 1000 llvm_unreachable("Unexpected semantics"); 1001 } 1002 opStatus roundToIntegral(roundingMode RM) { 1003 APFLOAT_DISPATCH_ON_SEMANTICS(roundToIntegral(RM)); 1004 } 1005 1006 // TODO: bool parameters are not readable and a source of bugs. 1007 // Do something. 1008 opStatus next(bool nextDown) { 1009 APFLOAT_DISPATCH_ON_SEMANTICS(next(nextDown)); 1010 } 1011 1012 /// Add two APFloats, rounding ties to the nearest even. 1013 /// No error checking. 1014 APFloat operator+(const APFloat &RHS) const { 1015 APFloat Result(*this); 1016 (void)Result.add(RHS, rmNearestTiesToEven); 1017 return Result; 1018 } 1019 1020 /// Subtract two APFloats, rounding ties to the nearest even. 1021 /// No error checking. 1022 APFloat operator-(const APFloat &RHS) const { 1023 APFloat Result(*this); 1024 (void)Result.subtract(RHS, rmNearestTiesToEven); 1025 return Result; 1026 } 1027 1028 /// Multiply two APFloats, rounding ties to the nearest even. 1029 /// No error checking. 1030 APFloat operator*(const APFloat &RHS) const { 1031 APFloat Result(*this); 1032 (void)Result.multiply(RHS, rmNearestTiesToEven); 1033 return Result; 1034 } 1035 1036 /// Divide the first APFloat by the second, rounding ties to the nearest even. 1037 /// No error checking. 1038 APFloat operator/(const APFloat &RHS) const { 1039 APFloat Result(*this); 1040 (void)Result.divide(RHS, rmNearestTiesToEven); 1041 return Result; 1042 } 1043 1044 void changeSign() { APFLOAT_DISPATCH_ON_SEMANTICS(changeSign()); } 1045 void clearSign() { 1046 if (isNegative()) 1047 changeSign(); 1048 } 1049 void copySign(const APFloat &RHS) { 1050 if (isNegative() != RHS.isNegative()) 1051 changeSign(); 1052 } 1053 1054 /// A static helper to produce a copy of an APFloat value with its sign 1055 /// copied from some other APFloat. 1056 static APFloat copySign(APFloat Value, const APFloat &Sign) { 1057 Value.copySign(Sign); 1058 return Value; 1059 } 1060 1061 opStatus convert(const fltSemantics &ToSemantics, roundingMode RM, 1062 bool *losesInfo); 1063 opStatus convertToInteger(MutableArrayRef<integerPart> Input, 1064 unsigned int Width, bool IsSigned, roundingMode RM, 1065 bool *IsExact) const { 1066 APFLOAT_DISPATCH_ON_SEMANTICS( 1067 convertToInteger(Input, Width, IsSigned, RM, IsExact)); 1068 } 1069 opStatus convertToInteger(APSInt &Result, roundingMode RM, 1070 bool *IsExact) const; 1071 opStatus convertFromAPInt(const APInt &Input, bool IsSigned, 1072 roundingMode RM) { 1073 APFLOAT_DISPATCH_ON_SEMANTICS(convertFromAPInt(Input, IsSigned, RM)); 1074 } 1075 opStatus convertFromSignExtendedInteger(const integerPart *Input, 1076 unsigned int InputSize, bool IsSigned, 1077 roundingMode RM) { 1078 APFLOAT_DISPATCH_ON_SEMANTICS( 1079 convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM)); 1080 } 1081 opStatus convertFromZeroExtendedInteger(const integerPart *Input, 1082 unsigned int InputSize, bool IsSigned, 1083 roundingMode RM) { 1084 APFLOAT_DISPATCH_ON_SEMANTICS( 1085 convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM)); 1086 } 1087 opStatus convertFromString(StringRef, roundingMode); 1088 APInt bitcastToAPInt() const { 1089 APFLOAT_DISPATCH_ON_SEMANTICS(bitcastToAPInt()); 1090 } 1091 double convertToDouble() const { return getIEEE().convertToDouble(); } 1092 float convertToFloat() const { return getIEEE().convertToFloat(); } 1093 1094 bool operator==(const APFloat &) const = delete; 1095 1096 cmpResult compare(const APFloat &RHS) const { 1097 assert(&getSemantics() == &RHS.getSemantics() && 1098 "Should only compare APFloats with the same semantics"); 1099 if (usesLayout<IEEEFloat>(getSemantics())) 1100 return U.IEEE.compare(RHS.U.IEEE); 1101 if (usesLayout<DoubleAPFloat>(getSemantics())) 1102 return U.Double.compare(RHS.U.Double); 1103 llvm_unreachable("Unexpected semantics"); 1104 } 1105 1106 bool bitwiseIsEqual(const APFloat &RHS) const { 1107 if (&getSemantics() != &RHS.getSemantics()) 1108 return false; 1109 if (usesLayout<IEEEFloat>(getSemantics())) 1110 return U.IEEE.bitwiseIsEqual(RHS.U.IEEE); 1111 if (usesLayout<DoubleAPFloat>(getSemantics())) 1112 return U.Double.bitwiseIsEqual(RHS.U.Double); 1113 llvm_unreachable("Unexpected semantics"); 1114 } 1115 1116 unsigned int convertToHexString(char *DST, unsigned int HexDigits, 1117 bool UpperCase, roundingMode RM) const { 1118 APFLOAT_DISPATCH_ON_SEMANTICS( 1119 convertToHexString(DST, HexDigits, UpperCase, RM)); 1120 } 1121 1122 bool isZero() const { return getCategory() == fcZero; } 1123 bool isInfinity() const { return getCategory() == fcInfinity; } 1124 bool isNaN() const { return getCategory() == fcNaN; } 1125 1126 bool isNegative() const { return getIEEE().isNegative(); } 1127 bool isDenormal() const { APFLOAT_DISPATCH_ON_SEMANTICS(isDenormal()); } 1128 bool isSignaling() const { return getIEEE().isSignaling(); } 1129 1130 bool isNormal() const { return !isDenormal() && isFiniteNonZero(); } 1131 bool isFinite() const { return !isNaN() && !isInfinity(); } 1132 1133 fltCategory getCategory() const { return getIEEE().getCategory(); } 1134 const fltSemantics &getSemantics() const { return *U.semantics; } 1135 bool isNonZero() const { return !isZero(); } 1136 bool isFiniteNonZero() const { return isFinite() && !isZero(); } 1137 bool isPosZero() const { return isZero() && !isNegative(); } 1138 bool isNegZero() const { return isZero() && isNegative(); } 1139 bool isSmallest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isSmallest()); } 1140 bool isLargest() const { APFLOAT_DISPATCH_ON_SEMANTICS(isLargest()); } 1141 bool isInteger() const { APFLOAT_DISPATCH_ON_SEMANTICS(isInteger()); } 1142 1143 APFloat &operator=(const APFloat &RHS) = default; 1144 APFloat &operator=(APFloat &&RHS) = default; 1145 1146 void toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision = 0, 1147 unsigned FormatMaxPadding = 3) const { 1148 APFLOAT_DISPATCH_ON_SEMANTICS( 1149 toString(Str, FormatPrecision, FormatMaxPadding)); 1150 } 1151 1152 void print(raw_ostream &) const; 1153 void dump() const; 1154 1155 bool getExactInverse(APFloat *inv) const { 1156 APFLOAT_DISPATCH_ON_SEMANTICS(getExactInverse(inv)); 1157 } 1158 1159 friend hash_code hash_value(const APFloat &Arg); 1160 friend int ilogb(const APFloat &Arg) { return ilogb(Arg.getIEEE()); } 1161 friend APFloat scalbn(APFloat X, int Exp, roundingMode RM); 1162 friend APFloat frexp(const APFloat &X, int &Exp, roundingMode RM); 1163 friend IEEEFloat; 1164 friend DoubleAPFloat; 1165 }; 1166 1167 /// See friend declarations above. 1168 /// 1169 /// These additional declarations are required in order to compile LLVM with IBM 1170 /// xlC compiler. 1171 hash_code hash_value(const APFloat &Arg); 1172 inline APFloat scalbn(APFloat X, int Exp, APFloat::roundingMode RM) { 1173 if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics())) 1174 return APFloat(scalbn(X.U.IEEE, Exp, RM), X.getSemantics()); 1175 if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics())) 1176 return APFloat(scalbn(X.U.Double, Exp, RM), X.getSemantics()); 1177 llvm_unreachable("Unexpected semantics"); 1178 } 1179 1180 /// Equivalent of C standard library function. 1181 /// 1182 /// While the C standard says Exp is an unspecified value for infinity and nan, 1183 /// this returns INT_MAX for infinities, and INT_MIN for NaNs. 1184 inline APFloat frexp(const APFloat &X, int &Exp, APFloat::roundingMode RM) { 1185 if (APFloat::usesLayout<detail::IEEEFloat>(X.getSemantics())) 1186 return APFloat(frexp(X.U.IEEE, Exp, RM), X.getSemantics()); 1187 if (APFloat::usesLayout<detail::DoubleAPFloat>(X.getSemantics())) 1188 return APFloat(frexp(X.U.Double, Exp, RM), X.getSemantics()); 1189 llvm_unreachable("Unexpected semantics"); 1190 } 1191 /// Returns the absolute value of the argument. 1192 inline APFloat abs(APFloat X) { 1193 X.clearSign(); 1194 return X; 1195 } 1196 1197 /// \brief Returns the negated value of the argument. 1198 inline APFloat neg(APFloat X) { 1199 X.changeSign(); 1200 return X; 1201 } 1202 1203 /// Implements IEEE minNum semantics. Returns the smaller of the 2 arguments if 1204 /// both are not NaN. If either argument is a NaN, returns the other argument. 1205 LLVM_READONLY 1206 inline APFloat minnum(const APFloat &A, const APFloat &B) { 1207 if (A.isNaN()) 1208 return B; 1209 if (B.isNaN()) 1210 return A; 1211 return (B.compare(A) == APFloat::cmpLessThan) ? B : A; 1212 } 1213 1214 /// Implements IEEE maxNum semantics. Returns the larger of the 2 arguments if 1215 /// both are not NaN. If either argument is a NaN, returns the other argument. 1216 LLVM_READONLY 1217 inline APFloat maxnum(const APFloat &A, const APFloat &B) { 1218 if (A.isNaN()) 1219 return B; 1220 if (B.isNaN()) 1221 return A; 1222 return (A.compare(B) == APFloat::cmpLessThan) ? B : A; 1223 } 1224 1225 } // namespace llvm 1226 1227 #undef APFLOAT_DISPATCH_ON_SEMANTICS 1228 #endif // LLVM_ADT_APFLOAT_H 1229