diff --git a/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp b/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp index 64806cee37ef..231e565f27e5 100644 --- a/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp +++ b/clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.cpp @@ -1,213 +1,217 @@ //===--- MagicNumbersCheck.cpp - clang-tidy-------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // A checker for magic numbers: integer or floating point literals embedded // in the code, outside the definition of a constant or an enumeration. // //===----------------------------------------------------------------------===// #include "MagicNumbersCheck.h" #include "../utils/OptionsUtils.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "llvm/ADT/STLExtras.h" #include using namespace clang::ast_matchers; using namespace clang::ast_type_traits; namespace clang { static bool isUsedToInitializeAConstant(const MatchFinder::MatchResult &Result, const DynTypedNode &Node) { const auto *AsDecl = Node.get(); if (AsDecl) { if (AsDecl->getType().isConstQualified()) return true; return AsDecl->isImplicit(); } if (Node.get()) return true; return llvm::any_of(Result.Context->getParents(Node), [&Result](const DynTypedNode &Parent) { return isUsedToInitializeAConstant(Result, Parent); }); } static bool isUsedToDefineABitField(const MatchFinder::MatchResult &Result, const DynTypedNode &Node) { const auto *AsFieldDecl = Node.get(); if (AsFieldDecl && AsFieldDecl->isBitField()) return true; return llvm::any_of(Result.Context->getParents(Node), [&Result](const DynTypedNode &Parent) { return isUsedToDefineABitField(Result, Parent); }); } namespace tidy { namespace readability { const char DefaultIgnoredIntegerValues[] = "1;2;3;4;"; const char DefaultIgnoredFloatingPointValues[] = "1.0;100.0;"; MagicNumbersCheck::MagicNumbersCheck(StringRef Name, ClangTidyContext *Context) : ClangTidyCheck(Name, Context), IgnoreAllFloatingPointValues( Options.get("IgnoreAllFloatingPointValues", false)), IgnoreBitFieldsWidths(Options.get("IgnoreBitFieldsWidths", true)), IgnorePowersOf2IntegerValues( Options.get("IgnorePowersOf2IntegerValues", false)) { // Process the set of ignored integer values. const std::vector IgnoredIntegerValuesInput = utils::options::parseStringList( Options.get("IgnoredIntegerValues", DefaultIgnoredIntegerValues)); IgnoredIntegerValues.resize(IgnoredIntegerValuesInput.size()); llvm::transform(IgnoredIntegerValuesInput, IgnoredIntegerValues.begin(), [](const std::string &Value) { return std::stoll(Value); }); llvm::sort(IgnoredIntegerValues); if (!IgnoreAllFloatingPointValues) { // Process the set of ignored floating point values. const std::vector IgnoredFloatingPointValuesInput = utils::options::parseStringList(Options.get( "IgnoredFloatingPointValues", DefaultIgnoredFloatingPointValues)); IgnoredFloatingPointValues.reserve(IgnoredFloatingPointValuesInput.size()); IgnoredDoublePointValues.reserve(IgnoredFloatingPointValuesInput.size()); for (const auto &InputValue : IgnoredFloatingPointValuesInput) { llvm::APFloat FloatValue(llvm::APFloat::IEEEsingle()); - FloatValue.convertFromString(InputValue, DefaultRoundingMode); + if (!FloatValue.convertFromString(InputValue, DefaultRoundingMode)) { + assert(false && "Invalid floating point representation"); + } IgnoredFloatingPointValues.push_back(FloatValue.convertToFloat()); llvm::APFloat DoubleValue(llvm::APFloat::IEEEdouble()); - DoubleValue.convertFromString(InputValue, DefaultRoundingMode); + if (!DoubleValue.convertFromString(InputValue, DefaultRoundingMode)) { + assert(false && "Invalid floating point representation"); + } IgnoredDoublePointValues.push_back(DoubleValue.convertToDouble()); } llvm::sort(IgnoredFloatingPointValues.begin(), IgnoredFloatingPointValues.end()); llvm::sort(IgnoredDoublePointValues.begin(), IgnoredDoublePointValues.end()); } } void MagicNumbersCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) { Options.store(Opts, "IgnoredIntegerValues", DefaultIgnoredIntegerValues); Options.store(Opts, "IgnoredFloatingPointValues", DefaultIgnoredFloatingPointValues); } void MagicNumbersCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher(integerLiteral().bind("integer"), this); if (!IgnoreAllFloatingPointValues) Finder->addMatcher(floatLiteral().bind("float"), this); } void MagicNumbersCheck::check(const MatchFinder::MatchResult &Result) { checkBoundMatch(Result, "integer"); checkBoundMatch(Result, "float"); } bool MagicNumbersCheck::isConstant(const MatchFinder::MatchResult &Result, const Expr &ExprResult) const { return llvm::any_of( Result.Context->getParents(ExprResult), [&Result](const DynTypedNode &Parent) { if (isUsedToInitializeAConstant(Result, Parent)) return true; // Ignore this instance, because this matches an // expanded class enumeration value. if (Parent.get() && llvm::any_of( Result.Context->getParents(Parent), [](const DynTypedNode &GrandParent) { return GrandParent.get() != nullptr; })) return true; // Ignore this instance, because this match reports the // location where the template is defined, not where it // is instantiated. if (Parent.get()) return true; // Don't warn on string user defined literals: // std::string s = "Hello World"s; if (const auto *UDL = Parent.get()) if (UDL->getLiteralOperatorKind() == UserDefinedLiteral::LOK_String) return true; return false; }); } bool MagicNumbersCheck::isIgnoredValue(const IntegerLiteral *Literal) const { const llvm::APInt IntValue = Literal->getValue(); const int64_t Value = IntValue.getZExtValue(); if (Value == 0) return true; if (IgnorePowersOf2IntegerValues && IntValue.isPowerOf2()) return true; return std::binary_search(IgnoredIntegerValues.begin(), IgnoredIntegerValues.end(), Value); } bool MagicNumbersCheck::isIgnoredValue(const FloatingLiteral *Literal) const { const llvm::APFloat FloatValue = Literal->getValue(); if (FloatValue.isZero()) return true; if (&FloatValue.getSemantics() == &llvm::APFloat::IEEEsingle()) { const float Value = FloatValue.convertToFloat(); return std::binary_search(IgnoredFloatingPointValues.begin(), IgnoredFloatingPointValues.end(), Value); } if (&FloatValue.getSemantics() == &llvm::APFloat::IEEEdouble()) { const double Value = FloatValue.convertToDouble(); return std::binary_search(IgnoredDoublePointValues.begin(), IgnoredDoublePointValues.end(), Value); } return false; } bool MagicNumbersCheck::isSyntheticValue(const SourceManager *SourceManager, const IntegerLiteral *Literal) const { const std::pair FileOffset = SourceManager->getDecomposedLoc(Literal->getLocation()); if (FileOffset.first.isInvalid()) return false; const StringRef BufferIdentifier = SourceManager->getBuffer(FileOffset.first)->getBufferIdentifier(); return BufferIdentifier.empty(); } bool MagicNumbersCheck::isBitFieldWidth( const clang::ast_matchers::MatchFinder::MatchResult &Result, const IntegerLiteral &Literal) const { return IgnoreBitFieldsWidths && llvm::any_of(Result.Context->getParents(Literal), [&Result](const DynTypedNode &Parent) { return isUsedToDefineABitField(Result, Parent); }); } } // namespace readability } // namespace tidy } // namespace clang diff --git a/clang/lib/Lex/LiteralSupport.cpp b/clang/lib/Lex/LiteralSupport.cpp index 66309183a144..5881852b1424 100644 --- a/clang/lib/Lex/LiteralSupport.cpp +++ b/clang/lib/Lex/LiteralSupport.cpp @@ -1,1899 +1,1902 @@ //===--- LiteralSupport.cpp - Code to parse and process literals ----------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the NumericLiteralParser, CharLiteralParser, and // StringLiteralParser interfaces. // //===----------------------------------------------------------------------===// #include "clang/Lex/LiteralSupport.h" #include "clang/Basic/CharInfo.h" #include "clang/Basic/LangOptions.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/TargetInfo.h" #include "clang/Lex/LexDiagnostic.h" #include "clang/Lex/Lexer.h" #include "clang/Lex/Preprocessor.h" #include "clang/Lex/Token.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/ErrorHandling.h" #include #include #include #include #include #include using namespace clang; static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) { switch (kind) { default: llvm_unreachable("Unknown token type!"); case tok::char_constant: case tok::string_literal: case tok::utf8_char_constant: case tok::utf8_string_literal: return Target.getCharWidth(); case tok::wide_char_constant: case tok::wide_string_literal: return Target.getWCharWidth(); case tok::utf16_char_constant: case tok::utf16_string_literal: return Target.getChar16Width(); case tok::utf32_char_constant: case tok::utf32_string_literal: return Target.getChar32Width(); } } static CharSourceRange MakeCharSourceRange(const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd) { SourceLocation Begin = Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin, TokLoc.getManager(), Features); SourceLocation End = Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin, TokLoc.getManager(), Features); return CharSourceRange::getCharRange(Begin, End); } /// Produce a diagnostic highlighting some portion of a literal. /// /// Emits the diagnostic \p DiagID, highlighting the range of characters from /// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be /// a substring of a spelling buffer for the token beginning at \p TokBegin. static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID) { SourceLocation Begin = Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin, TokLoc.getManager(), Features); return Diags->Report(Begin, DiagID) << MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd); } /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in /// either a character or a string literal. static unsigned ProcessCharEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, bool &HadError, FullSourceLoc Loc, unsigned CharWidth, DiagnosticsEngine *Diags, const LangOptions &Features) { const char *EscapeBegin = ThisTokBuf; // Skip the '\' char. ++ThisTokBuf; // We know that this character can't be off the end of the buffer, because // that would have been \", which would not have been the end of string. unsigned ResultChar = *ThisTokBuf++; switch (ResultChar) { // These map to themselves. case '\\': case '\'': case '"': case '?': break; // These have fixed mappings. case 'a': // TODO: K&R: the meaning of '\\a' is different in traditional C ResultChar = 7; break; case 'b': ResultChar = 8; break; case 'e': if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::ext_nonstandard_escape) << "e"; ResultChar = 27; break; case 'E': if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::ext_nonstandard_escape) << "E"; ResultChar = 27; break; case 'f': ResultChar = 12; break; case 'n': ResultChar = 10; break; case 'r': ResultChar = 13; break; case 't': ResultChar = 9; break; case 'v': ResultChar = 11; break; case 'x': { // Hex escape. ResultChar = 0; if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) { if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::err_hex_escape_no_digits) << "x"; HadError = true; break; } // Hex escapes are a maximal series of hex digits. bool Overflow = false; for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) { int CharVal = llvm::hexDigitValue(ThisTokBuf[0]); if (CharVal == -1) break; // About to shift out a digit? if (ResultChar & 0xF0000000) Overflow = true; ResultChar <<= 4; ResultChar |= CharVal; } // See if any bits will be truncated when evaluated as a character. if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) { Overflow = true; ResultChar &= ~0U >> (32-CharWidth); } // Check for overflow. if (Overflow && Diags) // Too many digits to fit in Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::err_escape_too_large) << 0; break; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': { // Octal escapes. --ThisTokBuf; ResultChar = 0; // Octal escapes are a series of octal digits with maximum length 3. // "\0123" is a two digit sequence equal to "\012" "3". unsigned NumDigits = 0; do { ResultChar <<= 3; ResultChar |= *ThisTokBuf++ - '0'; ++NumDigits; } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 && ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7'); // Check for overflow. Reject '\777', but not L'\777'. if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) { if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::err_escape_too_large) << 1; ResultChar &= ~0U >> (32-CharWidth); } break; } // Otherwise, these are not valid escapes. case '(': case '{': case '[': case '%': // GCC accepts these as extensions. We warn about them as such though. if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::ext_nonstandard_escape) << std::string(1, ResultChar); break; default: if (!Diags) break; if (isPrintable(ResultChar)) Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::ext_unknown_escape) << std::string(1, ResultChar); else Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf, diag::ext_unknown_escape) << "x" + llvm::utohexstr(ResultChar); break; } return ResultChar; } static void appendCodePoint(unsigned Codepoint, llvm::SmallVectorImpl &Str) { char ResultBuf[4]; char *ResultPtr = ResultBuf; bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr); (void)Res; assert(Res && "Unexpected conversion failure"); Str.append(ResultBuf, ResultPtr); } void clang::expandUCNs(SmallVectorImpl &Buf, StringRef Input) { for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) { if (*I != '\\') { Buf.push_back(*I); continue; } ++I; assert(*I == 'u' || *I == 'U'); unsigned NumHexDigits; if (*I == 'u') NumHexDigits = 4; else NumHexDigits = 8; assert(I + NumHexDigits <= E); uint32_t CodePoint = 0; for (++I; NumHexDigits != 0; ++I, --NumHexDigits) { unsigned Value = llvm::hexDigitValue(*I); assert(Value != -1U); CodePoint <<= 4; CodePoint += Value; } appendCodePoint(CodePoint, Buf); --I; } } /// ProcessUCNEscape - Read the Universal Character Name, check constraints and /// return the UTF32. static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, uint32_t &UcnVal, unsigned short &UcnLen, FullSourceLoc Loc, DiagnosticsEngine *Diags, const LangOptions &Features, bool in_char_string_literal = false) { const char *UcnBegin = ThisTokBuf; // Skip the '\u' char's. ThisTokBuf += 2; if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) { if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1); return false; } UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8); unsigned short UcnLenSave = UcnLen; for (; ThisTokBuf != ThisTokEnd && UcnLenSave; ++ThisTokBuf, UcnLenSave--) { int CharVal = llvm::hexDigitValue(ThisTokBuf[0]); if (CharVal == -1) break; UcnVal <<= 4; UcnVal |= CharVal; } // If we didn't consume the proper number of digits, there is a problem. if (UcnLenSave) { if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, diag::err_ucn_escape_incomplete); return false; } // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2] if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints UcnVal > 0x10FFFF) { // maximum legal UTF32 value if (Diags) Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, diag::err_ucn_escape_invalid); return false; } // C++11 allows UCNs that refer to control characters and basic source // characters inside character and string literals if (UcnVal < 0xa0 && (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, ` bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal); if (Diags) { char BasicSCSChar = UcnVal; if (UcnVal >= 0x20 && UcnVal < 0x7f) Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, IsError ? diag::err_ucn_escape_basic_scs : diag::warn_cxx98_compat_literal_ucn_escape_basic_scs) << StringRef(&BasicSCSChar, 1); else Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, IsError ? diag::err_ucn_control_character : diag::warn_cxx98_compat_literal_ucn_control_character); } if (IsError) return false; } if (!Features.CPlusPlus && !Features.C99 && Diags) Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf, diag::warn_ucn_not_valid_in_c89_literal); return true; } /// MeasureUCNEscape - Determine the number of bytes within the resulting string /// which this UCN will occupy. static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, unsigned CharByteWidth, const LangOptions &Features, bool &HadError) { // UTF-32: 4 bytes per escape. if (CharByteWidth == 4) return 4; uint32_t UcnVal = 0; unsigned short UcnLen = 0; FullSourceLoc Loc; if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen, Loc, nullptr, Features, true)) { HadError = true; return 0; } // UTF-16: 2 bytes for BMP, 4 bytes otherwise. if (CharByteWidth == 2) return UcnVal <= 0xFFFF ? 2 : 4; // UTF-8. if (UcnVal < 0x80) return 1; if (UcnVal < 0x800) return 2; if (UcnVal < 0x10000) return 3; return 4; } /// EncodeUCNEscape - Read the Universal Character Name, check constraints and /// convert the UTF32 to UTF8 or UTF16. This is a subroutine of /// StringLiteralParser. When we decide to implement UCN's for identifiers, /// we will likely rework our support for UCN's. static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf, const char *ThisTokEnd, char *&ResultBuf, bool &HadError, FullSourceLoc Loc, unsigned CharByteWidth, DiagnosticsEngine *Diags, const LangOptions &Features) { typedef uint32_t UTF32; UTF32 UcnVal = 0; unsigned short UcnLen = 0; if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen, Loc, Diags, Features, true)) { HadError = true; return; } assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) && "only character widths of 1, 2, or 4 bytes supported"); (void)UcnLen; assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported"); if (CharByteWidth == 4) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. llvm::UTF32 *ResultPtr = reinterpret_cast(ResultBuf); *ResultPtr = UcnVal; ResultBuf += 4; return; } if (CharByteWidth == 2) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. llvm::UTF16 *ResultPtr = reinterpret_cast(ResultBuf); if (UcnVal <= (UTF32)0xFFFF) { *ResultPtr = UcnVal; ResultBuf += 2; return; } // Convert to UTF16. UcnVal -= 0x10000; *ResultPtr = 0xD800 + (UcnVal >> 10); *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF); ResultBuf += 4; return; } assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters"); // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8. // The conversion below was inspired by: // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c // First, we determine how many bytes the result will require. typedef uint8_t UTF8; unsigned short bytesToWrite = 0; if (UcnVal < (UTF32)0x80) bytesToWrite = 1; else if (UcnVal < (UTF32)0x800) bytesToWrite = 2; else if (UcnVal < (UTF32)0x10000) bytesToWrite = 3; else bytesToWrite = 4; const unsigned byteMask = 0xBF; const unsigned byteMark = 0x80; // Once the bits are split out into bytes of UTF8, this is a mask OR-ed // into the first byte, depending on how many bytes follow. static const UTF8 firstByteMark[5] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0 }; // Finally, we write the bytes into ResultBuf. ResultBuf += bytesToWrite; switch (bytesToWrite) { // note: everything falls through. case 4: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; LLVM_FALLTHROUGH; case 3: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; LLVM_FALLTHROUGH; case 2: *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6; LLVM_FALLTHROUGH; case 1: *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]); } // Update the buffer. ResultBuf += bytesToWrite; } /// integer-constant: [C99 6.4.4.1] /// decimal-constant integer-suffix /// octal-constant integer-suffix /// hexadecimal-constant integer-suffix /// binary-literal integer-suffix [GNU, C++1y] /// user-defined-integer-literal: [C++11 lex.ext] /// decimal-literal ud-suffix /// octal-literal ud-suffix /// hexadecimal-literal ud-suffix /// binary-literal ud-suffix [GNU, C++1y] /// decimal-constant: /// nonzero-digit /// decimal-constant digit /// octal-constant: /// 0 /// octal-constant octal-digit /// hexadecimal-constant: /// hexadecimal-prefix hexadecimal-digit /// hexadecimal-constant hexadecimal-digit /// hexadecimal-prefix: one of /// 0x 0X /// binary-literal: /// 0b binary-digit /// 0B binary-digit /// binary-literal binary-digit /// integer-suffix: /// unsigned-suffix [long-suffix] /// unsigned-suffix [long-long-suffix] /// long-suffix [unsigned-suffix] /// long-long-suffix [unsigned-sufix] /// nonzero-digit: /// 1 2 3 4 5 6 7 8 9 /// octal-digit: /// 0 1 2 3 4 5 6 7 /// hexadecimal-digit: /// 0 1 2 3 4 5 6 7 8 9 /// a b c d e f /// A B C D E F /// binary-digit: /// 0 /// 1 /// unsigned-suffix: one of /// u U /// long-suffix: one of /// l L /// long-long-suffix: one of /// ll LL /// /// floating-constant: [C99 6.4.4.2] /// TODO: add rules... /// NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling, SourceLocation TokLoc, Preprocessor &PP) : PP(PP), ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) { // This routine assumes that the range begin/end matches the regex for integer // and FP constants (specifically, the 'pp-number' regex), and assumes that // the byte at "*end" is both valid and not part of the regex. Because of // this, it doesn't have to check for 'overscan' in various places. assert(!isPreprocessingNumberBody(*ThisTokEnd) && "didn't maximally munch?"); s = DigitsBegin = ThisTokBegin; saw_exponent = false; saw_period = false; saw_ud_suffix = false; saw_fixed_point_suffix = false; isLong = false; isUnsigned = false; isLongLong = false; isHalf = false; isFloat = false; isImaginary = false; isFloat16 = false; isFloat128 = false; MicrosoftInteger = 0; isFract = false; isAccum = false; hadError = false; if (*s == '0') { // parse radix ParseNumberStartingWithZero(TokLoc); if (hadError) return; } else { // the first digit is non-zero radix = 10; s = SkipDigits(s); if (s == ThisTokEnd) { // Done. } else { ParseDecimalOrOctalCommon(TokLoc); if (hadError) return; } } SuffixBegin = s; checkSeparator(TokLoc, s, CSK_AfterDigits); // Initial scan to lookahead for fixed point suffix. if (PP.getLangOpts().FixedPoint) { for (const char *c = s; c != ThisTokEnd; ++c) { if (*c == 'r' || *c == 'k' || *c == 'R' || *c == 'K') { saw_fixed_point_suffix = true; break; } } } // Parse the suffix. At this point we can classify whether we have an FP or // integer constant. bool isFPConstant = isFloatingLiteral(); // Loop over all of the characters of the suffix. If we see something bad, // we break out of the loop. for (; s != ThisTokEnd; ++s) { switch (*s) { case 'R': case 'r': if (!PP.getLangOpts().FixedPoint) break; if (isFract || isAccum) break; if (!(saw_period || saw_exponent)) break; isFract = true; continue; case 'K': case 'k': if (!PP.getLangOpts().FixedPoint) break; if (isFract || isAccum) break; if (!(saw_period || saw_exponent)) break; isAccum = true; continue; case 'h': // FP Suffix for "half". case 'H': // OpenCL Extension v1.2 s9.5 - h or H suffix for half type. if (!(PP.getLangOpts().Half || PP.getLangOpts().FixedPoint)) break; if (isIntegerLiteral()) break; // Error for integer constant. if (isHalf || isFloat || isLong) break; // HH, FH, LH invalid. isHalf = true; continue; // Success. case 'f': // FP Suffix for "float" case 'F': if (!isFPConstant) break; // Error for integer constant. if (isHalf || isFloat || isLong || isFloat128) break; // HF, FF, LF, QF invalid. // CUDA host and device may have different _Float16 support, therefore // allows f16 literals to avoid false alarm. // ToDo: more precise check for CUDA. if ((PP.getTargetInfo().hasFloat16Type() || PP.getLangOpts().CUDA) && s + 2 < ThisTokEnd && s[1] == '1' && s[2] == '6') { s += 2; // success, eat up 2 characters. isFloat16 = true; continue; } isFloat = true; continue; // Success. case 'q': // FP Suffix for "__float128" case 'Q': if (!isFPConstant) break; // Error for integer constant. if (isHalf || isFloat || isLong || isFloat128) break; // HQ, FQ, LQ, QQ invalid. isFloat128 = true; continue; // Success. case 'u': case 'U': if (isFPConstant) break; // Error for floating constant. if (isUnsigned) break; // Cannot be repeated. isUnsigned = true; continue; // Success. case 'l': case 'L': if (isLong || isLongLong) break; // Cannot be repeated. if (isHalf || isFloat || isFloat128) break; // LH, LF, LQ invalid. // Check for long long. The L's need to be adjacent and the same case. if (s[1] == s[0]) { assert(s + 1 < ThisTokEnd && "didn't maximally munch?"); if (isFPConstant) break; // long long invalid for floats. isLongLong = true; ++s; // Eat both of them. } else { isLong = true; } continue; // Success. case 'i': case 'I': if (PP.getLangOpts().MicrosoftExt) { if (isLong || isLongLong || MicrosoftInteger) break; if (!isFPConstant) { // Allow i8, i16, i32, and i64. switch (s[1]) { case '8': s += 2; // i8 suffix MicrosoftInteger = 8; break; case '1': if (s[2] == '6') { s += 3; // i16 suffix MicrosoftInteger = 16; } break; case '3': if (s[2] == '2') { s += 3; // i32 suffix MicrosoftInteger = 32; } break; case '6': if (s[2] == '4') { s += 3; // i64 suffix MicrosoftInteger = 64; } break; default: break; } } if (MicrosoftInteger) { assert(s <= ThisTokEnd && "didn't maximally munch?"); break; } } LLVM_FALLTHROUGH; case 'j': case 'J': if (isImaginary) break; // Cannot be repeated. isImaginary = true; continue; // Success. } // If we reached here, there was an error or a ud-suffix. break; } // "i", "if", and "il" are user-defined suffixes in C++1y. if (s != ThisTokEnd || isImaginary) { // FIXME: Don't bother expanding UCNs if !tok.hasUCN(). expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin)); if (isValidUDSuffix(PP.getLangOpts(), UDSuffixBuf)) { if (!isImaginary) { // Any suffix pieces we might have parsed are actually part of the // ud-suffix. isLong = false; isUnsigned = false; isLongLong = false; isFloat = false; isFloat16 = false; isHalf = false; isImaginary = false; MicrosoftInteger = 0; saw_fixed_point_suffix = false; isFract = false; isAccum = false; } saw_ud_suffix = true; return; } if (s != ThisTokEnd) { // Report an error if there are any. PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, SuffixBegin - ThisTokBegin), diag::err_invalid_suffix_constant) << StringRef(SuffixBegin, ThisTokEnd - SuffixBegin) << isFPConstant; hadError = true; } } if (!hadError && saw_fixed_point_suffix) { assert(isFract || isAccum); } } /// ParseDecimalOrOctalCommon - This method is called for decimal or octal /// numbers. It issues an error for illegal digits, and handles floating point /// parsing. If it detects a floating point number, the radix is set to 10. void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){ assert((radix == 8 || radix == 10) && "Unexpected radix"); // If we have a hex digit other than 'e' (which denotes a FP exponent) then // the code is using an incorrect base. if (isHexDigit(*s) && *s != 'e' && *s != 'E' && !isValidUDSuffix(PP.getLangOpts(), StringRef(s, ThisTokEnd - s))) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), diag::err_invalid_digit) << StringRef(s, 1) << (radix == 8 ? 1 : 0); hadError = true; return; } if (*s == '.') { checkSeparator(TokLoc, s, CSK_AfterDigits); s++; radix = 10; saw_period = true; checkSeparator(TokLoc, s, CSK_BeforeDigits); s = SkipDigits(s); // Skip suffix. } if (*s == 'e' || *s == 'E') { // exponent checkSeparator(TokLoc, s, CSK_AfterDigits); const char *Exponent = s; s++; radix = 10; saw_exponent = true; if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign const char *first_non_digit = SkipDigits(s); if (containsDigits(s, first_non_digit)) { checkSeparator(TokLoc, s, CSK_BeforeDigits); s = first_non_digit; } else { if (!hadError) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), diag::err_exponent_has_no_digits); hadError = true; } return; } } } /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved /// suffixes as ud-suffixes, because the diagnostic experience is better if we /// treat it as an invalid suffix. bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix) { if (!LangOpts.CPlusPlus11 || Suffix.empty()) return false; // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid. if (Suffix[0] == '_') return true; // In C++11, there are no library suffixes. if (!LangOpts.CPlusPlus14) return false; // In C++14, "s", "h", "min", "ms", "us", and "ns" are used in the library. // Per tweaked N3660, "il", "i", and "if" are also used in the library. // In C++2a "d" and "y" are used in the library. return llvm::StringSwitch(Suffix) .Cases("h", "min", "s", true) .Cases("ms", "us", "ns", true) .Cases("il", "i", "if", true) .Cases("d", "y", LangOpts.CPlusPlus2a) .Default(false); } void NumericLiteralParser::checkSeparator(SourceLocation TokLoc, const char *Pos, CheckSeparatorKind IsAfterDigits) { if (IsAfterDigits == CSK_AfterDigits) { if (Pos == ThisTokBegin) return; --Pos; } else if (Pos == ThisTokEnd) return; if (isDigitSeparator(*Pos)) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin), diag::err_digit_separator_not_between_digits) << IsAfterDigits; hadError = true; } } /// ParseNumberStartingWithZero - This method is called when the first character /// of the number is found to be a zero. This means it is either an octal /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or /// a floating point number (01239.123e4). Eat the prefix, determining the /// radix etc. void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) { assert(s[0] == '0' && "Invalid method call"); s++; int c1 = s[0]; // Handle a hex number like 0x1234. if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) { s++; assert(s < ThisTokEnd && "didn't maximally munch?"); radix = 16; DigitsBegin = s; s = SkipHexDigits(s); bool HasSignificandDigits = containsDigits(DigitsBegin, s); if (s == ThisTokEnd) { // Done. } else if (*s == '.') { s++; saw_period = true; const char *floatDigitsBegin = s; s = SkipHexDigits(s); if (containsDigits(floatDigitsBegin, s)) HasSignificandDigits = true; if (HasSignificandDigits) checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits); } if (!HasSignificandDigits) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin), diag::err_hex_constant_requires) << PP.getLangOpts().CPlusPlus << 1; hadError = true; return; } // A binary exponent can appear with or with a '.'. If dotted, the // binary exponent is required. if (*s == 'p' || *s == 'P') { checkSeparator(TokLoc, s, CSK_AfterDigits); const char *Exponent = s; s++; saw_exponent = true; if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign const char *first_non_digit = SkipDigits(s); if (!containsDigits(s, first_non_digit)) { if (!hadError) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, Exponent-ThisTokBegin), diag::err_exponent_has_no_digits); hadError = true; } return; } checkSeparator(TokLoc, s, CSK_BeforeDigits); s = first_non_digit; if (!PP.getLangOpts().HexFloats) PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus ? diag::ext_hex_literal_invalid : diag::ext_hex_constant_invalid); else if (PP.getLangOpts().CPlusPlus17) PP.Diag(TokLoc, diag::warn_cxx17_hex_literal); } else if (saw_period) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin), diag::err_hex_constant_requires) << PP.getLangOpts().CPlusPlus << 0; hadError = true; } return; } // Handle simple binary numbers 0b01010 if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) { // 0b101010 is a C++1y / GCC extension. PP.Diag(TokLoc, PP.getLangOpts().CPlusPlus14 ? diag::warn_cxx11_compat_binary_literal : PP.getLangOpts().CPlusPlus ? diag::ext_binary_literal_cxx14 : diag::ext_binary_literal); ++s; assert(s < ThisTokEnd && "didn't maximally munch?"); radix = 2; DigitsBegin = s; s = SkipBinaryDigits(s); if (s == ThisTokEnd) { // Done. } else if (isHexDigit(*s) && !isValidUDSuffix(PP.getLangOpts(), StringRef(s, ThisTokEnd - s))) { PP.Diag(PP.AdvanceToTokenCharacter(TokLoc, s-ThisTokBegin), diag::err_invalid_digit) << StringRef(s, 1) << 2; hadError = true; } // Other suffixes will be diagnosed by the caller. return; } // For now, the radix is set to 8. If we discover that we have a // floating point constant, the radix will change to 10. Octal floating // point constants are not permitted (only decimal and hexadecimal). radix = 8; DigitsBegin = s; s = SkipOctalDigits(s); if (s == ThisTokEnd) return; // Done, simple octal number like 01234 // If we have some other non-octal digit that *is* a decimal digit, see if // this is part of a floating point number like 094.123 or 09e1. if (isDigit(*s)) { const char *EndDecimal = SkipDigits(s); if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') { s = EndDecimal; radix = 10; } } ParseDecimalOrOctalCommon(TokLoc); } static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) { switch (Radix) { case 2: return NumDigits <= 64; case 8: return NumDigits <= 64 / 3; // Digits are groups of 3 bits. case 10: return NumDigits <= 19; // floor(log10(2^64)) case 16: return NumDigits <= 64 / 4; // Digits are groups of 4 bits. default: llvm_unreachable("impossible Radix"); } } /// GetIntegerValue - Convert this numeric literal value to an APInt that /// matches Val's input width. If there is an overflow, set Val to the low bits /// of the result and return true. Otherwise, return false. bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) { // Fast path: Compute a conservative bound on the maximum number of // bits per digit in this radix. If we can't possibly overflow a // uint64 based on that bound then do the simple conversion to // integer. This avoids the expensive overflow checking below, and // handles the common cases that matter (small decimal integers and // hex/octal values which don't overflow). const unsigned NumDigits = SuffixBegin - DigitsBegin; if (alwaysFitsInto64Bits(radix, NumDigits)) { uint64_t N = 0; for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr) if (!isDigitSeparator(*Ptr)) N = N * radix + llvm::hexDigitValue(*Ptr); // This will truncate the value to Val's input width. Simply check // for overflow by comparing. Val = N; return Val.getZExtValue() != N; } Val = 0; const char *Ptr = DigitsBegin; llvm::APInt RadixVal(Val.getBitWidth(), radix); llvm::APInt CharVal(Val.getBitWidth(), 0); llvm::APInt OldVal = Val; bool OverflowOccurred = false; while (Ptr < SuffixBegin) { if (isDigitSeparator(*Ptr)) { ++Ptr; continue; } unsigned C = llvm::hexDigitValue(*Ptr++); // If this letter is out of bound for this radix, reject it. assert(C < radix && "NumericLiteralParser ctor should have rejected this"); CharVal = C; // Add the digit to the value in the appropriate radix. If adding in digits // made the value smaller, then this overflowed. OldVal = Val; // Multiply by radix, did overflow occur on the multiply? Val *= RadixVal; OverflowOccurred |= Val.udiv(RadixVal) != OldVal; // Add value, did overflow occur on the value? // (a + b) ult b <=> overflow Val += CharVal; OverflowOccurred |= Val.ult(CharVal); } return OverflowOccurred; } llvm::APFloat::opStatus NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) { using llvm::APFloat; unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin); llvm::SmallString<16> Buffer; StringRef Str(ThisTokBegin, n); if (Str.find('\'') != StringRef::npos) { Buffer.reserve(n); std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer), &isDigitSeparator); Str = Buffer; } auto StatusOrErr = Result.convertFromString(Str, APFloat::rmNearestTiesToEven); - assert(StatusOrErr && "Invalid floating point representation"); - return StatusOrErr ? *StatusOrErr : APFloat::opInvalidOp; + if (!StatusOrErr) { + assert(false && "Invalid floating point representation"); + return APFloat::opInvalidOp; + } + return *StatusOrErr; } static inline bool IsExponentPart(char c) { return c == 'p' || c == 'P' || c == 'e' || c == 'E'; } bool NumericLiteralParser::GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale) { assert(radix == 16 || radix == 10); // Find how many digits are needed to store the whole literal. unsigned NumDigits = SuffixBegin - DigitsBegin; if (saw_period) --NumDigits; // Initial scan of the exponent if it exists bool ExpOverflowOccurred = false; bool NegativeExponent = false; const char *ExponentBegin; uint64_t Exponent = 0; int64_t BaseShift = 0; if (saw_exponent) { const char *Ptr = DigitsBegin; while (!IsExponentPart(*Ptr)) ++Ptr; ExponentBegin = Ptr; ++Ptr; NegativeExponent = *Ptr == '-'; if (NegativeExponent) ++Ptr; unsigned NumExpDigits = SuffixBegin - Ptr; if (alwaysFitsInto64Bits(radix, NumExpDigits)) { llvm::StringRef ExpStr(Ptr, NumExpDigits); llvm::APInt ExpInt(/*numBits=*/64, ExpStr, /*radix=*/10); Exponent = ExpInt.getZExtValue(); } else { ExpOverflowOccurred = true; } if (NegativeExponent) BaseShift -= Exponent; else BaseShift += Exponent; } // Number of bits needed for decimal literal is // ceil(NumDigits * log2(10)) Integral part // + Scale Fractional part // + ceil(Exponent * log2(10)) Exponent // -------------------------------------------------- // ceil((NumDigits + Exponent) * log2(10)) + Scale // // But for simplicity in handling integers, we can round up log2(10) to 4, // making: // 4 * (NumDigits + Exponent) + Scale // // Number of digits needed for hexadecimal literal is // 4 * NumDigits Integral part // + Scale Fractional part // + Exponent Exponent // -------------------------------------------------- // (4 * NumDigits) + Scale + Exponent uint64_t NumBitsNeeded; if (radix == 10) NumBitsNeeded = 4 * (NumDigits + Exponent) + Scale; else NumBitsNeeded = 4 * NumDigits + Exponent + Scale; if (NumBitsNeeded > std::numeric_limits::max()) ExpOverflowOccurred = true; llvm::APInt Val(static_cast(NumBitsNeeded), 0, /*isSigned=*/false); bool FoundDecimal = false; int64_t FractBaseShift = 0; const char *End = saw_exponent ? ExponentBegin : SuffixBegin; for (const char *Ptr = DigitsBegin; Ptr < End; ++Ptr) { if (*Ptr == '.') { FoundDecimal = true; continue; } // Normal reading of an integer unsigned C = llvm::hexDigitValue(*Ptr); assert(C < radix && "NumericLiteralParser ctor should have rejected this"); Val *= radix; Val += C; if (FoundDecimal) // Keep track of how much we will need to adjust this value by from the // number of digits past the radix point. --FractBaseShift; } // For a radix of 16, we will be multiplying by 2 instead of 16. if (radix == 16) FractBaseShift *= 4; BaseShift += FractBaseShift; Val <<= Scale; uint64_t Base = (radix == 16) ? 2 : 10; if (BaseShift > 0) { for (int64_t i = 0; i < BaseShift; ++i) { Val *= Base; } } else if (BaseShift < 0) { for (int64_t i = BaseShift; i < 0 && !Val.isNullValue(); ++i) Val = Val.udiv(Base); } bool IntOverflowOccurred = false; auto MaxVal = llvm::APInt::getMaxValue(StoreVal.getBitWidth()); if (Val.getBitWidth() > StoreVal.getBitWidth()) { IntOverflowOccurred |= Val.ugt(MaxVal.zext(Val.getBitWidth())); StoreVal = Val.trunc(StoreVal.getBitWidth()); } else if (Val.getBitWidth() < StoreVal.getBitWidth()) { IntOverflowOccurred |= Val.zext(MaxVal.getBitWidth()).ugt(MaxVal); StoreVal = Val.zext(StoreVal.getBitWidth()); } else { StoreVal = Val; } return IntOverflowOccurred || ExpOverflowOccurred; } /// \verbatim /// user-defined-character-literal: [C++11 lex.ext] /// character-literal ud-suffix /// ud-suffix: /// identifier /// character-literal: [C++11 lex.ccon] /// ' c-char-sequence ' /// u' c-char-sequence ' /// U' c-char-sequence ' /// L' c-char-sequence ' /// u8' c-char-sequence ' [C++1z lex.ccon] /// c-char-sequence: /// c-char /// c-char-sequence c-char /// c-char: /// any member of the source character set except the single-quote ', /// backslash \, or new-line character /// escape-sequence /// universal-character-name /// escape-sequence: /// simple-escape-sequence /// octal-escape-sequence /// hexadecimal-escape-sequence /// simple-escape-sequence: /// one of \' \" \? \\ \a \b \f \n \r \t \v /// octal-escape-sequence: /// \ octal-digit /// \ octal-digit octal-digit /// \ octal-digit octal-digit octal-digit /// hexadecimal-escape-sequence: /// \x hexadecimal-digit /// hexadecimal-escape-sequence hexadecimal-digit /// universal-character-name: [C++11 lex.charset] /// \u hex-quad /// \U hex-quad hex-quad /// hex-quad: /// hex-digit hex-digit hex-digit hex-digit /// \endverbatim /// CharLiteralParser::CharLiteralParser(const char *begin, const char *end, SourceLocation Loc, Preprocessor &PP, tok::TokenKind kind) { // At this point we know that the character matches the regex "(L|u|U)?'.*'". HadError = false; Kind = kind; const char *TokBegin = begin; // Skip over wide character determinant. if (Kind != tok::char_constant) ++begin; if (Kind == tok::utf8_char_constant) ++begin; // Skip over the entry quote. assert(begin[0] == '\'' && "Invalid token lexed"); ++begin; // Remove an optional ud-suffix. if (end[-1] != '\'') { const char *UDSuffixEnd = end; do { --end; } while (end[-1] != '\''); // FIXME: Don't bother with this if !tok.hasUCN(). expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end)); UDSuffixOffset = end - TokBegin; } // Trim the ending quote. assert(end != begin && "Invalid token lexed"); --end; // FIXME: The "Value" is an uint64_t so we can handle char literals of // up to 64-bits. // FIXME: This extensively assumes that 'char' is 8-bits. assert(PP.getTargetInfo().getCharWidth() == 8 && "Assumes char is 8 bits"); assert(PP.getTargetInfo().getIntWidth() <= 64 && (PP.getTargetInfo().getIntWidth() & 7) == 0 && "Assumes sizeof(int) on target is <= 64 and a multiple of char"); assert(PP.getTargetInfo().getWCharWidth() <= 64 && "Assumes sizeof(wchar) on target is <= 64"); SmallVector codepoint_buffer; codepoint_buffer.resize(end - begin); uint32_t *buffer_begin = &codepoint_buffer.front(); uint32_t *buffer_end = buffer_begin + codepoint_buffer.size(); // Unicode escapes representing characters that cannot be correctly // represented in a single code unit are disallowed in character literals // by this implementation. uint32_t largest_character_for_kind; if (tok::wide_char_constant == Kind) { largest_character_for_kind = 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth()); } else if (tok::utf8_char_constant == Kind) { largest_character_for_kind = 0x7F; } else if (tok::utf16_char_constant == Kind) { largest_character_for_kind = 0xFFFF; } else if (tok::utf32_char_constant == Kind) { largest_character_for_kind = 0x10FFFF; } else { largest_character_for_kind = 0x7Fu; } while (begin != end) { // Is this a span of non-escape characters? if (begin[0] != '\\') { char const *start = begin; do { ++begin; } while (begin != end && *begin != '\\'); char const *tmp_in_start = start; uint32_t *tmp_out_start = buffer_begin; llvm::ConversionResult res = llvm::ConvertUTF8toUTF32(reinterpret_cast(&start), reinterpret_cast(begin), &buffer_begin, buffer_end, llvm::strictConversion); if (res != llvm::conversionOK) { // If we see bad encoding for unprefixed character literals, warn and // simply copy the byte values, for compatibility with gcc and // older versions of clang. bool NoErrorOnBadEncoding = isAscii(); unsigned Msg = diag::err_bad_character_encoding; if (NoErrorOnBadEncoding) Msg = diag::warn_bad_character_encoding; PP.Diag(Loc, Msg); if (NoErrorOnBadEncoding) { start = tmp_in_start; buffer_begin = tmp_out_start; for (; start != begin; ++start, ++buffer_begin) *buffer_begin = static_cast(*start); } else { HadError = true; } } else { for (; tmp_out_start < buffer_begin; ++tmp_out_start) { if (*tmp_out_start > largest_character_for_kind) { HadError = true; PP.Diag(Loc, diag::err_character_too_large); } } } continue; } // Is this a Universal Character Name escape? if (begin[1] == 'u' || begin[1] == 'U') { unsigned short UcnLen = 0; if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen, FullSourceLoc(Loc, PP.getSourceManager()), &PP.getDiagnostics(), PP.getLangOpts(), true)) { HadError = true; } else if (*buffer_begin > largest_character_for_kind) { HadError = true; PP.Diag(Loc, diag::err_character_too_large); } ++buffer_begin; continue; } unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo()); uint64_t result = ProcessCharEscape(TokBegin, begin, end, HadError, FullSourceLoc(Loc,PP.getSourceManager()), CharWidth, &PP.getDiagnostics(), PP.getLangOpts()); *buffer_begin++ = result; } unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front(); if (NumCharsSoFar > 1) { if (isWide()) PP.Diag(Loc, diag::warn_extraneous_char_constant); else if (isAscii() && NumCharsSoFar == 4) PP.Diag(Loc, diag::ext_four_char_character_literal); else if (isAscii()) PP.Diag(Loc, diag::ext_multichar_character_literal); else PP.Diag(Loc, diag::err_multichar_utf_character_literal); IsMultiChar = true; } else { IsMultiChar = false; } llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0); // Narrow character literals act as though their value is concatenated // in this implementation, but warn on overflow. bool multi_char_too_long = false; if (isAscii() && isMultiChar()) { LitVal = 0; for (size_t i = 0; i < NumCharsSoFar; ++i) { // check for enough leading zeros to shift into multi_char_too_long |= (LitVal.countLeadingZeros() < 8); LitVal <<= 8; LitVal = LitVal + (codepoint_buffer[i] & 0xFF); } } else if (NumCharsSoFar > 0) { // otherwise just take the last character LitVal = buffer_begin[-1]; } if (!HadError && multi_char_too_long) { PP.Diag(Loc, diag::warn_char_constant_too_large); } // Transfer the value from APInt to uint64_t Value = LitVal.getZExtValue(); // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1") // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple // character constants are not sign extended in the this implementation: // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC. if (isAscii() && NumCharsSoFar == 1 && (Value & 128) && PP.getLangOpts().CharIsSigned) Value = (signed char)Value; } /// \verbatim /// string-literal: [C++0x lex.string] /// encoding-prefix " [s-char-sequence] " /// encoding-prefix R raw-string /// encoding-prefix: /// u8 /// u /// U /// L /// s-char-sequence: /// s-char /// s-char-sequence s-char /// s-char: /// any member of the source character set except the double-quote ", /// backslash \, or new-line character /// escape-sequence /// universal-character-name /// raw-string: /// " d-char-sequence ( r-char-sequence ) d-char-sequence " /// r-char-sequence: /// r-char /// r-char-sequence r-char /// r-char: /// any member of the source character set, except a right parenthesis ) /// followed by the initial d-char-sequence (which may be empty) /// followed by a double quote ". /// d-char-sequence: /// d-char /// d-char-sequence d-char /// d-char: /// any member of the basic source character set except: /// space, the left parenthesis (, the right parenthesis ), /// the backslash \, and the control characters representing horizontal /// tab, vertical tab, form feed, and newline. /// escape-sequence: [C++0x lex.ccon] /// simple-escape-sequence /// octal-escape-sequence /// hexadecimal-escape-sequence /// simple-escape-sequence: /// one of \' \" \? \\ \a \b \f \n \r \t \v /// octal-escape-sequence: /// \ octal-digit /// \ octal-digit octal-digit /// \ octal-digit octal-digit octal-digit /// hexadecimal-escape-sequence: /// \x hexadecimal-digit /// hexadecimal-escape-sequence hexadecimal-digit /// universal-character-name: /// \u hex-quad /// \U hex-quad hex-quad /// hex-quad: /// hex-digit hex-digit hex-digit hex-digit /// \endverbatim /// StringLiteralParser:: StringLiteralParser(ArrayRef StringToks, Preprocessor &PP, bool Complain) : SM(PP.getSourceManager()), Features(PP.getLangOpts()), Target(PP.getTargetInfo()), Diags(Complain ? &PP.getDiagnostics() :nullptr), MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown), ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) { init(StringToks); } void StringLiteralParser::init(ArrayRef StringToks){ // The literal token may have come from an invalid source location (e.g. due // to a PCH error), in which case the token length will be 0. if (StringToks.empty() || StringToks[0].getLength() < 2) return DiagnoseLexingError(SourceLocation()); // Scan all of the string portions, remember the max individual token length, // computing a bound on the concatenated string length, and see whether any // piece is a wide-string. If any of the string portions is a wide-string // literal, the result is a wide-string literal [C99 6.4.5p4]. assert(!StringToks.empty() && "expected at least one token"); MaxTokenLength = StringToks[0].getLength(); assert(StringToks[0].getLength() >= 2 && "literal token is invalid!"); SizeBound = StringToks[0].getLength()-2; // -2 for "". Kind = StringToks[0].getKind(); hadError = false; // Implement Translation Phase #6: concatenation of string literals /// (C99 5.1.1.2p1). The common case is only one string fragment. for (unsigned i = 1; i != StringToks.size(); ++i) { if (StringToks[i].getLength() < 2) return DiagnoseLexingError(StringToks[i].getLocation()); // The string could be shorter than this if it needs cleaning, but this is a // reasonable bound, which is all we need. assert(StringToks[i].getLength() >= 2 && "literal token is invalid!"); SizeBound += StringToks[i].getLength()-2; // -2 for "". // Remember maximum string piece length. if (StringToks[i].getLength() > MaxTokenLength) MaxTokenLength = StringToks[i].getLength(); // Remember if we see any wide or utf-8/16/32 strings. // Also check for illegal concatenations. if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) { if (isAscii()) { Kind = StringToks[i].getKind(); } else { if (Diags) Diags->Report(StringToks[i].getLocation(), diag::err_unsupported_string_concat); hadError = true; } } } // Include space for the null terminator. ++SizeBound; // TODO: K&R warning: "traditional C rejects string constant concatenation" // Get the width in bytes of char/wchar_t/char16_t/char32_t CharByteWidth = getCharWidth(Kind, Target); assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple"); CharByteWidth /= 8; // The output buffer size needs to be large enough to hold wide characters. // This is a worst-case assumption which basically corresponds to L"" "long". SizeBound *= CharByteWidth; // Size the temporary buffer to hold the result string data. ResultBuf.resize(SizeBound); // Likewise, but for each string piece. SmallString<512> TokenBuf; TokenBuf.resize(MaxTokenLength); // Loop over all the strings, getting their spelling, and expanding them to // wide strings as appropriate. ResultPtr = &ResultBuf[0]; // Next byte to fill in. Pascal = false; SourceLocation UDSuffixTokLoc; for (unsigned i = 0, e = StringToks.size(); i != e; ++i) { const char *ThisTokBuf = &TokenBuf[0]; // Get the spelling of the token, which eliminates trigraphs, etc. We know // that ThisTokBuf points to a buffer that is big enough for the whole token // and 'spelled' tokens can only shrink. bool StringInvalid = false; unsigned ThisTokLen = Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features, &StringInvalid); if (StringInvalid) return DiagnoseLexingError(StringToks[i].getLocation()); const char *ThisTokBegin = ThisTokBuf; const char *ThisTokEnd = ThisTokBuf+ThisTokLen; // Remove an optional ud-suffix. if (ThisTokEnd[-1] != '"') { const char *UDSuffixEnd = ThisTokEnd; do { --ThisTokEnd; } while (ThisTokEnd[-1] != '"'); StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd); if (UDSuffixBuf.empty()) { if (StringToks[i].hasUCN()) expandUCNs(UDSuffixBuf, UDSuffix); else UDSuffixBuf.assign(UDSuffix); UDSuffixToken = i; UDSuffixOffset = ThisTokEnd - ThisTokBuf; UDSuffixTokLoc = StringToks[i].getLocation(); } else { SmallString<32> ExpandedUDSuffix; if (StringToks[i].hasUCN()) { expandUCNs(ExpandedUDSuffix, UDSuffix); UDSuffix = ExpandedUDSuffix; } // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the // result of a concatenation involving at least one user-defined-string- // literal, all the participating user-defined-string-literals shall // have the same ud-suffix. if (UDSuffixBuf != UDSuffix) { if (Diags) { SourceLocation TokLoc = StringToks[i].getLocation(); Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix) << UDSuffixBuf << UDSuffix << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc) << SourceRange(TokLoc, TokLoc); } hadError = true; } } } // Strip the end quote. --ThisTokEnd; // TODO: Input character set mapping support. // Skip marker for wide or unicode strings. if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') { ++ThisTokBuf; // Skip 8 of u8 marker for utf8 strings. if (ThisTokBuf[0] == '8') ++ThisTokBuf; } // Check for raw string if (ThisTokBuf[0] == 'R') { ThisTokBuf += 2; // skip R" const char *Prefix = ThisTokBuf; while (ThisTokBuf[0] != '(') ++ThisTokBuf; ++ThisTokBuf; // skip '(' // Remove same number of characters from the end ThisTokEnd -= ThisTokBuf - Prefix; assert(ThisTokEnd >= ThisTokBuf && "malformed raw string literal"); // C++14 [lex.string]p4: A source-file new-line in a raw string literal // results in a new-line in the resulting execution string-literal. StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf); while (!RemainingTokenSpan.empty()) { // Split the string literal on \r\n boundaries. size_t CRLFPos = RemainingTokenSpan.find("\r\n"); StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos); StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos); // Copy everything before the \r\n sequence into the string literal. if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF)) hadError = true; // Point into the \n inside the \r\n sequence and operate on the // remaining portion of the literal. RemainingTokenSpan = AfterCRLF.substr(1); } } else { if (ThisTokBuf[0] != '"') { // The file may have come from PCH and then changed after loading the // PCH; Fail gracefully. return DiagnoseLexingError(StringToks[i].getLocation()); } ++ThisTokBuf; // skip " // Check if this is a pascal string if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd && ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') { // If the \p sequence is found in the first token, we have a pascal string // Otherwise, if we already have a pascal string, ignore the first \p if (i == 0) { ++ThisTokBuf; Pascal = true; } else if (Pascal) ThisTokBuf += 2; } while (ThisTokBuf != ThisTokEnd) { // Is this a span of non-escape characters? if (ThisTokBuf[0] != '\\') { const char *InStart = ThisTokBuf; do { ++ThisTokBuf; } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\'); // Copy the character span over. if (CopyStringFragment(StringToks[i], ThisTokBegin, StringRef(InStart, ThisTokBuf - InStart))) hadError = true; continue; } // Is this a Universal Character Name escape? if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') { EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, ResultPtr, hadError, FullSourceLoc(StringToks[i].getLocation(), SM), CharByteWidth, Diags, Features); continue; } // Otherwise, this is a non-UCN escape character. Process it. unsigned ResultChar = ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError, FullSourceLoc(StringToks[i].getLocation(), SM), CharByteWidth*8, Diags, Features); if (CharByteWidth == 4) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. llvm::UTF32 *ResultWidePtr = reinterpret_cast(ResultPtr); *ResultWidePtr = ResultChar; ResultPtr += 4; } else if (CharByteWidth == 2) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. llvm::UTF16 *ResultWidePtr = reinterpret_cast(ResultPtr); *ResultWidePtr = ResultChar & 0xFFFF; ResultPtr += 2; } else { assert(CharByteWidth == 1 && "Unexpected char width"); *ResultPtr++ = ResultChar & 0xFF; } } } } if (Pascal) { if (CharByteWidth == 4) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. llvm::UTF32 *ResultWidePtr = reinterpret_cast(ResultBuf.data()); ResultWidePtr[0] = GetNumStringChars() - 1; } else if (CharByteWidth == 2) { // FIXME: Make the type of the result buffer correct instead of // using reinterpret_cast. llvm::UTF16 *ResultWidePtr = reinterpret_cast(ResultBuf.data()); ResultWidePtr[0] = GetNumStringChars() - 1; } else { assert(CharByteWidth == 1 && "Unexpected char width"); ResultBuf[0] = GetNumStringChars() - 1; } // Verify that pascal strings aren't too large. if (GetStringLength() > 256) { if (Diags) Diags->Report(StringToks.front().getLocation(), diag::err_pascal_string_too_long) << SourceRange(StringToks.front().getLocation(), StringToks.back().getLocation()); hadError = true; return; } } else if (Diags) { // Complain if this string literal has too many characters. unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509; if (GetNumStringChars() > MaxChars) Diags->Report(StringToks.front().getLocation(), diag::ext_string_too_long) << GetNumStringChars() << MaxChars << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0) << SourceRange(StringToks.front().getLocation(), StringToks.back().getLocation()); } } static const char *resyncUTF8(const char *Err, const char *End) { if (Err == End) return End; End = Err + std::min(llvm::getNumBytesForUTF8(*Err), End-Err); while (++Err != End && (*Err & 0xC0) == 0x80) ; return Err; } /// This function copies from Fragment, which is a sequence of bytes /// within Tok's contents (which begin at TokBegin) into ResultPtr. /// Performs widening for multi-byte characters. bool StringLiteralParser::CopyStringFragment(const Token &Tok, const char *TokBegin, StringRef Fragment) { const llvm::UTF8 *ErrorPtrTmp; if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp)) return false; // If we see bad encoding for unprefixed string literals, warn and // simply copy the byte values, for compatibility with gcc and older // versions of clang. bool NoErrorOnBadEncoding = isAscii(); if (NoErrorOnBadEncoding) { memcpy(ResultPtr, Fragment.data(), Fragment.size()); ResultPtr += Fragment.size(); } if (Diags) { const char *ErrorPtr = reinterpret_cast(ErrorPtrTmp); FullSourceLoc SourceLoc(Tok.getLocation(), SM); const DiagnosticBuilder &Builder = Diag(Diags, Features, SourceLoc, TokBegin, ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()), NoErrorOnBadEncoding ? diag::warn_bad_string_encoding : diag::err_bad_string_encoding); const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end()); StringRef NextFragment(NextStart, Fragment.end()-NextStart); // Decode into a dummy buffer. SmallString<512> Dummy; Dummy.reserve(Fragment.size() * CharByteWidth); char *Ptr = Dummy.data(); while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) { const char *ErrorPtr = reinterpret_cast(ErrorPtrTmp); NextStart = resyncUTF8(ErrorPtr, Fragment.end()); Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin, ErrorPtr, NextStart); NextFragment = StringRef(NextStart, Fragment.end()-NextStart); } } return !NoErrorOnBadEncoding; } void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) { hadError = true; if (Diags) Diags->Report(Loc, diag::err_lexing_string); } /// getOffsetOfStringByte - This function returns the offset of the /// specified byte of the string data represented by Token. This handles /// advancing over escape sequences in the string. unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok, unsigned ByteNo) const { // Get the spelling of the token. SmallString<32> SpellingBuffer; SpellingBuffer.resize(Tok.getLength()); bool StringInvalid = false; const char *SpellingPtr = &SpellingBuffer[0]; unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features, &StringInvalid); if (StringInvalid) return 0; const char *SpellingStart = SpellingPtr; const char *SpellingEnd = SpellingPtr+TokLen; // Handle UTF-8 strings just like narrow strings. if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8') SpellingPtr += 2; assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' && SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet"); // For raw string literals, this is easy. if (SpellingPtr[0] == 'R') { assert(SpellingPtr[1] == '"' && "Should be a raw string literal!"); // Skip 'R"'. SpellingPtr += 2; while (*SpellingPtr != '(') { ++SpellingPtr; assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal"); } // Skip '('. ++SpellingPtr; return SpellingPtr - SpellingStart + ByteNo; } // Skip over the leading quote assert(SpellingPtr[0] == '"' && "Should be a string literal!"); ++SpellingPtr; // Skip over bytes until we find the offset we're looking for. while (ByteNo) { assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!"); // Step over non-escapes simply. if (*SpellingPtr != '\\') { ++SpellingPtr; --ByteNo; continue; } // Otherwise, this is an escape character. Advance over it. bool HadError = false; if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') { const char *EscapePtr = SpellingPtr; unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd, 1, Features, HadError); if (Len > ByteNo) { // ByteNo is somewhere within the escape sequence. SpellingPtr = EscapePtr; break; } ByteNo -= Len; } else { ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError, FullSourceLoc(Tok.getLocation(), SM), CharByteWidth*8, Diags, Features); --ByteNo; } assert(!HadError && "This method isn't valid on erroneous strings"); } return SpellingPtr-SpellingStart; } /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved /// suffixes as ud-suffixes, because the diagnostic experience is better if we /// treat it as an invalid suffix. bool StringLiteralParser::isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix) { return NumericLiteralParser::isValidUDSuffix(LangOpts, Suffix) || Suffix == "sv"; } diff --git a/llvm/lib/Support/APFloat.cpp b/llvm/lib/Support/APFloat.cpp index f6999a6f236d..d26c5e6cd2e6 100644 --- a/llvm/lib/Support/APFloat.cpp +++ b/llvm/lib/Support/APFloat.cpp @@ -1,4596 +1,4598 @@ //===-- APFloat.cpp - Implement APFloat class -----------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements a class to represent arbitrary precision floating // point values and provide a variety of arithmetic operations on them. // //===----------------------------------------------------------------------===// #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/FoldingSet.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Config/llvm-config.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Error.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/raw_ostream.h" #include #include #define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \ do { \ if (usesLayout(getSemantics())) \ return U.IEEE.METHOD_CALL; \ if (usesLayout(getSemantics())) \ return U.Double.METHOD_CALL; \ llvm_unreachable("Unexpected semantics"); \ } while (false) using namespace llvm; /// A macro used to combine two fcCategory enums into one key which can be used /// in a switch statement to classify how the interaction of two APFloat's /// categories affects an operation. /// /// TODO: If clang source code is ever allowed to use constexpr in its own /// codebase, change this into a static inline function. #define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs)) /* Assumed in hexadecimal significand parsing, and conversion to hexadecimal strings. */ static_assert(APFloatBase::integerPartWidth % 4 == 0, "Part width must be divisible by 4!"); namespace llvm { /* Represents floating point arithmetic semantics. */ struct fltSemantics { /* The largest E such that 2^E is representable; this matches the definition of IEEE 754. */ APFloatBase::ExponentType maxExponent; /* The smallest E such that 2^E is a normalized number; this matches the definition of IEEE 754. */ APFloatBase::ExponentType minExponent; /* Number of bits in the significand. This includes the integer bit. */ unsigned int precision; /* Number of bits actually used in the semantics. */ unsigned int sizeInBits; }; static const fltSemantics semIEEEhalf = {15, -14, 11, 16}; static const fltSemantics semIEEEsingle = {127, -126, 24, 32}; static const fltSemantics semIEEEdouble = {1023, -1022, 53, 64}; static const fltSemantics semIEEEquad = {16383, -16382, 113, 128}; static const fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80}; static const fltSemantics semBogus = {0, 0, 0, 0}; /* The IBM double-double semantics. Such a number consists of a pair of IEEE 64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal, (double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo. Therefore it has two 53-bit mantissa parts that aren't necessarily adjacent to each other, and two 11-bit exponents. Note: we need to make the value different from semBogus as otherwise an unsafe optimization may collapse both values to a single address, and we heavily rely on them having distinct addresses. */ static const fltSemantics semPPCDoubleDouble = {-1, 0, 0, 0}; /* These are legacy semantics for the fallback, inaccrurate implementation of IBM double-double, if the accurate semPPCDoubleDouble doesn't handle the operation. It's equivalent to having an IEEE number with consecutive 106 bits of mantissa and 11 bits of exponent. It's not equivalent to IBM double-double. For example, a legit IBM double-double, 1 + epsilon: 1 + epsilon = 1 + (1 >> 1076) is not representable by a consecutive 106 bits of mantissa. Currently, these semantics are used in the following way: semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) -> (64-bit APInt, 64-bit APInt) -> (128-bit APInt) -> semPPCDoubleDoubleLegacy -> IEEE operations We use bitcastToAPInt() to get the bit representation (in APInt) of the underlying IEEEdouble, then use the APInt constructor to construct the legacy IEEE float. TODO: Implement all operations in semPPCDoubleDouble, and delete these semantics. */ static const fltSemantics semPPCDoubleDoubleLegacy = {1023, -1022 + 53, 53 + 53, 128}; const llvm::fltSemantics &APFloatBase::EnumToSemantics(Semantics S) { switch (S) { case S_IEEEhalf: return IEEEhalf(); case S_IEEEsingle: return IEEEsingle(); case S_IEEEdouble: return IEEEdouble(); case S_x87DoubleExtended: return x87DoubleExtended(); case S_IEEEquad: return IEEEquad(); case S_PPCDoubleDouble: return PPCDoubleDouble(); } llvm_unreachable("Unrecognised floating semantics"); } APFloatBase::Semantics APFloatBase::SemanticsToEnum(const llvm::fltSemantics &Sem) { if (&Sem == &llvm::APFloat::IEEEhalf()) return S_IEEEhalf; else if (&Sem == &llvm::APFloat::IEEEsingle()) return S_IEEEsingle; else if (&Sem == &llvm::APFloat::IEEEdouble()) return S_IEEEdouble; else if (&Sem == &llvm::APFloat::x87DoubleExtended()) return S_x87DoubleExtended; else if (&Sem == &llvm::APFloat::IEEEquad()) return S_IEEEquad; else if (&Sem == &llvm::APFloat::PPCDoubleDouble()) return S_PPCDoubleDouble; else llvm_unreachable("Unknown floating semantics"); } const fltSemantics &APFloatBase::IEEEhalf() { return semIEEEhalf; } const fltSemantics &APFloatBase::IEEEsingle() { return semIEEEsingle; } const fltSemantics &APFloatBase::IEEEdouble() { return semIEEEdouble; } const fltSemantics &APFloatBase::IEEEquad() { return semIEEEquad; } const fltSemantics &APFloatBase::x87DoubleExtended() { return semX87DoubleExtended; } const fltSemantics &APFloatBase::Bogus() { return semBogus; } const fltSemantics &APFloatBase::PPCDoubleDouble() { return semPPCDoubleDouble; } /* A tight upper bound on number of parts required to hold the value pow(5, power) is power * 815 / (351 * integerPartWidth) + 1 However, whilst the result may require only this many parts, because we are multiplying two values to get it, the multiplication may require an extra part with the excess part being zero (consider the trivial case of 1 * 1, tcFullMultiply requires two parts to hold the single-part result). So we add an extra one to guarantee enough space whilst multiplying. */ const unsigned int maxExponent = 16383; const unsigned int maxPrecision = 113; const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1; const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815) / (351 * APFloatBase::integerPartWidth)); unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) { return semantics.precision; } APFloatBase::ExponentType APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) { return semantics.maxExponent; } APFloatBase::ExponentType APFloatBase::semanticsMinExponent(const fltSemantics &semantics) { return semantics.minExponent; } unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) { return semantics.sizeInBits; } unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) { return Sem.sizeInBits; } /* A bunch of private, handy routines. */ static inline Error createError(const Twine &Err) { return make_error(Err, inconvertibleErrorCode()); } static inline unsigned int partCountForBits(unsigned int bits) { return ((bits) + APFloatBase::integerPartWidth - 1) / APFloatBase::integerPartWidth; } /* Returns 0U-9U. Return values >= 10U are not digits. */ static inline unsigned int decDigitValue(unsigned int c) { return c - '0'; } /* Return the value of a decimal exponent of the form [+-]ddddddd. If the exponent overflows, returns a large exponent with the appropriate sign. */ static Expected readExponent(StringRef::iterator begin, StringRef::iterator end) { bool isNegative; unsigned int absExponent; const unsigned int overlargeExponent = 24000; /* FIXME. */ StringRef::iterator p = begin; // Treat no exponent as 0 to match binutils if (p == end || ((*p == '-' || *p == '+') && (p + 1) == end)) { return 0; } isNegative = (*p == '-'); if (*p == '-' || *p == '+') { p++; if (p == end) return createError("Exponent has no digits"); } absExponent = decDigitValue(*p++); if (absExponent >= 10U) return createError("Invalid character in exponent"); for (; p != end; ++p) { unsigned int value; value = decDigitValue(*p); if (value >= 10U) return createError("Invalid character in exponent"); absExponent = absExponent * 10U + value; if (absExponent >= overlargeExponent) { absExponent = overlargeExponent; break; } } if (isNegative) return -(int) absExponent; else return (int) absExponent; } /* This is ugly and needs cleaning up, but I don't immediately see how whilst remaining safe. */ static Expected totalExponent(StringRef::iterator p, StringRef::iterator end, int exponentAdjustment) { int unsignedExponent; bool negative, overflow; int exponent = 0; if (p == end) return createError("Exponent has no digits"); negative = *p == '-'; if (*p == '-' || *p == '+') { p++; if (p == end) return createError("Exponent has no digits"); } unsignedExponent = 0; overflow = false; for (; p != end; ++p) { unsigned int value; value = decDigitValue(*p); if (value >= 10U) return createError("Invalid character in exponent"); unsignedExponent = unsignedExponent * 10 + value; if (unsignedExponent > 32767) { overflow = true; break; } } if (exponentAdjustment > 32767 || exponentAdjustment < -32768) overflow = true; if (!overflow) { exponent = unsignedExponent; if (negative) exponent = -exponent; exponent += exponentAdjustment; if (exponent > 32767 || exponent < -32768) overflow = true; } if (overflow) exponent = negative ? -32768: 32767; return exponent; } static Expected skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end, StringRef::iterator *dot) { StringRef::iterator p = begin; *dot = end; while (p != end && *p == '0') p++; if (p != end && *p == '.') { *dot = p++; if (end - begin == 1) return createError("Significand has no digits"); while (p != end && *p == '0') p++; } return p; } /* Given a normal decimal floating point number of the form dddd.dddd[eE][+-]ddd where the decimal point and exponent are optional, fill out the structure D. Exponent is appropriate if the significand is treated as an integer, and normalizedExponent if the significand is taken to have the decimal point after a single leading non-zero digit. If the value is zero, V->firstSigDigit points to a non-digit, and the return exponent is zero. */ struct decimalInfo { const char *firstSigDigit; const char *lastSigDigit; int exponent; int normalizedExponent; }; static Error interpretDecimal(StringRef::iterator begin, StringRef::iterator end, decimalInfo *D) { StringRef::iterator dot = end; auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot); if (!PtrOrErr) return PtrOrErr.takeError(); StringRef::iterator p = *PtrOrErr; D->firstSigDigit = p; D->exponent = 0; D->normalizedExponent = 0; for (; p != end; ++p) { if (*p == '.') { if (dot != end) return createError("String contains multiple dots"); dot = p++; if (p == end) break; } if (decDigitValue(*p) >= 10U) break; } if (p != end) { if (*p != 'e' && *p != 'E') return createError("Invalid character in significand"); if (p == begin) return createError("Significand has no digits"); if (dot != end && p - begin == 1) return createError("Significand has no digits"); /* p points to the first non-digit in the string */ auto ExpOrErr = readExponent(p + 1, end); if (!ExpOrErr) return ExpOrErr.takeError(); D->exponent = *ExpOrErr; /* Implied decimal point? */ if (dot == end) dot = p; } /* If number is all zeroes accept any exponent. */ if (p != D->firstSigDigit) { /* Drop insignificant trailing zeroes. */ if (p != begin) { do do p--; while (p != begin && *p == '0'); while (p != begin && *p == '.'); } /* Adjust the exponents for any decimal point. */ D->exponent += static_cast((dot - p) - (dot > p)); D->normalizedExponent = (D->exponent + static_cast((p - D->firstSigDigit) - (dot > D->firstSigDigit && dot < p))); } D->lastSigDigit = p; return Error::success(); } /* Return the trailing fraction of a hexadecimal number. DIGITVALUE is the first hex digit of the fraction, P points to the next digit. */ static Expected trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end, unsigned int digitValue) { unsigned int hexDigit; /* If the first trailing digit isn't 0 or 8 we can work out the fraction immediately. */ if (digitValue > 8) return lfMoreThanHalf; else if (digitValue < 8 && digitValue > 0) return lfLessThanHalf; // Otherwise we need to find the first non-zero digit. while (p != end && (*p == '0' || *p == '.')) p++; if (p == end) return createError("Invalid trailing hexadecimal fraction!"); hexDigit = hexDigitValue(*p); /* If we ran off the end it is exactly zero or one-half, otherwise a little more. */ if (hexDigit == -1U) return digitValue == 0 ? lfExactlyZero: lfExactlyHalf; else return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf; } /* Return the fraction lost were a bignum truncated losing the least significant BITS bits. */ static lostFraction lostFractionThroughTruncation(const APFloatBase::integerPart *parts, unsigned int partCount, unsigned int bits) { unsigned int lsb; lsb = APInt::tcLSB(parts, partCount); /* Note this is guaranteed true if bits == 0, or LSB == -1U. */ if (bits <= lsb) return lfExactlyZero; if (bits == lsb + 1) return lfExactlyHalf; if (bits <= partCount * APFloatBase::integerPartWidth && APInt::tcExtractBit(parts, bits - 1)) return lfMoreThanHalf; return lfLessThanHalf; } /* Shift DST right BITS bits noting lost fraction. */ static lostFraction shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits) { lostFraction lost_fraction; lost_fraction = lostFractionThroughTruncation(dst, parts, bits); APInt::tcShiftRight(dst, parts, bits); return lost_fraction; } /* Combine the effect of two lost fractions. */ static lostFraction combineLostFractions(lostFraction moreSignificant, lostFraction lessSignificant) { if (lessSignificant != lfExactlyZero) { if (moreSignificant == lfExactlyZero) moreSignificant = lfLessThanHalf; else if (moreSignificant == lfExactlyHalf) moreSignificant = lfMoreThanHalf; } return moreSignificant; } /* The error from the true value, in half-ulps, on multiplying two floating point numbers, which differ from the value they approximate by at most HUE1 and HUE2 half-ulps, is strictly less than the returned value. See "How to Read Floating Point Numbers Accurately" by William D Clinger. */ static unsigned int HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2) { assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8)); if (HUerr1 + HUerr2 == 0) return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */ else return inexactMultiply + 2 * (HUerr1 + HUerr2); } /* The number of ulps from the boundary (zero, or half if ISNEAREST) when the least significant BITS are truncated. BITS cannot be zero. */ static APFloatBase::integerPart ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits, bool isNearest) { unsigned int count, partBits; APFloatBase::integerPart part, boundary; assert(bits != 0); bits--; count = bits / APFloatBase::integerPartWidth; partBits = bits % APFloatBase::integerPartWidth + 1; part = parts[count] & (~(APFloatBase::integerPart) 0 >> (APFloatBase::integerPartWidth - partBits)); if (isNearest) boundary = (APFloatBase::integerPart) 1 << (partBits - 1); else boundary = 0; if (count == 0) { if (part - boundary <= boundary - part) return part - boundary; else return boundary - part; } if (part == boundary) { while (--count) if (parts[count]) return ~(APFloatBase::integerPart) 0; /* A lot. */ return parts[0]; } else if (part == boundary - 1) { while (--count) if (~parts[count]) return ~(APFloatBase::integerPart) 0; /* A lot. */ return -parts[0]; } return ~(APFloatBase::integerPart) 0; /* A lot. */ } /* Place pow(5, power) in DST, and return the number of parts used. DST must be at least one part larger than size of the answer. */ static unsigned int powerOf5(APFloatBase::integerPart *dst, unsigned int power) { static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 }; APFloatBase::integerPart pow5s[maxPowerOfFiveParts * 2 + 5]; pow5s[0] = 78125 * 5; unsigned int partsCount[16] = { 1 }; APFloatBase::integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5; unsigned int result; assert(power <= maxExponent); p1 = dst; p2 = scratch; *p1 = firstEightPowers[power & 7]; power >>= 3; result = 1; pow5 = pow5s; for (unsigned int n = 0; power; power >>= 1, n++) { unsigned int pc; pc = partsCount[n]; /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */ if (pc == 0) { pc = partsCount[n - 1]; APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc); pc *= 2; if (pow5[pc - 1] == 0) pc--; partsCount[n] = pc; } if (power & 1) { APFloatBase::integerPart *tmp; APInt::tcFullMultiply(p2, p1, pow5, result, pc); result += pc; if (p2[result - 1] == 0) result--; /* Now result is in p1 with partsCount parts and p2 is scratch space. */ tmp = p1; p1 = p2; p2 = tmp; } pow5 += pc; } if (p1 != dst) APInt::tcAssign(dst, p1, result); return result; } /* Zero at the end to avoid modular arithmetic when adding one; used when rounding up during hexadecimal output. */ static const char hexDigitsLower[] = "0123456789abcdef0"; static const char hexDigitsUpper[] = "0123456789ABCDEF0"; static const char infinityL[] = "infinity"; static const char infinityU[] = "INFINITY"; static const char NaNL[] = "nan"; static const char NaNU[] = "NAN"; /* Write out an integerPart in hexadecimal, starting with the most significant nibble. Write out exactly COUNT hexdigits, return COUNT. */ static unsigned int partAsHex (char *dst, APFloatBase::integerPart part, unsigned int count, const char *hexDigitChars) { unsigned int result = count; assert(count != 0 && count <= APFloatBase::integerPartWidth / 4); part >>= (APFloatBase::integerPartWidth - 4 * count); while (count--) { dst[count] = hexDigitChars[part & 0xf]; part >>= 4; } return result; } /* Write out an unsigned decimal integer. */ static char * writeUnsignedDecimal (char *dst, unsigned int n) { char buff[40], *p; p = buff; do *p++ = '0' + n % 10; while (n /= 10); do *dst++ = *--p; while (p != buff); return dst; } /* Write out a signed decimal integer. */ static char * writeSignedDecimal (char *dst, int value) { if (value < 0) { *dst++ = '-'; dst = writeUnsignedDecimal(dst, -(unsigned) value); } else dst = writeUnsignedDecimal(dst, value); return dst; } namespace detail { /* Constructors. */ void IEEEFloat::initialize(const fltSemantics *ourSemantics) { unsigned int count; semantics = ourSemantics; count = partCount(); if (count > 1) significand.parts = new integerPart[count]; } void IEEEFloat::freeSignificand() { if (needsCleanup()) delete [] significand.parts; } void IEEEFloat::assign(const IEEEFloat &rhs) { assert(semantics == rhs.semantics); sign = rhs.sign; category = rhs.category; exponent = rhs.exponent; if (isFiniteNonZero() || category == fcNaN) copySignificand(rhs); } void IEEEFloat::copySignificand(const IEEEFloat &rhs) { assert(isFiniteNonZero() || category == fcNaN); assert(rhs.partCount() >= partCount()); APInt::tcAssign(significandParts(), rhs.significandParts(), partCount()); } /* Make this number a NaN, with an arbitrary but deterministic value for the significand. If double or longer, this is a signalling NaN, which may not be ideal. If float, this is QNaN(0). */ void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) { category = fcNaN; sign = Negative; integerPart *significand = significandParts(); unsigned numParts = partCount(); // Set the significand bits to the fill. if (!fill || fill->getNumWords() < numParts) APInt::tcSet(significand, 0, numParts); if (fill) { APInt::tcAssign(significand, fill->getRawData(), std::min(fill->getNumWords(), numParts)); // Zero out the excess bits of the significand. unsigned bitsToPreserve = semantics->precision - 1; unsigned part = bitsToPreserve / 64; bitsToPreserve %= 64; significand[part] &= ((1ULL << bitsToPreserve) - 1); for (part++; part != numParts; ++part) significand[part] = 0; } unsigned QNaNBit = semantics->precision - 2; if (SNaN) { // We always have to clear the QNaN bit to make it an SNaN. APInt::tcClearBit(significand, QNaNBit); // If there are no bits set in the payload, we have to set // *something* to make it a NaN instead of an infinity; // conventionally, this is the next bit down from the QNaN bit. if (APInt::tcIsZero(significand, numParts)) APInt::tcSetBit(significand, QNaNBit - 1); } else { // We always have to set the QNaN bit to make it a QNaN. APInt::tcSetBit(significand, QNaNBit); } // For x87 extended precision, we want to make a NaN, not a // pseudo-NaN. Maybe we should expose the ability to make // pseudo-NaNs? if (semantics == &semX87DoubleExtended) APInt::tcSetBit(significand, QNaNBit + 1); } IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) { if (this != &rhs) { if (semantics != rhs.semantics) { freeSignificand(); initialize(rhs.semantics); } assign(rhs); } return *this; } IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) { freeSignificand(); semantics = rhs.semantics; significand = rhs.significand; exponent = rhs.exponent; category = rhs.category; sign = rhs.sign; rhs.semantics = &semBogus; return *this; } bool IEEEFloat::isDenormal() const { return isFiniteNonZero() && (exponent == semantics->minExponent) && (APInt::tcExtractBit(significandParts(), semantics->precision - 1) == 0); } bool IEEEFloat::isSmallest() const { // The smallest number by magnitude in our format will be the smallest // denormal, i.e. the floating point number with exponent being minimum // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0). return isFiniteNonZero() && exponent == semantics->minExponent && significandMSB() == 0; } bool IEEEFloat::isSignificandAllOnes() const { // Test if the significand excluding the integral bit is all ones. This allows // us to test for binade boundaries. const integerPart *Parts = significandParts(); const unsigned PartCount = partCount(); for (unsigned i = 0; i < PartCount - 1; i++) if (~Parts[i]) return false; // Set the unused high bits to all ones when we compare. const unsigned NumHighBits = PartCount*integerPartWidth - semantics->precision + 1; assert(NumHighBits <= integerPartWidth && "Can not have more high bits to " "fill than integerPartWidth"); const integerPart HighBitFill = ~integerPart(0) << (integerPartWidth - NumHighBits); if (~(Parts[PartCount - 1] | HighBitFill)) return false; return true; } bool IEEEFloat::isSignificandAllZeros() const { // Test if the significand excluding the integral bit is all zeros. This // allows us to test for binade boundaries. const integerPart *Parts = significandParts(); const unsigned PartCount = partCount(); for (unsigned i = 0; i < PartCount - 1; i++) if (Parts[i]) return false; const unsigned NumHighBits = PartCount*integerPartWidth - semantics->precision + 1; assert(NumHighBits <= integerPartWidth && "Can not have more high bits to " "clear than integerPartWidth"); const integerPart HighBitMask = ~integerPart(0) >> NumHighBits; if (Parts[PartCount - 1] & HighBitMask) return false; return true; } bool IEEEFloat::isLargest() const { // The largest number by magnitude in our format will be the floating point // number with maximum exponent and with significand that is all ones. return isFiniteNonZero() && exponent == semantics->maxExponent && isSignificandAllOnes(); } bool IEEEFloat::isInteger() const { // This could be made more efficient; I'm going for obviously correct. if (!isFinite()) return false; IEEEFloat truncated = *this; truncated.roundToIntegral(rmTowardZero); return compare(truncated) == cmpEqual; } bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const { if (this == &rhs) return true; if (semantics != rhs.semantics || category != rhs.category || sign != rhs.sign) return false; if (category==fcZero || category==fcInfinity) return true; if (isFiniteNonZero() && exponent != rhs.exponent) return false; return std::equal(significandParts(), significandParts() + partCount(), rhs.significandParts()); } IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) { initialize(&ourSemantics); sign = 0; category = fcNormal; zeroSignificand(); exponent = ourSemantics.precision - 1; significandParts()[0] = value; normalize(rmNearestTiesToEven, lfExactlyZero); } IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) { initialize(&ourSemantics); category = fcZero; sign = false; } // Delegate to the previous constructor, because later copy constructor may // actually inspects category, which can't be garbage. IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag) : IEEEFloat(ourSemantics) {} IEEEFloat::IEEEFloat(const IEEEFloat &rhs) { initialize(rhs.semantics); assign(rhs); } IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) { *this = std::move(rhs); } IEEEFloat::~IEEEFloat() { freeSignificand(); } unsigned int IEEEFloat::partCount() const { return partCountForBits(semantics->precision + 1); } const IEEEFloat::integerPart *IEEEFloat::significandParts() const { return const_cast(this)->significandParts(); } IEEEFloat::integerPart *IEEEFloat::significandParts() { if (partCount() > 1) return significand.parts; else return &significand.part; } void IEEEFloat::zeroSignificand() { APInt::tcSet(significandParts(), 0, partCount()); } /* Increment an fcNormal floating point number's significand. */ void IEEEFloat::incrementSignificand() { integerPart carry; carry = APInt::tcIncrement(significandParts(), partCount()); /* Our callers should never cause us to overflow. */ assert(carry == 0); (void)carry; } /* Add the significand of the RHS. Returns the carry flag. */ IEEEFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) { integerPart *parts; parts = significandParts(); assert(semantics == rhs.semantics); assert(exponent == rhs.exponent); return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount()); } /* Subtract the significand of the RHS with a borrow flag. Returns the borrow flag. */ IEEEFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs, integerPart borrow) { integerPart *parts; parts = significandParts(); assert(semantics == rhs.semantics); assert(exponent == rhs.exponent); return APInt::tcSubtract(parts, rhs.significandParts(), borrow, partCount()); } /* Multiply the significand of the RHS. If ADDEND is non-NULL, add it on to the full-precision result of the multiplication. Returns the lost fraction. */ lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs, const IEEEFloat *addend) { unsigned int omsb; // One, not zero, based MSB. unsigned int partsCount, newPartsCount, precision; integerPart *lhsSignificand; integerPart scratch[4]; integerPart *fullSignificand; lostFraction lost_fraction; bool ignored; assert(semantics == rhs.semantics); precision = semantics->precision; // Allocate space for twice as many bits as the original significand, plus one // extra bit for the addition to overflow into. newPartsCount = partCountForBits(precision * 2 + 1); if (newPartsCount > 4) fullSignificand = new integerPart[newPartsCount]; else fullSignificand = scratch; lhsSignificand = significandParts(); partsCount = partCount(); APInt::tcFullMultiply(fullSignificand, lhsSignificand, rhs.significandParts(), partsCount, partsCount); lost_fraction = lfExactlyZero; omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1; exponent += rhs.exponent; // Assume the operands involved in the multiplication are single-precision // FP, and the two multiplicants are: // *this = a23 . a22 ... a0 * 2^e1 // rhs = b23 . b22 ... b0 * 2^e2 // the result of multiplication is: // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2) // Note that there are three significant bits at the left-hand side of the // radix point: two for the multiplication, and an overflow bit for the // addition (that will always be zero at this point). Move the radix point // toward left by two bits, and adjust exponent accordingly. exponent += 2; if (addend && addend->isNonZero()) { // The intermediate result of the multiplication has "2 * precision" // signicant bit; adjust the addend to be consistent with mul result. // Significand savedSignificand = significand; const fltSemantics *savedSemantics = semantics; fltSemantics extendedSemantics; opStatus status; unsigned int extendedPrecision; // Normalize our MSB to one below the top bit to allow for overflow. extendedPrecision = 2 * precision + 1; if (omsb != extendedPrecision - 1) { assert(extendedPrecision > omsb); APInt::tcShiftLeft(fullSignificand, newPartsCount, (extendedPrecision - 1) - omsb); exponent -= (extendedPrecision - 1) - omsb; } /* Create new semantics. */ extendedSemantics = *semantics; extendedSemantics.precision = extendedPrecision; if (newPartsCount == 1) significand.part = fullSignificand[0]; else significand.parts = fullSignificand; semantics = &extendedSemantics; IEEEFloat extendedAddend(*addend); status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored); assert(status == opOK); (void)status; // Shift the significand of the addend right by one bit. This guarantees // that the high bit of the significand is zero (same as fullSignificand), // so the addition will overflow (if it does overflow at all) into the top bit. lost_fraction = extendedAddend.shiftSignificandRight(1); assert(lost_fraction == lfExactlyZero && "Lost precision while shifting addend for fused-multiply-add."); lost_fraction = addOrSubtractSignificand(extendedAddend, false); /* Restore our state. */ if (newPartsCount == 1) fullSignificand[0] = significand.part; significand = savedSignificand; semantics = savedSemantics; omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1; } // Convert the result having "2 * precision" significant-bits back to the one // having "precision" significant-bits. First, move the radix point from // poision "2*precision - 1" to "precision - 1". The exponent need to be // adjusted by "2*precision - 1" - "precision - 1" = "precision". exponent -= precision + 1; // In case MSB resides at the left-hand side of radix point, shift the // mantissa right by some amount to make sure the MSB reside right before // the radix point (i.e. "MSB . rest-significant-bits"). // // Note that the result is not normalized when "omsb < precision". So, the // caller needs to call IEEEFloat::normalize() if normalized value is // expected. if (omsb > precision) { unsigned int bits, significantParts; lostFraction lf; bits = omsb - precision; significantParts = partCountForBits(omsb); lf = shiftRight(fullSignificand, significantParts, bits); lost_fraction = combineLostFractions(lf, lost_fraction); exponent += bits; } APInt::tcAssign(lhsSignificand, fullSignificand, partsCount); if (newPartsCount > 4) delete [] fullSignificand; return lost_fraction; } /* Multiply the significands of LHS and RHS to DST. */ lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) { unsigned int bit, i, partsCount; const integerPart *rhsSignificand; integerPart *lhsSignificand, *dividend, *divisor; integerPart scratch[4]; lostFraction lost_fraction; assert(semantics == rhs.semantics); lhsSignificand = significandParts(); rhsSignificand = rhs.significandParts(); partsCount = partCount(); if (partsCount > 2) dividend = new integerPart[partsCount * 2]; else dividend = scratch; divisor = dividend + partsCount; /* Copy the dividend and divisor as they will be modified in-place. */ for (i = 0; i < partsCount; i++) { dividend[i] = lhsSignificand[i]; divisor[i] = rhsSignificand[i]; lhsSignificand[i] = 0; } exponent -= rhs.exponent; unsigned int precision = semantics->precision; /* Normalize the divisor. */ bit = precision - APInt::tcMSB(divisor, partsCount) - 1; if (bit) { exponent += bit; APInt::tcShiftLeft(divisor, partsCount, bit); } /* Normalize the dividend. */ bit = precision - APInt::tcMSB(dividend, partsCount) - 1; if (bit) { exponent -= bit; APInt::tcShiftLeft(dividend, partsCount, bit); } /* Ensure the dividend >= divisor initially for the loop below. Incidentally, this means that the division loop below is guaranteed to set the integer bit to one. */ if (APInt::tcCompare(dividend, divisor, partsCount) < 0) { exponent--; APInt::tcShiftLeft(dividend, partsCount, 1); assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0); } /* Long division. */ for (bit = precision; bit; bit -= 1) { if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) { APInt::tcSubtract(dividend, divisor, 0, partsCount); APInt::tcSetBit(lhsSignificand, bit - 1); } APInt::tcShiftLeft(dividend, partsCount, 1); } /* Figure out the lost fraction. */ int cmp = APInt::tcCompare(dividend, divisor, partsCount); if (cmp > 0) lost_fraction = lfMoreThanHalf; else if (cmp == 0) lost_fraction = lfExactlyHalf; else if (APInt::tcIsZero(dividend, partsCount)) lost_fraction = lfExactlyZero; else lost_fraction = lfLessThanHalf; if (partsCount > 2) delete [] dividend; return lost_fraction; } unsigned int IEEEFloat::significandMSB() const { return APInt::tcMSB(significandParts(), partCount()); } unsigned int IEEEFloat::significandLSB() const { return APInt::tcLSB(significandParts(), partCount()); } /* Note that a zero result is NOT normalized to fcZero. */ lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) { /* Our exponent should not overflow. */ assert((ExponentType) (exponent + bits) >= exponent); exponent += bits; return shiftRight(significandParts(), partCount(), bits); } /* Shift the significand left BITS bits, subtract BITS from its exponent. */ void IEEEFloat::shiftSignificandLeft(unsigned int bits) { assert(bits < semantics->precision); if (bits) { unsigned int partsCount = partCount(); APInt::tcShiftLeft(significandParts(), partsCount, bits); exponent -= bits; assert(!APInt::tcIsZero(significandParts(), partsCount)); } } IEEEFloat::cmpResult IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const { int compare; assert(semantics == rhs.semantics); assert(isFiniteNonZero()); assert(rhs.isFiniteNonZero()); compare = exponent - rhs.exponent; /* If exponents are equal, do an unsigned bignum comparison of the significands. */ if (compare == 0) compare = APInt::tcCompare(significandParts(), rhs.significandParts(), partCount()); if (compare > 0) return cmpGreaterThan; else if (compare < 0) return cmpLessThan; else return cmpEqual; } /* Handle overflow. Sign is preserved. We either become infinity or the largest finite number. */ IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) { /* Infinity? */ if (rounding_mode == rmNearestTiesToEven || rounding_mode == rmNearestTiesToAway || (rounding_mode == rmTowardPositive && !sign) || (rounding_mode == rmTowardNegative && sign)) { category = fcInfinity; return (opStatus) (opOverflow | opInexact); } /* Otherwise we become the largest finite number. */ category = fcNormal; exponent = semantics->maxExponent; APInt::tcSetLeastSignificantBits(significandParts(), partCount(), semantics->precision); return opInexact; } /* Returns TRUE if, when truncating the current number, with BIT the new LSB, with the given lost fraction and rounding mode, the result would need to be rounded away from zero (i.e., by increasing the signficand). This routine must work for fcZero of both signs, and fcNormal numbers. */ bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode, lostFraction lost_fraction, unsigned int bit) const { /* NaNs and infinities should not have lost fractions. */ assert(isFiniteNonZero() || category == fcZero); /* Current callers never pass this so we don't handle it. */ assert(lost_fraction != lfExactlyZero); switch (rounding_mode) { case rmNearestTiesToAway: return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf; case rmNearestTiesToEven: if (lost_fraction == lfMoreThanHalf) return true; /* Our zeroes don't have a significand to test. */ if (lost_fraction == lfExactlyHalf && category != fcZero) return APInt::tcExtractBit(significandParts(), bit); return false; case rmTowardZero: return false; case rmTowardPositive: return !sign; case rmTowardNegative: return sign; } llvm_unreachable("Invalid rounding mode found"); } IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode, lostFraction lost_fraction) { unsigned int omsb; /* One, not zero, based MSB. */ int exponentChange; if (!isFiniteNonZero()) return opOK; /* Before rounding normalize the exponent of fcNormal numbers. */ omsb = significandMSB() + 1; if (omsb) { /* OMSB is numbered from 1. We want to place it in the integer bit numbered PRECISION if possible, with a compensating change in the exponent. */ exponentChange = omsb - semantics->precision; /* If the resulting exponent is too high, overflow according to the rounding mode. */ if (exponent + exponentChange > semantics->maxExponent) return handleOverflow(rounding_mode); /* Subnormal numbers have exponent minExponent, and their MSB is forced based on that. */ if (exponent + exponentChange < semantics->minExponent) exponentChange = semantics->minExponent - exponent; /* Shifting left is easy as we don't lose precision. */ if (exponentChange < 0) { assert(lost_fraction == lfExactlyZero); shiftSignificandLeft(-exponentChange); return opOK; } if (exponentChange > 0) { lostFraction lf; /* Shift right and capture any new lost fraction. */ lf = shiftSignificandRight(exponentChange); lost_fraction = combineLostFractions(lf, lost_fraction); /* Keep OMSB up-to-date. */ if (omsb > (unsigned) exponentChange) omsb -= exponentChange; else omsb = 0; } } /* Now round the number according to rounding_mode given the lost fraction. */ /* As specified in IEEE 754, since we do not trap we do not report underflow for exact results. */ if (lost_fraction == lfExactlyZero) { /* Canonicalize zeroes. */ if (omsb == 0) category = fcZero; return opOK; } /* Increment the significand if we're rounding away from zero. */ if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) { if (omsb == 0) exponent = semantics->minExponent; incrementSignificand(); omsb = significandMSB() + 1; /* Did the significand increment overflow? */ if (omsb == (unsigned) semantics->precision + 1) { /* Renormalize by incrementing the exponent and shifting our significand right one. However if we already have the maximum exponent we overflow to infinity. */ if (exponent == semantics->maxExponent) { category = fcInfinity; return (opStatus) (opOverflow | opInexact); } shiftSignificandRight(1); return opInexact; } } /* The normal case - we were and are not denormal, and any significand increment above didn't overflow. */ if (omsb == semantics->precision) return opInexact; /* We have a non-zero denormal. */ assert(omsb < semantics->precision); /* Canonicalize zeroes. */ if (omsb == 0) category = fcZero; /* The fcZero case is a denormal that underflowed to zero. */ return (opStatus) (opUnderflow | opInexact); } IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs, bool subtract) { switch (PackCategoriesIntoKey(category, rhs.category)) { default: llvm_unreachable(nullptr); case PackCategoriesIntoKey(fcNaN, fcZero): case PackCategoriesIntoKey(fcNaN, fcNormal): case PackCategoriesIntoKey(fcNaN, fcInfinity): case PackCategoriesIntoKey(fcNaN, fcNaN): case PackCategoriesIntoKey(fcNormal, fcZero): case PackCategoriesIntoKey(fcInfinity, fcNormal): case PackCategoriesIntoKey(fcInfinity, fcZero): return opOK; case PackCategoriesIntoKey(fcZero, fcNaN): case PackCategoriesIntoKey(fcNormal, fcNaN): case PackCategoriesIntoKey(fcInfinity, fcNaN): // We need to be sure to flip the sign here for subtraction because we // don't have a separate negate operation so -NaN becomes 0 - NaN here. sign = rhs.sign ^ subtract; category = fcNaN; copySignificand(rhs); return opOK; case PackCategoriesIntoKey(fcNormal, fcInfinity): case PackCategoriesIntoKey(fcZero, fcInfinity): category = fcInfinity; sign = rhs.sign ^ subtract; return opOK; case PackCategoriesIntoKey(fcZero, fcNormal): assign(rhs); sign = rhs.sign ^ subtract; return opOK; case PackCategoriesIntoKey(fcZero, fcZero): /* Sign depends on rounding mode; handled by caller. */ return opOK; case PackCategoriesIntoKey(fcInfinity, fcInfinity): /* Differently signed infinities can only be validly subtracted. */ if (((sign ^ rhs.sign)!=0) != subtract) { makeNaN(); return opInvalidOp; } return opOK; case PackCategoriesIntoKey(fcNormal, fcNormal): return opDivByZero; } } /* Add or subtract two normal numbers. */ lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs, bool subtract) { integerPart carry; lostFraction lost_fraction; int bits; /* Determine if the operation on the absolute values is effectively an addition or subtraction. */ subtract ^= static_cast(sign ^ rhs.sign); /* Are we bigger exponent-wise than the RHS? */ bits = exponent - rhs.exponent; /* Subtraction is more subtle than one might naively expect. */ if (subtract) { IEEEFloat temp_rhs(rhs); if (bits == 0) lost_fraction = lfExactlyZero; else if (bits > 0) { lost_fraction = temp_rhs.shiftSignificandRight(bits - 1); shiftSignificandLeft(1); } else { lost_fraction = shiftSignificandRight(-bits - 1); temp_rhs.shiftSignificandLeft(1); } // Should we reverse the subtraction. if (compareAbsoluteValue(temp_rhs) == cmpLessThan) { carry = temp_rhs.subtractSignificand (*this, lost_fraction != lfExactlyZero); copySignificand(temp_rhs); sign = !sign; } else { carry = subtractSignificand (temp_rhs, lost_fraction != lfExactlyZero); } /* Invert the lost fraction - it was on the RHS and subtracted. */ if (lost_fraction == lfLessThanHalf) lost_fraction = lfMoreThanHalf; else if (lost_fraction == lfMoreThanHalf) lost_fraction = lfLessThanHalf; /* The code above is intended to ensure that no borrow is necessary. */ assert(!carry); (void)carry; } else { if (bits > 0) { IEEEFloat temp_rhs(rhs); lost_fraction = temp_rhs.shiftSignificandRight(bits); carry = addSignificand(temp_rhs); } else { lost_fraction = shiftSignificandRight(-bits); carry = addSignificand(rhs); } /* We have a guard bit; generating a carry cannot happen. */ assert(!carry); (void)carry; } return lost_fraction; } IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) { switch (PackCategoriesIntoKey(category, rhs.category)) { default: llvm_unreachable(nullptr); case PackCategoriesIntoKey(fcNaN, fcZero): case PackCategoriesIntoKey(fcNaN, fcNormal): case PackCategoriesIntoKey(fcNaN, fcInfinity): case PackCategoriesIntoKey(fcNaN, fcNaN): sign = false; return opOK; case PackCategoriesIntoKey(fcZero, fcNaN): case PackCategoriesIntoKey(fcNormal, fcNaN): case PackCategoriesIntoKey(fcInfinity, fcNaN): sign = false; category = fcNaN; copySignificand(rhs); return opOK; case PackCategoriesIntoKey(fcNormal, fcInfinity): case PackCategoriesIntoKey(fcInfinity, fcNormal): case PackCategoriesIntoKey(fcInfinity, fcInfinity): category = fcInfinity; return opOK; case PackCategoriesIntoKey(fcZero, fcNormal): case PackCategoriesIntoKey(fcNormal, fcZero): case PackCategoriesIntoKey(fcZero, fcZero): category = fcZero; return opOK; case PackCategoriesIntoKey(fcZero, fcInfinity): case PackCategoriesIntoKey(fcInfinity, fcZero): makeNaN(); return opInvalidOp; case PackCategoriesIntoKey(fcNormal, fcNormal): return opOK; } } IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) { switch (PackCategoriesIntoKey(category, rhs.category)) { default: llvm_unreachable(nullptr); case PackCategoriesIntoKey(fcZero, fcNaN): case PackCategoriesIntoKey(fcNormal, fcNaN): case PackCategoriesIntoKey(fcInfinity, fcNaN): category = fcNaN; copySignificand(rhs); LLVM_FALLTHROUGH; case PackCategoriesIntoKey(fcNaN, fcZero): case PackCategoriesIntoKey(fcNaN, fcNormal): case PackCategoriesIntoKey(fcNaN, fcInfinity): case PackCategoriesIntoKey(fcNaN, fcNaN): sign = false; LLVM_FALLTHROUGH; case PackCategoriesIntoKey(fcInfinity, fcZero): case PackCategoriesIntoKey(fcInfinity, fcNormal): case PackCategoriesIntoKey(fcZero, fcInfinity): case PackCategoriesIntoKey(fcZero, fcNormal): return opOK; case PackCategoriesIntoKey(fcNormal, fcInfinity): category = fcZero; return opOK; case PackCategoriesIntoKey(fcNormal, fcZero): category = fcInfinity; return opDivByZero; case PackCategoriesIntoKey(fcInfinity, fcInfinity): case PackCategoriesIntoKey(fcZero, fcZero): makeNaN(); return opInvalidOp; case PackCategoriesIntoKey(fcNormal, fcNormal): return opOK; } } IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) { switch (PackCategoriesIntoKey(category, rhs.category)) { default: llvm_unreachable(nullptr); case PackCategoriesIntoKey(fcNaN, fcZero): case PackCategoriesIntoKey(fcNaN, fcNormal): case PackCategoriesIntoKey(fcNaN, fcInfinity): case PackCategoriesIntoKey(fcNaN, fcNaN): case PackCategoriesIntoKey(fcZero, fcInfinity): case PackCategoriesIntoKey(fcZero, fcNormal): case PackCategoriesIntoKey(fcNormal, fcInfinity): return opOK; case PackCategoriesIntoKey(fcZero, fcNaN): case PackCategoriesIntoKey(fcNormal, fcNaN): case PackCategoriesIntoKey(fcInfinity, fcNaN): sign = false; category = fcNaN; copySignificand(rhs); return opOK; case PackCategoriesIntoKey(fcNormal, fcZero): case PackCategoriesIntoKey(fcInfinity, fcZero): case PackCategoriesIntoKey(fcInfinity, fcNormal): case PackCategoriesIntoKey(fcInfinity, fcInfinity): case PackCategoriesIntoKey(fcZero, fcZero): makeNaN(); return opInvalidOp; case PackCategoriesIntoKey(fcNormal, fcNormal): return opOK; } } /* Change sign. */ void IEEEFloat::changeSign() { /* Look mummy, this one's easy. */ sign = !sign; } /* Normalized addition or subtraction. */ IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs, roundingMode rounding_mode, bool subtract) { opStatus fs; fs = addOrSubtractSpecials(rhs, subtract); /* This return code means it was not a simple case. */ if (fs == opDivByZero) { lostFraction lost_fraction; lost_fraction = addOrSubtractSignificand(rhs, subtract); fs = normalize(rounding_mode, lost_fraction); /* Can only be zero if we lost no fraction. */ assert(category != fcZero || lost_fraction == lfExactlyZero); } /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a positive zero unless rounding to minus infinity, except that adding two like-signed zeroes gives that zero. */ if (category == fcZero) { if (rhs.category != fcZero || (sign == rhs.sign) == subtract) sign = (rounding_mode == rmTowardNegative); } return fs; } /* Normalized addition. */ IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs, roundingMode rounding_mode) { return addOrSubtract(rhs, rounding_mode, false); } /* Normalized subtraction. */ IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs, roundingMode rounding_mode) { return addOrSubtract(rhs, rounding_mode, true); } /* Normalized multiply. */ IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs, roundingMode rounding_mode) { opStatus fs; sign ^= rhs.sign; fs = multiplySpecials(rhs); if (isFiniteNonZero()) { lostFraction lost_fraction = multiplySignificand(rhs, nullptr); fs = normalize(rounding_mode, lost_fraction); if (lost_fraction != lfExactlyZero) fs = (opStatus) (fs | opInexact); } return fs; } /* Normalized divide. */ IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs, roundingMode rounding_mode) { opStatus fs; sign ^= rhs.sign; fs = divideSpecials(rhs); if (isFiniteNonZero()) { lostFraction lost_fraction = divideSignificand(rhs); fs = normalize(rounding_mode, lost_fraction); if (lost_fraction != lfExactlyZero) fs = (opStatus) (fs | opInexact); } return fs; } /* Normalized remainder. This is not currently correct in all cases. */ IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) { opStatus fs; IEEEFloat V = *this; unsigned int origSign = sign; fs = V.divide(rhs, rmNearestTiesToEven); if (fs == opDivByZero) return fs; int parts = partCount(); integerPart *x = new integerPart[parts]; bool ignored; fs = V.convertToInteger(makeMutableArrayRef(x, parts), parts * integerPartWidth, true, rmNearestTiesToEven, &ignored); if (fs == opInvalidOp) { delete[] x; return fs; } fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true, rmNearestTiesToEven); assert(fs==opOK); // should always work fs = V.multiply(rhs, rmNearestTiesToEven); assert(fs==opOK || fs==opInexact); // should not overflow or underflow fs = subtract(V, rmNearestTiesToEven); assert(fs==opOK || fs==opInexact); // likewise if (isZero()) sign = origSign; // IEEE754 requires this delete[] x; return fs; } /* Normalized llvm frem (C fmod). */ IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) { opStatus fs; fs = modSpecials(rhs); unsigned int origSign = sign; while (isFiniteNonZero() && rhs.isFiniteNonZero() && compareAbsoluteValue(rhs) != cmpLessThan) { IEEEFloat V = scalbn(rhs, ilogb(*this) - ilogb(rhs), rmNearestTiesToEven); if (compareAbsoluteValue(V) == cmpLessThan) V = scalbn(V, -1, rmNearestTiesToEven); V.sign = sign; fs = subtract(V, rmNearestTiesToEven); assert(fs==opOK); } if (isZero()) sign = origSign; // fmod requires this return fs; } /* Normalized fused-multiply-add. */ IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand, const IEEEFloat &addend, roundingMode rounding_mode) { opStatus fs; /* Post-multiplication sign, before addition. */ sign ^= multiplicand.sign; /* If and only if all arguments are normal do we need to do an extended-precision calculation. */ if (isFiniteNonZero() && multiplicand.isFiniteNonZero() && addend.isFinite()) { lostFraction lost_fraction; lost_fraction = multiplySignificand(multiplicand, &addend); fs = normalize(rounding_mode, lost_fraction); if (lost_fraction != lfExactlyZero) fs = (opStatus) (fs | opInexact); /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a positive zero unless rounding to minus infinity, except that adding two like-signed zeroes gives that zero. */ if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign) sign = (rounding_mode == rmTowardNegative); } else { fs = multiplySpecials(multiplicand); /* FS can only be opOK or opInvalidOp. There is no more work to do in the latter case. The IEEE-754R standard says it is implementation-defined in this case whether, if ADDEND is a quiet NaN, we raise invalid op; this implementation does so. If we need to do the addition we can do so with normal precision. */ if (fs == opOK) fs = addOrSubtract(addend, rounding_mode, false); } return fs; } /* Rounding-mode corrrect round to integral value. */ IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) { opStatus fs; // If the exponent is large enough, we know that this value is already // integral, and the arithmetic below would potentially cause it to saturate // to +/-Inf. Bail out early instead. if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics)) return opOK; // The algorithm here is quite simple: we add 2^(p-1), where p is the // precision of our format, and then subtract it back off again. The choice // of rounding modes for the addition/subtraction determines the rounding mode // for our integral rounding as well. // NOTE: When the input value is negative, we do subtraction followed by // addition instead. APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1); IntegerConstant <<= semanticsPrecision(*semantics)-1; IEEEFloat MagicConstant(*semantics); fs = MagicConstant.convertFromAPInt(IntegerConstant, false, rmNearestTiesToEven); MagicConstant.sign = sign; if (fs != opOK) return fs; // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly. bool inputSign = isNegative(); fs = add(MagicConstant, rounding_mode); if (fs != opOK && fs != opInexact) return fs; fs = subtract(MagicConstant, rounding_mode); // Restore the input sign. if (inputSign != isNegative()) changeSign(); return fs; } /* Comparison requires normalized numbers. */ IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const { cmpResult result; assert(semantics == rhs.semantics); switch (PackCategoriesIntoKey(category, rhs.category)) { default: llvm_unreachable(nullptr); case PackCategoriesIntoKey(fcNaN, fcZero): case PackCategoriesIntoKey(fcNaN, fcNormal): case PackCategoriesIntoKey(fcNaN, fcInfinity): case PackCategoriesIntoKey(fcNaN, fcNaN): case PackCategoriesIntoKey(fcZero, fcNaN): case PackCategoriesIntoKey(fcNormal, fcNaN): case PackCategoriesIntoKey(fcInfinity, fcNaN): return cmpUnordered; case PackCategoriesIntoKey(fcInfinity, fcNormal): case PackCategoriesIntoKey(fcInfinity, fcZero): case PackCategoriesIntoKey(fcNormal, fcZero): if (sign) return cmpLessThan; else return cmpGreaterThan; case PackCategoriesIntoKey(fcNormal, fcInfinity): case PackCategoriesIntoKey(fcZero, fcInfinity): case PackCategoriesIntoKey(fcZero, fcNormal): if (rhs.sign) return cmpGreaterThan; else return cmpLessThan; case PackCategoriesIntoKey(fcInfinity, fcInfinity): if (sign == rhs.sign) return cmpEqual; else if (sign) return cmpLessThan; else return cmpGreaterThan; case PackCategoriesIntoKey(fcZero, fcZero): return cmpEqual; case PackCategoriesIntoKey(fcNormal, fcNormal): break; } /* Two normal numbers. Do they have the same sign? */ if (sign != rhs.sign) { if (sign) result = cmpLessThan; else result = cmpGreaterThan; } else { /* Compare absolute values; invert result if negative. */ result = compareAbsoluteValue(rhs); if (sign) { if (result == cmpLessThan) result = cmpGreaterThan; else if (result == cmpGreaterThan) result = cmpLessThan; } } return result; } /// IEEEFloat::convert - convert a value of one floating point type to another. /// The return value corresponds to the IEEE754 exceptions. *losesInfo /// records whether the transformation lost information, i.e. whether /// converting the result back to the original type will produce the /// original value (this is almost the same as return value==fsOK, but there /// are edge cases where this is not so). IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics, roundingMode rounding_mode, bool *losesInfo) { lostFraction lostFraction; unsigned int newPartCount, oldPartCount; opStatus fs; int shift; const fltSemantics &fromSemantics = *semantics; lostFraction = lfExactlyZero; newPartCount = partCountForBits(toSemantics.precision + 1); oldPartCount = partCount(); shift = toSemantics.precision - fromSemantics.precision; bool X86SpecialNan = false; if (&fromSemantics == &semX87DoubleExtended && &toSemantics != &semX87DoubleExtended && category == fcNaN && (!(*significandParts() & 0x8000000000000000ULL) || !(*significandParts() & 0x4000000000000000ULL))) { // x86 has some unusual NaNs which cannot be represented in any other // format; note them here. X86SpecialNan = true; } // If this is a truncation of a denormal number, and the target semantics // has larger exponent range than the source semantics (this can happen // when truncating from PowerPC double-double to double format), the // right shift could lose result mantissa bits. Adjust exponent instead // of performing excessive shift. if (shift < 0 && isFiniteNonZero()) { int exponentChange = significandMSB() + 1 - fromSemantics.precision; if (exponent + exponentChange < toSemantics.minExponent) exponentChange = toSemantics.minExponent - exponent; if (exponentChange < shift) exponentChange = shift; if (exponentChange < 0) { shift -= exponentChange; exponent += exponentChange; } } // If this is a truncation, perform the shift before we narrow the storage. if (shift < 0 && (isFiniteNonZero() || category==fcNaN)) lostFraction = shiftRight(significandParts(), oldPartCount, -shift); // Fix the storage so it can hold to new value. if (newPartCount > oldPartCount) { // The new type requires more storage; make it available. integerPart *newParts; newParts = new integerPart[newPartCount]; APInt::tcSet(newParts, 0, newPartCount); if (isFiniteNonZero() || category==fcNaN) APInt::tcAssign(newParts, significandParts(), oldPartCount); freeSignificand(); significand.parts = newParts; } else if (newPartCount == 1 && oldPartCount != 1) { // Switch to built-in storage for a single part. integerPart newPart = 0; if (isFiniteNonZero() || category==fcNaN) newPart = significandParts()[0]; freeSignificand(); significand.part = newPart; } // Now that we have the right storage, switch the semantics. semantics = &toSemantics; // If this is an extension, perform the shift now that the storage is // available. if (shift > 0 && (isFiniteNonZero() || category==fcNaN)) APInt::tcShiftLeft(significandParts(), newPartCount, shift); if (isFiniteNonZero()) { fs = normalize(rounding_mode, lostFraction); *losesInfo = (fs != opOK); } else if (category == fcNaN) { *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan; // For x87 extended precision, we want to make a NaN, not a special NaN if // the input wasn't special either. if (!X86SpecialNan && semantics == &semX87DoubleExtended) APInt::tcSetBit(significandParts(), semantics->precision - 1); // gcc forces the Quiet bit on, which means (float)(double)(float_sNan) // does not give you back the same bits. This is dubious, and we // don't currently do it. You're really supposed to get // an invalid operation signal at runtime, but nobody does that. fs = opOK; } else { *losesInfo = false; fs = opOK; } return fs; } /* Convert a floating point number to an integer according to the rounding mode. If the rounded integer value is out of range this returns an invalid operation exception and the contents of the destination parts are unspecified. If the rounded value is in range but the floating point number is not the exact integer, the C standard doesn't require an inexact exception to be raised. IEEE 854 does require it so we do that. Note that for conversions to integer type the C standard requires round-to-zero to always be used. */ IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger( MutableArrayRef parts, unsigned int width, bool isSigned, roundingMode rounding_mode, bool *isExact) const { lostFraction lost_fraction; const integerPart *src; unsigned int dstPartsCount, truncatedBits; *isExact = false; /* Handle the three special cases first. */ if (category == fcInfinity || category == fcNaN) return opInvalidOp; dstPartsCount = partCountForBits(width); assert(dstPartsCount <= parts.size() && "Integer too big"); if (category == fcZero) { APInt::tcSet(parts.data(), 0, dstPartsCount); // Negative zero can't be represented as an int. *isExact = !sign; return opOK; } src = significandParts(); /* Step 1: place our absolute value, with any fraction truncated, in the destination. */ if (exponent < 0) { /* Our absolute value is less than one; truncate everything. */ APInt::tcSet(parts.data(), 0, dstPartsCount); /* For exponent -1 the integer bit represents .5, look at that. For smaller exponents leftmost truncated bit is 0. */ truncatedBits = semantics->precision -1U - exponent; } else { /* We want the most significant (exponent + 1) bits; the rest are truncated. */ unsigned int bits = exponent + 1U; /* Hopelessly large in magnitude? */ if (bits > width) return opInvalidOp; if (bits < semantics->precision) { /* We truncate (semantics->precision - bits) bits. */ truncatedBits = semantics->precision - bits; APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits); } else { /* We want at least as many bits as are available. */ APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision, 0); APInt::tcShiftLeft(parts.data(), dstPartsCount, bits - semantics->precision); truncatedBits = 0; } } /* Step 2: work out any lost fraction, and increment the absolute value if we would round away from zero. */ if (truncatedBits) { lost_fraction = lostFractionThroughTruncation(src, partCount(), truncatedBits); if (lost_fraction != lfExactlyZero && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) { if (APInt::tcIncrement(parts.data(), dstPartsCount)) return opInvalidOp; /* Overflow. */ } } else { lost_fraction = lfExactlyZero; } /* Step 3: check if we fit in the destination. */ unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1; if (sign) { if (!isSigned) { /* Negative numbers cannot be represented as unsigned. */ if (omsb != 0) return opInvalidOp; } else { /* It takes omsb bits to represent the unsigned integer value. We lose a bit for the sign, but care is needed as the maximally negative integer is a special case. */ if (omsb == width && APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb) return opInvalidOp; /* This case can happen because of rounding. */ if (omsb > width) return opInvalidOp; } APInt::tcNegate (parts.data(), dstPartsCount); } else { if (omsb >= width + !isSigned) return opInvalidOp; } if (lost_fraction == lfExactlyZero) { *isExact = true; return opOK; } else return opInexact; } /* Same as convertToSignExtendedInteger, except we provide deterministic values in case of an invalid operation exception, namely zero for NaNs and the minimal or maximal value respectively for underflow or overflow. The *isExact output tells whether the result is exact, in the sense that converting it back to the original floating point type produces the original value. This is almost equivalent to result==opOK, except for negative zeroes. */ IEEEFloat::opStatus IEEEFloat::convertToInteger(MutableArrayRef parts, unsigned int width, bool isSigned, roundingMode rounding_mode, bool *isExact) const { opStatus fs; fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode, isExact); if (fs == opInvalidOp) { unsigned int bits, dstPartsCount; dstPartsCount = partCountForBits(width); assert(dstPartsCount <= parts.size() && "Integer too big"); if (category == fcNaN) bits = 0; else if (sign) bits = isSigned; else bits = width - isSigned; APInt::tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits); if (sign && isSigned) APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1); } return fs; } /* Convert an unsigned integer SRC to a floating point number, rounding according to ROUNDING_MODE. The sign of the floating point number is not modified. */ IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts( const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) { unsigned int omsb, precision, dstCount; integerPart *dst; lostFraction lost_fraction; category = fcNormal; omsb = APInt::tcMSB(src, srcCount) + 1; dst = significandParts(); dstCount = partCount(); precision = semantics->precision; /* We want the most significant PRECISION bits of SRC. There may not be that many; extract what we can. */ if (precision <= omsb) { exponent = omsb - 1; lost_fraction = lostFractionThroughTruncation(src, srcCount, omsb - precision); APInt::tcExtract(dst, dstCount, src, precision, omsb - precision); } else { exponent = precision - 1; lost_fraction = lfExactlyZero; APInt::tcExtract(dst, dstCount, src, omsb, 0); } return normalize(rounding_mode, lost_fraction); } IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned, roundingMode rounding_mode) { unsigned int partCount = Val.getNumWords(); APInt api = Val; sign = false; if (isSigned && api.isNegative()) { sign = true; api = -api; } return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode); } /* Convert a two's complement integer SRC to a floating point number, rounding according to ROUNDING_MODE. ISSIGNED is true if the integer is signed, in which case it must be sign-extended. */ IEEEFloat::opStatus IEEEFloat::convertFromSignExtendedInteger(const integerPart *src, unsigned int srcCount, bool isSigned, roundingMode rounding_mode) { opStatus status; if (isSigned && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) { integerPart *copy; /* If we're signed and negative negate a copy. */ sign = true; copy = new integerPart[srcCount]; APInt::tcAssign(copy, src, srcCount); APInt::tcNegate(copy, srcCount); status = convertFromUnsignedParts(copy, srcCount, rounding_mode); delete [] copy; } else { sign = false; status = convertFromUnsignedParts(src, srcCount, rounding_mode); } return status; } /* FIXME: should this just take a const APInt reference? */ IEEEFloat::opStatus IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts, unsigned int width, bool isSigned, roundingMode rounding_mode) { unsigned int partCount = partCountForBits(width); APInt api = APInt(width, makeArrayRef(parts, partCount)); sign = false; if (isSigned && APInt::tcExtractBit(parts, width - 1)) { sign = true; api = -api; } return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode); } Expected IEEEFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode) { lostFraction lost_fraction = lfExactlyZero; category = fcNormal; zeroSignificand(); exponent = 0; integerPart *significand = significandParts(); unsigned partsCount = partCount(); unsigned bitPos = partsCount * integerPartWidth; bool computedTrailingFraction = false; // Skip leading zeroes and any (hexa)decimal point. StringRef::iterator begin = s.begin(); StringRef::iterator end = s.end(); StringRef::iterator dot; auto PtrOrErr = skipLeadingZeroesAndAnyDot(begin, end, &dot); if (!PtrOrErr) return PtrOrErr.takeError(); StringRef::iterator p = *PtrOrErr; StringRef::iterator firstSignificantDigit = p; while (p != end) { integerPart hex_value; if (*p == '.') { if (dot != end) return createError("String contains multiple dots"); dot = p++; continue; } hex_value = hexDigitValue(*p); if (hex_value == -1U) break; p++; // Store the number while we have space. if (bitPos) { bitPos -= 4; hex_value <<= bitPos % integerPartWidth; significand[bitPos / integerPartWidth] |= hex_value; } else if (!computedTrailingFraction) { auto FractOrErr = trailingHexadecimalFraction(p, end, hex_value); if (!FractOrErr) return FractOrErr.takeError(); lost_fraction = *FractOrErr; computedTrailingFraction = true; } } /* Hex floats require an exponent but not a hexadecimal point. */ if (p == end) return createError("Hex strings require an exponent"); if (*p != 'p' && *p != 'P') return createError("Invalid character in significand"); if (p == begin) return createError("Significand has no digits"); if (dot != end && p - begin == 1) return createError("Significand has no digits"); /* Ignore the exponent if we are zero. */ if (p != firstSignificantDigit) { int expAdjustment; /* Implicit hexadecimal point? */ if (dot == end) dot = p; /* Calculate the exponent adjustment implicit in the number of significant digits. */ expAdjustment = static_cast(dot - firstSignificantDigit); if (expAdjustment < 0) expAdjustment++; expAdjustment = expAdjustment * 4 - 1; /* Adjust for writing the significand starting at the most significant nibble. */ expAdjustment += semantics->precision; expAdjustment -= partsCount * integerPartWidth; /* Adjust for the given exponent. */ auto ExpOrErr = totalExponent(p + 1, end, expAdjustment); if (!ExpOrErr) return ExpOrErr.takeError(); exponent = *ExpOrErr; } return normalize(rounding_mode, lost_fraction); } IEEEFloat::opStatus IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts, unsigned sigPartCount, int exp, roundingMode rounding_mode) { unsigned int parts, pow5PartCount; fltSemantics calcSemantics = { 32767, -32767, 0, 0 }; integerPart pow5Parts[maxPowerOfFiveParts]; bool isNearest; isNearest = (rounding_mode == rmNearestTiesToEven || rounding_mode == rmNearestTiesToAway); parts = partCountForBits(semantics->precision + 11); /* Calculate pow(5, abs(exp)). */ pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp); for (;; parts *= 2) { opStatus sigStatus, powStatus; unsigned int excessPrecision, truncatedBits; calcSemantics.precision = parts * integerPartWidth - 1; excessPrecision = calcSemantics.precision - semantics->precision; truncatedBits = excessPrecision; IEEEFloat decSig(calcSemantics, uninitialized); decSig.makeZero(sign); IEEEFloat pow5(calcSemantics); sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount, rmNearestTiesToEven); powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount, rmNearestTiesToEven); /* Add exp, as 10^n = 5^n * 2^n. */ decSig.exponent += exp; lostFraction calcLostFraction; integerPart HUerr, HUdistance; unsigned int powHUerr; if (exp >= 0) { /* multiplySignificand leaves the precision-th bit set to 1. */ calcLostFraction = decSig.multiplySignificand(pow5, nullptr); powHUerr = powStatus != opOK; } else { calcLostFraction = decSig.divideSignificand(pow5); /* Denormal numbers have less precision. */ if (decSig.exponent < semantics->minExponent) { excessPrecision += (semantics->minExponent - decSig.exponent); truncatedBits = excessPrecision; if (excessPrecision > calcSemantics.precision) excessPrecision = calcSemantics.precision; } /* Extra half-ulp lost in reciprocal of exponent. */ powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2; } /* Both multiplySignificand and divideSignificand return the result with the integer bit set. */ assert(APInt::tcExtractBit (decSig.significandParts(), calcSemantics.precision - 1) == 1); HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK, powHUerr); HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(), excessPrecision, isNearest); /* Are we guaranteed to round correctly if we truncate? */ if (HUdistance >= HUerr) { APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(), calcSemantics.precision - excessPrecision, excessPrecision); /* Take the exponent of decSig. If we tcExtract-ed less bits above we must adjust our exponent to compensate for the implicit right shift. */ exponent = (decSig.exponent + semantics->precision - (calcSemantics.precision - excessPrecision)); calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(), decSig.partCount(), truncatedBits); return normalize(rounding_mode, calcLostFraction); } } } Expected IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) { decimalInfo D; opStatus fs; /* Scan the text. */ StringRef::iterator p = str.begin(); if (Error Err = interpretDecimal(p, str.end(), &D)) return std::move(Err); /* Handle the quick cases. First the case of no significant digits, i.e. zero, and then exponents that are obviously too large or too small. Writing L for log 10 / log 2, a number d.ddddd*10^exp definitely overflows if (exp - 1) * L >= maxExponent and definitely underflows to zero where (exp + 1) * L <= minExponent - precision With integer arithmetic the tightest bounds for L are 93/28 < L < 196/59 [ numerator <= 256 ] 42039/12655 < L < 28738/8651 [ numerator <= 65536 ] */ // Test if we have a zero number allowing for strings with no null terminators // and zero decimals with non-zero exponents. // // We computed firstSigDigit by ignoring all zeros and dots. Thus if // D->firstSigDigit equals str.end(), every digit must be a zero and there can // be at most one dot. On the other hand, if we have a zero with a non-zero // exponent, then we know that D.firstSigDigit will be non-numeric. if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) { category = fcZero; fs = opOK; /* Check whether the normalized exponent is high enough to overflow max during the log-rebasing in the max-exponent check below. */ } else if (D.normalizedExponent - 1 > INT_MAX / 42039) { fs = handleOverflow(rounding_mode); /* If it wasn't, then it also wasn't high enough to overflow max during the log-rebasing in the min-exponent check. Check that it won't overflow min in either check, then perform the min-exponent check. */ } else if (D.normalizedExponent - 1 < INT_MIN / 42039 || (D.normalizedExponent + 1) * 28738 <= 8651 * (semantics->minExponent - (int) semantics->precision)) { /* Underflow to zero and round. */ category = fcNormal; zeroSignificand(); fs = normalize(rounding_mode, lfLessThanHalf); /* We can finally safely perform the max-exponent check. */ } else if ((D.normalizedExponent - 1) * 42039 >= 12655 * semantics->maxExponent) { /* Overflow and round. */ fs = handleOverflow(rounding_mode); } else { integerPart *decSignificand; unsigned int partCount; /* A tight upper bound on number of bits required to hold an N-digit decimal integer is N * 196 / 59. Allocate enough space to hold the full significand, and an extra part required by tcMultiplyPart. */ partCount = static_cast(D.lastSigDigit - D.firstSigDigit) + 1; partCount = partCountForBits(1 + 196 * partCount / 59); decSignificand = new integerPart[partCount + 1]; partCount = 0; /* Convert to binary efficiently - we do almost all multiplication in an integerPart. When this would overflow do we do a single bignum multiplication, and then revert again to multiplication in an integerPart. */ do { integerPart decValue, val, multiplier; val = 0; multiplier = 1; do { if (*p == '.') { p++; if (p == str.end()) { break; } } decValue = decDigitValue(*p++); if (decValue >= 10U) { delete[] decSignificand; return createError("Invalid character in significand"); } multiplier *= 10; val = val * 10 + decValue; /* The maximum number that can be multiplied by ten with any digit added without overflowing an integerPart. */ } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10); /* Multiply out the current part. */ APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val, partCount, partCount + 1, false); /* If we used another part (likely but not guaranteed), increase the count. */ if (decSignificand[partCount]) partCount++; } while (p <= D.lastSigDigit); category = fcNormal; fs = roundSignificandWithExponent(decSignificand, partCount, D.exponent, rounding_mode); delete [] decSignificand; } return fs; } bool IEEEFloat::convertFromStringSpecials(StringRef str) { if (str.equals("inf") || str.equals("INFINITY") || str.equals("+Inf")) { makeInf(false); return true; } if (str.equals("-inf") || str.equals("-INFINITY") || str.equals("-Inf")) { makeInf(true); return true; } if (str.equals("nan") || str.equals("NaN")) { makeNaN(false, false); return true; } if (str.equals("-nan") || str.equals("-NaN")) { makeNaN(false, true); return true; } return false; } Expected IEEEFloat::convertFromString(StringRef str, roundingMode rounding_mode) { if (str.empty()) return createError("Invalid string length"); // Handle special cases. if (convertFromStringSpecials(str)) return opOK; /* Handle a leading minus sign. */ StringRef::iterator p = str.begin(); size_t slen = str.size(); sign = *p == '-' ? 1 : 0; if (*p == '-' || *p == '+') { p++; slen--; if (!slen) return createError("String has no digits"); } if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) { if (slen == 2) return createError("Invalid string"); return convertFromHexadecimalString(StringRef(p + 2, slen - 2), rounding_mode); } return convertFromDecimalString(StringRef(p, slen), rounding_mode); } /* Write out a hexadecimal representation of the floating point value to DST, which must be of sufficient size, in the C99 form [-]0xh.hhhhp[+-]d. Return the number of characters written, excluding the terminating NUL. If UPPERCASE, the output is in upper case, otherwise in lower case. HEXDIGITS digits appear altogether, rounding the value if necessary. If HEXDIGITS is 0, the minimal precision to display the number precisely is used instead. If nothing would appear after the decimal point it is suppressed. The decimal exponent is always printed and has at least one digit. Zero values display an exponent of zero. Infinities and NaNs appear as "infinity" or "nan" respectively. The above rules are as specified by C99. There is ambiguity about what the leading hexadecimal digit should be. This implementation uses whatever is necessary so that the exponent is displayed as stored. This implies the exponent will fall within the IEEE format range, and the leading hexadecimal digit will be 0 (for denormals), 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with any other digits zero). */ unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits, bool upperCase, roundingMode rounding_mode) const { char *p; p = dst; if (sign) *dst++ = '-'; switch (category) { case fcInfinity: memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1); dst += sizeof infinityL - 1; break; case fcNaN: memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1); dst += sizeof NaNU - 1; break; case fcZero: *dst++ = '0'; *dst++ = upperCase ? 'X': 'x'; *dst++ = '0'; if (hexDigits > 1) { *dst++ = '.'; memset (dst, '0', hexDigits - 1); dst += hexDigits - 1; } *dst++ = upperCase ? 'P': 'p'; *dst++ = '0'; break; case fcNormal: dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode); break; } *dst = 0; return static_cast(dst - p); } /* Does the hard work of outputting the correctly rounded hexadecimal form of a normal floating point number with the specified number of hexadecimal digits. If HEXDIGITS is zero the minimum number of digits necessary to print the value precisely is output. */ char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits, bool upperCase, roundingMode rounding_mode) const { unsigned int count, valueBits, shift, partsCount, outputDigits; const char *hexDigitChars; const integerPart *significand; char *p; bool roundUp; *dst++ = '0'; *dst++ = upperCase ? 'X': 'x'; roundUp = false; hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower; significand = significandParts(); partsCount = partCount(); /* +3 because the first digit only uses the single integer bit, so we have 3 virtual zero most-significant-bits. */ valueBits = semantics->precision + 3; shift = integerPartWidth - valueBits % integerPartWidth; /* The natural number of digits required ignoring trailing insignificant zeroes. */ outputDigits = (valueBits - significandLSB () + 3) / 4; /* hexDigits of zero means use the required number for the precision. Otherwise, see if we are truncating. If we are, find out if we need to round away from zero. */ if (hexDigits) { if (hexDigits < outputDigits) { /* We are dropping non-zero bits, so need to check how to round. "bits" is the number of dropped bits. */ unsigned int bits; lostFraction fraction; bits = valueBits - hexDigits * 4; fraction = lostFractionThroughTruncation (significand, partsCount, bits); roundUp = roundAwayFromZero(rounding_mode, fraction, bits); } outputDigits = hexDigits; } /* Write the digits consecutively, and start writing in the location of the hexadecimal point. We move the most significant digit left and add the hexadecimal point later. */ p = ++dst; count = (valueBits + integerPartWidth - 1) / integerPartWidth; while (outputDigits && count) { integerPart part; /* Put the most significant integerPartWidth bits in "part". */ if (--count == partsCount) part = 0; /* An imaginary higher zero part. */ else part = significand[count] << shift; if (count && shift) part |= significand[count - 1] >> (integerPartWidth - shift); /* Convert as much of "part" to hexdigits as we can. */ unsigned int curDigits = integerPartWidth / 4; if (curDigits > outputDigits) curDigits = outputDigits; dst += partAsHex (dst, part, curDigits, hexDigitChars); outputDigits -= curDigits; } if (roundUp) { char *q = dst; /* Note that hexDigitChars has a trailing '0'. */ do { q--; *q = hexDigitChars[hexDigitValue (*q) + 1]; } while (*q == '0'); assert(q >= p); } else { /* Add trailing zeroes. */ memset (dst, '0', outputDigits); dst += outputDigits; } /* Move the most significant digit to before the point, and if there is something after the decimal point add it. This must come after rounding above. */ p[-1] = p[0]; if (dst -1 == p) dst--; else p[0] = '.'; /* Finally output the exponent. */ *dst++ = upperCase ? 'P': 'p'; return writeSignedDecimal (dst, exponent); } hash_code hash_value(const IEEEFloat &Arg) { if (!Arg.isFiniteNonZero()) return hash_combine((uint8_t)Arg.category, // NaN has no sign, fix it at zero. Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign, Arg.semantics->precision); // Normal floats need their exponent and significand hashed. return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign, Arg.semantics->precision, Arg.exponent, hash_combine_range( Arg.significandParts(), Arg.significandParts() + Arg.partCount())); } // Conversion from APFloat to/from host float/double. It may eventually be // possible to eliminate these and have everybody deal with APFloats, but that // will take a while. This approach will not easily extend to long double. // Current implementation requires integerPartWidth==64, which is correct at // the moment but could be made more general. // Denormals have exponent minExponent in APFloat, but minExponent-1 in // the actual IEEE respresentations. We compensate for that here. APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended); assert(partCount()==2); uint64_t myexponent, mysignificand; if (isFiniteNonZero()) { myexponent = exponent+16383; //bias mysignificand = significandParts()[0]; if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL)) myexponent = 0; // denormal } else if (category==fcZero) { myexponent = 0; mysignificand = 0; } else if (category==fcInfinity) { myexponent = 0x7fff; mysignificand = 0x8000000000000000ULL; } else { assert(category == fcNaN && "Unknown category"); myexponent = 0x7fff; mysignificand = significandParts()[0]; } uint64_t words[2]; words[0] = mysignificand; words[1] = ((uint64_t)(sign & 1) << 15) | (myexponent & 0x7fffLL); return APInt(80, words); } APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy); assert(partCount()==2); uint64_t words[2]; opStatus fs; bool losesInfo; // Convert number to double. To avoid spurious underflows, we re- // normalize against the "double" minExponent first, and only *then* // truncate the mantissa. The result of that second conversion // may be inexact, but should never underflow. // Declare fltSemantics before APFloat that uses it (and // saves pointer to it) to ensure correct destruction order. fltSemantics extendedSemantics = *semantics; extendedSemantics.minExponent = semIEEEdouble.minExponent; IEEEFloat extended(*this); fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo); assert(fs == opOK && !losesInfo); (void)fs; IEEEFloat u(extended); fs = u.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo); assert(fs == opOK || fs == opInexact); (void)fs; words[0] = *u.convertDoubleAPFloatToAPInt().getRawData(); // If conversion was exact or resulted in a special case, we're done; // just set the second double to zero. Otherwise, re-convert back to // the extended format and compute the difference. This now should // convert exactly to double. if (u.isFiniteNonZero() && losesInfo) { fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo); assert(fs == opOK && !losesInfo); (void)fs; IEEEFloat v(extended); v.subtract(u, rmNearestTiesToEven); fs = v.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo); assert(fs == opOK && !losesInfo); (void)fs; words[1] = *v.convertDoubleAPFloatToAPInt().getRawData(); } else { words[1] = 0; } return APInt(128, words); } APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics*)&semIEEEquad); assert(partCount()==2); uint64_t myexponent, mysignificand, mysignificand2; if (isFiniteNonZero()) { myexponent = exponent+16383; //bias mysignificand = significandParts()[0]; mysignificand2 = significandParts()[1]; if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL)) myexponent = 0; // denormal } else if (category==fcZero) { myexponent = 0; mysignificand = mysignificand2 = 0; } else if (category==fcInfinity) { myexponent = 0x7fff; mysignificand = mysignificand2 = 0; } else { assert(category == fcNaN && "Unknown category!"); myexponent = 0x7fff; mysignificand = significandParts()[0]; mysignificand2 = significandParts()[1]; } uint64_t words[2]; words[0] = mysignificand; words[1] = ((uint64_t)(sign & 1) << 63) | ((myexponent & 0x7fff) << 48) | (mysignificand2 & 0xffffffffffffLL); return APInt(128, words); } APInt IEEEFloat::convertDoubleAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble); assert(partCount()==1); uint64_t myexponent, mysignificand; if (isFiniteNonZero()) { myexponent = exponent+1023; //bias mysignificand = *significandParts(); if (myexponent==1 && !(mysignificand & 0x10000000000000LL)) myexponent = 0; // denormal } else if (category==fcZero) { myexponent = 0; mysignificand = 0; } else if (category==fcInfinity) { myexponent = 0x7ff; mysignificand = 0; } else { assert(category == fcNaN && "Unknown category!"); myexponent = 0x7ff; mysignificand = *significandParts(); } return APInt(64, ((((uint64_t)(sign & 1) << 63) | ((myexponent & 0x7ff) << 52) | (mysignificand & 0xfffffffffffffLL)))); } APInt IEEEFloat::convertFloatAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle); assert(partCount()==1); uint32_t myexponent, mysignificand; if (isFiniteNonZero()) { myexponent = exponent+127; //bias mysignificand = (uint32_t)*significandParts(); if (myexponent == 1 && !(mysignificand & 0x800000)) myexponent = 0; // denormal } else if (category==fcZero) { myexponent = 0; mysignificand = 0; } else if (category==fcInfinity) { myexponent = 0xff; mysignificand = 0; } else { assert(category == fcNaN && "Unknown category!"); myexponent = 0xff; mysignificand = (uint32_t)*significandParts(); } return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) | (mysignificand & 0x7fffff))); } APInt IEEEFloat::convertHalfAPFloatToAPInt() const { assert(semantics == (const llvm::fltSemantics*)&semIEEEhalf); assert(partCount()==1); uint32_t myexponent, mysignificand; if (isFiniteNonZero()) { myexponent = exponent+15; //bias mysignificand = (uint32_t)*significandParts(); if (myexponent == 1 && !(mysignificand & 0x400)) myexponent = 0; // denormal } else if (category==fcZero) { myexponent = 0; mysignificand = 0; } else if (category==fcInfinity) { myexponent = 0x1f; mysignificand = 0; } else { assert(category == fcNaN && "Unknown category!"); myexponent = 0x1f; mysignificand = (uint32_t)*significandParts(); } return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) | (mysignificand & 0x3ff))); } // This function creates an APInt that is just a bit map of the floating // point constant as it would appear in memory. It is not a conversion, // and treating the result as a normal integer is unlikely to be useful. APInt IEEEFloat::bitcastToAPInt() const { if (semantics == (const llvm::fltSemantics*)&semIEEEhalf) return convertHalfAPFloatToAPInt(); if (semantics == (const llvm::fltSemantics*)&semIEEEsingle) return convertFloatAPFloatToAPInt(); if (semantics == (const llvm::fltSemantics*)&semIEEEdouble) return convertDoubleAPFloatToAPInt(); if (semantics == (const llvm::fltSemantics*)&semIEEEquad) return convertQuadrupleAPFloatToAPInt(); if (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy) return convertPPCDoubleDoubleAPFloatToAPInt(); assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended && "unknown format!"); return convertF80LongDoubleAPFloatToAPInt(); } float IEEEFloat::convertToFloat() const { assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle && "Float semantics are not IEEEsingle"); APInt api = bitcastToAPInt(); return api.bitsToFloat(); } double IEEEFloat::convertToDouble() const { assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble && "Float semantics are not IEEEdouble"); APInt api = bitcastToAPInt(); return api.bitsToDouble(); } /// Integer bit is explicit in this format. Intel hardware (387 and later) /// does not support these bit patterns: /// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity") /// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN") /// exponent!=0 nor all 1's, integer bit 0 ("unnormal") /// exponent = 0, integer bit 1 ("pseudodenormal") /// At the moment, the first three are treated as NaNs, the last one as Normal. void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) { assert(api.getBitWidth()==80); uint64_t i1 = api.getRawData()[0]; uint64_t i2 = api.getRawData()[1]; uint64_t myexponent = (i2 & 0x7fff); uint64_t mysignificand = i1; uint8_t myintegerbit = mysignificand >> 63; initialize(&semX87DoubleExtended); assert(partCount()==2); sign = static_cast(i2>>15); if (myexponent == 0 && mysignificand == 0) { // exponent, significand meaningless category = fcZero; } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) { // exponent, significand meaningless category = fcInfinity; } else if ((myexponent == 0x7fff && mysignificand != 0x8000000000000000ULL) || (myexponent != 0x7fff && myexponent != 0 && myintegerbit == 0)) { // exponent meaningless category = fcNaN; significandParts()[0] = mysignificand; significandParts()[1] = 0; } else { category = fcNormal; exponent = myexponent - 16383; significandParts()[0] = mysignificand; significandParts()[1] = 0; if (myexponent==0) // denormal exponent = -16382; } } void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) { assert(api.getBitWidth()==128); uint64_t i1 = api.getRawData()[0]; uint64_t i2 = api.getRawData()[1]; opStatus fs; bool losesInfo; // Get the first double and convert to our format. initFromDoubleAPInt(APInt(64, i1)); fs = convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo); assert(fs == opOK && !losesInfo); (void)fs; // Unless we have a special case, add in second double. if (isFiniteNonZero()) { IEEEFloat v(semIEEEdouble, APInt(64, i2)); fs = v.convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo); assert(fs == opOK && !losesInfo); (void)fs; add(v, rmNearestTiesToEven); } } void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) { assert(api.getBitWidth()==128); uint64_t i1 = api.getRawData()[0]; uint64_t i2 = api.getRawData()[1]; uint64_t myexponent = (i2 >> 48) & 0x7fff; uint64_t mysignificand = i1; uint64_t mysignificand2 = i2 & 0xffffffffffffLL; initialize(&semIEEEquad); assert(partCount()==2); sign = static_cast(i2>>63); if (myexponent==0 && (mysignificand==0 && mysignificand2==0)) { // exponent, significand meaningless category = fcZero; } else if (myexponent==0x7fff && (mysignificand==0 && mysignificand2==0)) { // exponent, significand meaningless category = fcInfinity; } else if (myexponent==0x7fff && (mysignificand!=0 || mysignificand2 !=0)) { // exponent meaningless category = fcNaN; significandParts()[0] = mysignificand; significandParts()[1] = mysignificand2; } else { category = fcNormal; exponent = myexponent - 16383; significandParts()[0] = mysignificand; significandParts()[1] = mysignificand2; if (myexponent==0) // denormal exponent = -16382; else significandParts()[1] |= 0x1000000000000LL; // integer bit } } void IEEEFloat::initFromDoubleAPInt(const APInt &api) { assert(api.getBitWidth()==64); uint64_t i = *api.getRawData(); uint64_t myexponent = (i >> 52) & 0x7ff; uint64_t mysignificand = i & 0xfffffffffffffLL; initialize(&semIEEEdouble); assert(partCount()==1); sign = static_cast(i>>63); if (myexponent==0 && mysignificand==0) { // exponent, significand meaningless category = fcZero; } else if (myexponent==0x7ff && mysignificand==0) { // exponent, significand meaningless category = fcInfinity; } else if (myexponent==0x7ff && mysignificand!=0) { // exponent meaningless category = fcNaN; *significandParts() = mysignificand; } else { category = fcNormal; exponent = myexponent - 1023; *significandParts() = mysignificand; if (myexponent==0) // denormal exponent = -1022; else *significandParts() |= 0x10000000000000LL; // integer bit } } void IEEEFloat::initFromFloatAPInt(const APInt &api) { assert(api.getBitWidth()==32); uint32_t i = (uint32_t)*api.getRawData(); uint32_t myexponent = (i >> 23) & 0xff; uint32_t mysignificand = i & 0x7fffff; initialize(&semIEEEsingle); assert(partCount()==1); sign = i >> 31; if (myexponent==0 && mysignificand==0) { // exponent, significand meaningless category = fcZero; } else if (myexponent==0xff && mysignificand==0) { // exponent, significand meaningless category = fcInfinity; } else if (myexponent==0xff && mysignificand!=0) { // sign, exponent, significand meaningless category = fcNaN; *significandParts() = mysignificand; } else { category = fcNormal; exponent = myexponent - 127; //bias *significandParts() = mysignificand; if (myexponent==0) // denormal exponent = -126; else *significandParts() |= 0x800000; // integer bit } } void IEEEFloat::initFromHalfAPInt(const APInt &api) { assert(api.getBitWidth()==16); uint32_t i = (uint32_t)*api.getRawData(); uint32_t myexponent = (i >> 10) & 0x1f; uint32_t mysignificand = i & 0x3ff; initialize(&semIEEEhalf); assert(partCount()==1); sign = i >> 15; if (myexponent==0 && mysignificand==0) { // exponent, significand meaningless category = fcZero; } else if (myexponent==0x1f && mysignificand==0) { // exponent, significand meaningless category = fcInfinity; } else if (myexponent==0x1f && mysignificand!=0) { // sign, exponent, significand meaningless category = fcNaN; *significandParts() = mysignificand; } else { category = fcNormal; exponent = myexponent - 15; //bias *significandParts() = mysignificand; if (myexponent==0) // denormal exponent = -14; else *significandParts() |= 0x400; // integer bit } } /// Treat api as containing the bits of a floating point number. Currently /// we infer the floating point type from the size of the APInt. The /// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful /// when the size is anything else). void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) { if (Sem == &semIEEEhalf) return initFromHalfAPInt(api); if (Sem == &semIEEEsingle) return initFromFloatAPInt(api); if (Sem == &semIEEEdouble) return initFromDoubleAPInt(api); if (Sem == &semX87DoubleExtended) return initFromF80LongDoubleAPInt(api); if (Sem == &semIEEEquad) return initFromQuadrupleAPInt(api); if (Sem == &semPPCDoubleDoubleLegacy) return initFromPPCDoubleDoubleAPInt(api); llvm_unreachable(nullptr); } /// Make this number the largest magnitude normal number in the given /// semantics. void IEEEFloat::makeLargest(bool Negative) { // We want (in interchange format): // sign = {Negative} // exponent = 1..10 // significand = 1..1 category = fcNormal; sign = Negative; exponent = semantics->maxExponent; // Use memset to set all but the highest integerPart to all ones. integerPart *significand = significandParts(); unsigned PartCount = partCount(); memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1)); // Set the high integerPart especially setting all unused top bits for // internal consistency. const unsigned NumUnusedHighBits = PartCount*integerPartWidth - semantics->precision; significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth) ? (~integerPart(0) >> NumUnusedHighBits) : 0; } /// Make this number the smallest magnitude denormal number in the given /// semantics. void IEEEFloat::makeSmallest(bool Negative) { // We want (in interchange format): // sign = {Negative} // exponent = 0..0 // significand = 0..01 category = fcNormal; sign = Negative; exponent = semantics->minExponent; APInt::tcSet(significandParts(), 1, partCount()); } void IEEEFloat::makeSmallestNormalized(bool Negative) { // We want (in interchange format): // sign = {Negative} // exponent = 0..0 // significand = 10..0 category = fcNormal; zeroSignificand(); sign = Negative; exponent = semantics->minExponent; significandParts()[partCountForBits(semantics->precision) - 1] |= (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth)); } IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) { initFromAPInt(&Sem, API); } IEEEFloat::IEEEFloat(float f) { initFromAPInt(&semIEEEsingle, APInt::floatToBits(f)); } IEEEFloat::IEEEFloat(double d) { initFromAPInt(&semIEEEdouble, APInt::doubleToBits(d)); } namespace { void append(SmallVectorImpl &Buffer, StringRef Str) { Buffer.append(Str.begin(), Str.end()); } /// Removes data from the given significand until it is no more /// precise than is required for the desired precision. void AdjustToPrecision(APInt &significand, int &exp, unsigned FormatPrecision) { unsigned bits = significand.getActiveBits(); // 196/59 is a very slight overestimate of lg_2(10). unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59; if (bits <= bitsRequired) return; unsigned tensRemovable = (bits - bitsRequired) * 59 / 196; if (!tensRemovable) return; exp += tensRemovable; APInt divisor(significand.getBitWidth(), 1); APInt powten(significand.getBitWidth(), 10); while (true) { if (tensRemovable & 1) divisor *= powten; tensRemovable >>= 1; if (!tensRemovable) break; powten *= powten; } significand = significand.udiv(divisor); // Truncate the significand down to its active bit count. significand = significand.trunc(significand.getActiveBits()); } void AdjustToPrecision(SmallVectorImpl &buffer, int &exp, unsigned FormatPrecision) { unsigned N = buffer.size(); if (N <= FormatPrecision) return; // The most significant figures are the last ones in the buffer. unsigned FirstSignificant = N - FormatPrecision; // Round. // FIXME: this probably shouldn't use 'round half up'. // Rounding down is just a truncation, except we also want to drop // trailing zeros from the new result. if (buffer[FirstSignificant - 1] < '5') { while (FirstSignificant < N && buffer[FirstSignificant] == '0') FirstSignificant++; exp += FirstSignificant; buffer.erase(&buffer[0], &buffer[FirstSignificant]); return; } // Rounding up requires a decimal add-with-carry. If we continue // the carry, the newly-introduced zeros will just be truncated. for (unsigned I = FirstSignificant; I != N; ++I) { if (buffer[I] == '9') { FirstSignificant++; } else { buffer[I]++; break; } } // If we carried through, we have exactly one digit of precision. if (FirstSignificant == N) { exp += FirstSignificant; buffer.clear(); buffer.push_back('1'); return; } exp += FirstSignificant; buffer.erase(&buffer[0], &buffer[FirstSignificant]); } } void IEEEFloat::toString(SmallVectorImpl &Str, unsigned FormatPrecision, unsigned FormatMaxPadding, bool TruncateZero) const { switch (category) { case fcInfinity: if (isNegative()) return append(Str, "-Inf"); else return append(Str, "+Inf"); case fcNaN: return append(Str, "NaN"); case fcZero: if (isNegative()) Str.push_back('-'); if (!FormatMaxPadding) { if (TruncateZero) append(Str, "0.0E+0"); else { append(Str, "0.0"); if (FormatPrecision > 1) Str.append(FormatPrecision - 1, '0'); append(Str, "e+00"); } } else Str.push_back('0'); return; case fcNormal: break; } if (isNegative()) Str.push_back('-'); // Decompose the number into an APInt and an exponent. int exp = exponent - ((int) semantics->precision - 1); APInt significand(semantics->precision, makeArrayRef(significandParts(), partCountForBits(semantics->precision))); // Set FormatPrecision if zero. We want to do this before we // truncate trailing zeros, as those are part of the precision. if (!FormatPrecision) { // We use enough digits so the number can be round-tripped back to an // APFloat. The formula comes from "How to Print Floating-Point Numbers // Accurately" by Steele and White. // FIXME: Using a formula based purely on the precision is conservative; // we can print fewer digits depending on the actual value being printed. // FormatPrecision = 2 + floor(significandBits / lg_2(10)) FormatPrecision = 2 + semantics->precision * 59 / 196; } // Ignore trailing binary zeros. int trailingZeros = significand.countTrailingZeros(); exp += trailingZeros; significand.lshrInPlace(trailingZeros); // Change the exponent from 2^e to 10^e. if (exp == 0) { // Nothing to do. } else if (exp > 0) { // Just shift left. significand = significand.zext(semantics->precision + exp); significand <<= exp; exp = 0; } else { /* exp < 0 */ int texp = -exp; // We transform this using the identity: // (N)(2^-e) == (N)(5^e)(10^-e) // This means we have to multiply N (the significand) by 5^e. // To avoid overflow, we have to operate on numbers large // enough to store N * 5^e: // log2(N * 5^e) == log2(N) + e * log2(5) // <= semantics->precision + e * 137 / 59 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59) unsigned precision = semantics->precision + (137 * texp + 136) / 59; // Multiply significand by 5^e. // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8) significand = significand.zext(precision); APInt five_to_the_i(precision, 5); while (true) { if (texp & 1) significand *= five_to_the_i; texp >>= 1; if (!texp) break; five_to_the_i *= five_to_the_i; } } AdjustToPrecision(significand, exp, FormatPrecision); SmallVector buffer; // Fill the buffer. unsigned precision = significand.getBitWidth(); APInt ten(precision, 10); APInt digit(precision, 0); bool inTrail = true; while (significand != 0) { // digit <- significand % 10 // significand <- significand / 10 APInt::udivrem(significand, ten, significand, digit); unsigned d = digit.getZExtValue(); // Drop trailing zeros. if (inTrail && !d) exp++; else { buffer.push_back((char) ('0' + d)); inTrail = false; } } assert(!buffer.empty() && "no characters in buffer!"); // Drop down to FormatPrecision. // TODO: don't do more precise calculations above than are required. AdjustToPrecision(buffer, exp, FormatPrecision); unsigned NDigits = buffer.size(); // Check whether we should use scientific notation. bool FormatScientific; if (!FormatMaxPadding) FormatScientific = true; else { if (exp >= 0) { // 765e3 --> 765000 // ^^^ // But we shouldn't make the number look more precise than it is. FormatScientific = ((unsigned) exp > FormatMaxPadding || NDigits + (unsigned) exp > FormatPrecision); } else { // Power of the most significant digit. int MSD = exp + (int) (NDigits - 1); if (MSD >= 0) { // 765e-2 == 7.65 FormatScientific = false; } else { // 765e-5 == 0.00765 // ^ ^^ FormatScientific = ((unsigned) -MSD) > FormatMaxPadding; } } } // Scientific formatting is pretty straightforward. if (FormatScientific) { exp += (NDigits - 1); Str.push_back(buffer[NDigits-1]); Str.push_back('.'); if (NDigits == 1 && TruncateZero) Str.push_back('0'); else for (unsigned I = 1; I != NDigits; ++I) Str.push_back(buffer[NDigits-1-I]); // Fill with zeros up to FormatPrecision. if (!TruncateZero && FormatPrecision > NDigits - 1) Str.append(FormatPrecision - NDigits + 1, '0'); // For !TruncateZero we use lower 'e'. Str.push_back(TruncateZero ? 'E' : 'e'); Str.push_back(exp >= 0 ? '+' : '-'); if (exp < 0) exp = -exp; SmallVector expbuf; do { expbuf.push_back((char) ('0' + (exp % 10))); exp /= 10; } while (exp); // Exponent always at least two digits if we do not truncate zeros. if (!TruncateZero && expbuf.size() < 2) expbuf.push_back('0'); for (unsigned I = 0, E = expbuf.size(); I != E; ++I) Str.push_back(expbuf[E-1-I]); return; } // Non-scientific, positive exponents. if (exp >= 0) { for (unsigned I = 0; I != NDigits; ++I) Str.push_back(buffer[NDigits-1-I]); for (unsigned I = 0; I != (unsigned) exp; ++I) Str.push_back('0'); return; } // Non-scientific, negative exponents. // The number of digits to the left of the decimal point. int NWholeDigits = exp + (int) NDigits; unsigned I = 0; if (NWholeDigits > 0) { for (; I != (unsigned) NWholeDigits; ++I) Str.push_back(buffer[NDigits-I-1]); Str.push_back('.'); } else { unsigned NZeros = 1 + (unsigned) -NWholeDigits; Str.push_back('0'); Str.push_back('.'); for (unsigned Z = 1; Z != NZeros; ++Z) Str.push_back('0'); } for (; I != NDigits; ++I) Str.push_back(buffer[NDigits-I-1]); } bool IEEEFloat::getExactInverse(APFloat *inv) const { // Special floats and denormals have no exact inverse. if (!isFiniteNonZero()) return false; // Check that the number is a power of two by making sure that only the // integer bit is set in the significand. if (significandLSB() != semantics->precision - 1) return false; // Get the inverse. IEEEFloat reciprocal(*semantics, 1ULL); if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK) return false; // Avoid multiplication with a denormal, it is not safe on all platforms and // may be slower than a normal division. if (reciprocal.isDenormal()) return false; assert(reciprocal.isFiniteNonZero() && reciprocal.significandLSB() == reciprocal.semantics->precision - 1); if (inv) *inv = APFloat(reciprocal, *semantics); return true; } bool IEEEFloat::isSignaling() const { if (!isNaN()) return false; // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the // first bit of the trailing significand being 0. return !APInt::tcExtractBit(significandParts(), semantics->precision - 2); } /// IEEE-754R 2008 5.3.1: nextUp/nextDown. /// /// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with /// appropriate sign switching before/after the computation. IEEEFloat::opStatus IEEEFloat::next(bool nextDown) { // If we are performing nextDown, swap sign so we have -x. if (nextDown) changeSign(); // Compute nextUp(x) opStatus result = opOK; // Handle each float category separately. switch (category) { case fcInfinity: // nextUp(+inf) = +inf if (!isNegative()) break; // nextUp(-inf) = -getLargest() makeLargest(true); break; case fcNaN: // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag. // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not // change the payload. if (isSignaling()) { result = opInvalidOp; // For consistency, propagate the sign of the sNaN to the qNaN. makeNaN(false, isNegative(), nullptr); } break; case fcZero: // nextUp(pm 0) = +getSmallest() makeSmallest(false); break; case fcNormal: // nextUp(-getSmallest()) = -0 if (isSmallest() && isNegative()) { APInt::tcSet(significandParts(), 0, partCount()); category = fcZero; exponent = 0; break; } // nextUp(getLargest()) == INFINITY if (isLargest() && !isNegative()) { APInt::tcSet(significandParts(), 0, partCount()); category = fcInfinity; exponent = semantics->maxExponent + 1; break; } // nextUp(normal) == normal + inc. if (isNegative()) { // If we are negative, we need to decrement the significand. // We only cross a binade boundary that requires adjusting the exponent // if: // 1. exponent != semantics->minExponent. This implies we are not in the // smallest binade or are dealing with denormals. // 2. Our significand excluding the integral bit is all zeros. bool WillCrossBinadeBoundary = exponent != semantics->minExponent && isSignificandAllZeros(); // Decrement the significand. // // We always do this since: // 1. If we are dealing with a non-binade decrement, by definition we // just decrement the significand. // 2. If we are dealing with a normal -> normal binade decrement, since // we have an explicit integral bit the fact that all bits but the // integral bit are zero implies that subtracting one will yield a // significand with 0 integral bit and 1 in all other spots. Thus we // must just adjust the exponent and set the integral bit to 1. // 3. If we are dealing with a normal -> denormal binade decrement, // since we set the integral bit to 0 when we represent denormals, we // just decrement the significand. integerPart *Parts = significandParts(); APInt::tcDecrement(Parts, partCount()); if (WillCrossBinadeBoundary) { // Our result is a normal number. Do the following: // 1. Set the integral bit to 1. // 2. Decrement the exponent. APInt::tcSetBit(Parts, semantics->precision - 1); exponent--; } } else { // If we are positive, we need to increment the significand. // We only cross a binade boundary that requires adjusting the exponent if // the input is not a denormal and all of said input's significand bits // are set. If all of said conditions are true: clear the significand, set // the integral bit to 1, and increment the exponent. If we have a // denormal always increment since moving denormals and the numbers in the // smallest normal binade have the same exponent in our representation. bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes(); if (WillCrossBinadeBoundary) { integerPart *Parts = significandParts(); APInt::tcSet(Parts, 0, partCount()); APInt::tcSetBit(Parts, semantics->precision - 1); assert(exponent != semantics->maxExponent && "We can not increment an exponent beyond the maxExponent allowed" " by the given floating point semantics."); exponent++; } else { incrementSignificand(); } } break; } // If we are performing nextDown, swap sign so we have -nextUp(-x) if (nextDown) changeSign(); return result; } void IEEEFloat::makeInf(bool Negative) { category = fcInfinity; sign = Negative; exponent = semantics->maxExponent + 1; APInt::tcSet(significandParts(), 0, partCount()); } void IEEEFloat::makeZero(bool Negative) { category = fcZero; sign = Negative; exponent = semantics->minExponent-1; APInt::tcSet(significandParts(), 0, partCount()); } void IEEEFloat::makeQuiet() { assert(isNaN()); APInt::tcSetBit(significandParts(), semantics->precision - 2); } int ilogb(const IEEEFloat &Arg) { if (Arg.isNaN()) return IEEEFloat::IEK_NaN; if (Arg.isZero()) return IEEEFloat::IEK_Zero; if (Arg.isInfinity()) return IEEEFloat::IEK_Inf; if (!Arg.isDenormal()) return Arg.exponent; IEEEFloat Normalized(Arg); int SignificandBits = Arg.getSemantics().precision - 1; Normalized.exponent += SignificandBits; Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero); return Normalized.exponent - SignificandBits; } IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) { auto MaxExp = X.getSemantics().maxExponent; auto MinExp = X.getSemantics().minExponent; // If Exp is wildly out-of-scale, simply adding it to X.exponent will // overflow; clamp it to a safe range before adding, but ensure that the range // is large enough that the clamp does not change the result. The range we // need to support is the difference between the largest possible exponent and // the normalized exponent of half the smallest denormal. int SignificandBits = X.getSemantics().precision - 1; int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1; // Clamp to one past the range ends to let normalize handle overlflow. X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement); X.normalize(RoundingMode, lfExactlyZero); if (X.isNaN()) X.makeQuiet(); return X; } IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) { Exp = ilogb(Val); // Quiet signalling nans. if (Exp == IEEEFloat::IEK_NaN) { IEEEFloat Quiet(Val); Quiet.makeQuiet(); return Quiet; } if (Exp == IEEEFloat::IEK_Inf) return Val; // 1 is added because frexp is defined to return a normalized fraction in // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0). Exp = Exp == IEEEFloat::IEK_Zero ? 0 : Exp + 1; return scalbn(Val, -Exp, RM); } DoubleAPFloat::DoubleAPFloat(const fltSemantics &S) : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble), APFloat(semIEEEdouble)}) { assert(Semantics == &semPPCDoubleDouble); } DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag) : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble, uninitialized), APFloat(semIEEEdouble, uninitialized)}) { assert(Semantics == &semPPCDoubleDouble); } DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I) : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble, I), APFloat(semIEEEdouble)}) { assert(Semantics == &semPPCDoubleDouble); } DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I) : Semantics(&S), Floats(new APFloat[2]{ APFloat(semIEEEdouble, APInt(64, I.getRawData()[0])), APFloat(semIEEEdouble, APInt(64, I.getRawData()[1]))}) { assert(Semantics == &semPPCDoubleDouble); } DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First, APFloat &&Second) : Semantics(&S), Floats(new APFloat[2]{std::move(First), std::move(Second)}) { assert(Semantics == &semPPCDoubleDouble); assert(&Floats[0].getSemantics() == &semIEEEdouble); assert(&Floats[1].getSemantics() == &semIEEEdouble); } DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS) : Semantics(RHS.Semantics), Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]), APFloat(RHS.Floats[1])} : nullptr) { assert(Semantics == &semPPCDoubleDouble); } DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS) : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) { RHS.Semantics = &semBogus; assert(Semantics == &semPPCDoubleDouble); } DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) { if (Semantics == RHS.Semantics && RHS.Floats) { Floats[0] = RHS.Floats[0]; Floats[1] = RHS.Floats[1]; } else if (this != &RHS) { this->~DoubleAPFloat(); new (this) DoubleAPFloat(RHS); } return *this; } // Implement addition, subtraction, multiplication and division based on: // "Software for Doubled-Precision Floating-Point Computations", // by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283. APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa, const APFloat &c, const APFloat &cc, roundingMode RM) { int Status = opOK; APFloat z = a; Status |= z.add(c, RM); if (!z.isFinite()) { if (!z.isInfinity()) { Floats[0] = std::move(z); Floats[1].makeZero(/* Neg = */ false); return (opStatus)Status; } Status = opOK; auto AComparedToC = a.compareAbsoluteValue(c); z = cc; Status |= z.add(aa, RM); if (AComparedToC == APFloat::cmpGreaterThan) { // z = cc + aa + c + a; Status |= z.add(c, RM); Status |= z.add(a, RM); } else { // z = cc + aa + a + c; Status |= z.add(a, RM); Status |= z.add(c, RM); } if (!z.isFinite()) { Floats[0] = std::move(z); Floats[1].makeZero(/* Neg = */ false); return (opStatus)Status; } Floats[0] = z; APFloat zz = aa; Status |= zz.add(cc, RM); if (AComparedToC == APFloat::cmpGreaterThan) { // Floats[1] = a - z + c + zz; Floats[1] = a; Status |= Floats[1].subtract(z, RM); Status |= Floats[1].add(c, RM); Status |= Floats[1].add(zz, RM); } else { // Floats[1] = c - z + a + zz; Floats[1] = c; Status |= Floats[1].subtract(z, RM); Status |= Floats[1].add(a, RM); Status |= Floats[1].add(zz, RM); } } else { // q = a - z; APFloat q = a; Status |= q.subtract(z, RM); // zz = q + c + (a - (q + z)) + aa + cc; // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies. auto zz = q; Status |= zz.add(c, RM); Status |= q.add(z, RM); Status |= q.subtract(a, RM); q.changeSign(); Status |= zz.add(q, RM); Status |= zz.add(aa, RM); Status |= zz.add(cc, RM); if (zz.isZero() && !zz.isNegative()) { Floats[0] = std::move(z); Floats[1].makeZero(/* Neg = */ false); return opOK; } Floats[0] = z; Status |= Floats[0].add(zz, RM); if (!Floats[0].isFinite()) { Floats[1].makeZero(/* Neg = */ false); return (opStatus)Status; } Floats[1] = std::move(z); Status |= Floats[1].subtract(Floats[0], RM); Status |= Floats[1].add(zz, RM); } return (opStatus)Status; } APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS, const DoubleAPFloat &RHS, DoubleAPFloat &Out, roundingMode RM) { if (LHS.getCategory() == fcNaN) { Out = LHS; return opOK; } if (RHS.getCategory() == fcNaN) { Out = RHS; return opOK; } if (LHS.getCategory() == fcZero) { Out = RHS; return opOK; } if (RHS.getCategory() == fcZero) { Out = LHS; return opOK; } if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity && LHS.isNegative() != RHS.isNegative()) { Out.makeNaN(false, Out.isNegative(), nullptr); return opInvalidOp; } if (LHS.getCategory() == fcInfinity) { Out = LHS; return opOK; } if (RHS.getCategory() == fcInfinity) { Out = RHS; return opOK; } assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal); APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]), CC(RHS.Floats[1]); assert(&A.getSemantics() == &semIEEEdouble); assert(&AA.getSemantics() == &semIEEEdouble); assert(&C.getSemantics() == &semIEEEdouble); assert(&CC.getSemantics() == &semIEEEdouble); assert(&Out.Floats[0].getSemantics() == &semIEEEdouble); assert(&Out.Floats[1].getSemantics() == &semIEEEdouble); return Out.addImpl(A, AA, C, CC, RM); } APFloat::opStatus DoubleAPFloat::add(const DoubleAPFloat &RHS, roundingMode RM) { return addWithSpecial(*this, RHS, *this, RM); } APFloat::opStatus DoubleAPFloat::subtract(const DoubleAPFloat &RHS, roundingMode RM) { changeSign(); auto Ret = add(RHS, RM); changeSign(); return Ret; } APFloat::opStatus DoubleAPFloat::multiply(const DoubleAPFloat &RHS, APFloat::roundingMode RM) { const auto &LHS = *this; auto &Out = *this; /* Interesting observation: For special categories, finding the lowest common ancestor of the following layered graph gives the correct return category: NaN / \ Zero Inf \ / Normal e.g. NaN * NaN = NaN Zero * Inf = NaN Normal * Zero = Zero Normal * Inf = Inf */ if (LHS.getCategory() == fcNaN) { Out = LHS; return opOK; } if (RHS.getCategory() == fcNaN) { Out = RHS; return opOK; } if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) || (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) { Out.makeNaN(false, false, nullptr); return opOK; } if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) { Out = LHS; return opOK; } if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) { Out = RHS; return opOK; } assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal && "Special cases not handled exhaustively"); int Status = opOK; APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1]; // t = a * c APFloat T = A; Status |= T.multiply(C, RM); if (!T.isFiniteNonZero()) { Floats[0] = T; Floats[1].makeZero(/* Neg = */ false); return (opStatus)Status; } // tau = fmsub(a, c, t), that is -fmadd(-a, c, t). APFloat Tau = A; T.changeSign(); Status |= Tau.fusedMultiplyAdd(C, T, RM); T.changeSign(); { // v = a * d APFloat V = A; Status |= V.multiply(D, RM); // w = b * c APFloat W = B; Status |= W.multiply(C, RM); Status |= V.add(W, RM); // tau += v + w Status |= Tau.add(V, RM); } // u = t + tau APFloat U = T; Status |= U.add(Tau, RM); Floats[0] = U; if (!U.isFinite()) { Floats[1].makeZero(/* Neg = */ false); } else { // Floats[1] = (t - u) + tau Status |= T.subtract(U, RM); Status |= T.add(Tau, RM); Floats[1] = T; } return (opStatus)Status; } APFloat::opStatus DoubleAPFloat::divide(const DoubleAPFloat &RHS, APFloat::roundingMode RM) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); auto Ret = Tmp.divide(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM); *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); return Ret; } APFloat::opStatus DoubleAPFloat::remainder(const DoubleAPFloat &RHS) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); auto Ret = Tmp.remainder(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt())); *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); return Ret; } APFloat::opStatus DoubleAPFloat::mod(const DoubleAPFloat &RHS) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); auto Ret = Tmp.mod(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt())); *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); return Ret; } APFloat::opStatus DoubleAPFloat::fusedMultiplyAdd(const DoubleAPFloat &Multiplicand, const DoubleAPFloat &Addend, APFloat::roundingMode RM) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); auto Ret = Tmp.fusedMultiplyAdd( APFloat(semPPCDoubleDoubleLegacy, Multiplicand.bitcastToAPInt()), APFloat(semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()), RM); *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); return Ret; } APFloat::opStatus DoubleAPFloat::roundToIntegral(APFloat::roundingMode RM) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); auto Ret = Tmp.roundToIntegral(RM); *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); return Ret; } void DoubleAPFloat::changeSign() { Floats[0].changeSign(); Floats[1].changeSign(); } APFloat::cmpResult DoubleAPFloat::compareAbsoluteValue(const DoubleAPFloat &RHS) const { auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]); if (Result != cmpEqual) return Result; Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]); if (Result == cmpLessThan || Result == cmpGreaterThan) { auto Against = Floats[0].isNegative() ^ Floats[1].isNegative(); auto RHSAgainst = RHS.Floats[0].isNegative() ^ RHS.Floats[1].isNegative(); if (Against && !RHSAgainst) return cmpLessThan; if (!Against && RHSAgainst) return cmpGreaterThan; if (!Against && !RHSAgainst) return Result; if (Against && RHSAgainst) return (cmpResult)(cmpLessThan + cmpGreaterThan - Result); } return Result; } APFloat::fltCategory DoubleAPFloat::getCategory() const { return Floats[0].getCategory(); } bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); } void DoubleAPFloat::makeInf(bool Neg) { Floats[0].makeInf(Neg); Floats[1].makeZero(/* Neg = */ false); } void DoubleAPFloat::makeZero(bool Neg) { Floats[0].makeZero(Neg); Floats[1].makeZero(/* Neg = */ false); } void DoubleAPFloat::makeLargest(bool Neg) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x7fefffffffffffffull)); Floats[1] = APFloat(semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull)); if (Neg) changeSign(); } void DoubleAPFloat::makeSmallest(bool Neg) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); Floats[0].makeSmallest(Neg); Floats[1].makeZero(/* Neg = */ false); } void DoubleAPFloat::makeSmallestNormalized(bool Neg) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x0360000000000000ull)); if (Neg) Floats[0].changeSign(); Floats[1].makeZero(/* Neg = */ false); } void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) { Floats[0].makeNaN(SNaN, Neg, fill); Floats[1].makeZero(/* Neg = */ false); } APFloat::cmpResult DoubleAPFloat::compare(const DoubleAPFloat &RHS) const { auto Result = Floats[0].compare(RHS.Floats[0]); // |Float[0]| > |Float[1]| if (Result == APFloat::cmpEqual) return Floats[1].compare(RHS.Floats[1]); return Result; } bool DoubleAPFloat::bitwiseIsEqual(const DoubleAPFloat &RHS) const { return Floats[0].bitwiseIsEqual(RHS.Floats[0]) && Floats[1].bitwiseIsEqual(RHS.Floats[1]); } hash_code hash_value(const DoubleAPFloat &Arg) { if (Arg.Floats) return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1])); return hash_combine(Arg.Semantics); } APInt DoubleAPFloat::bitcastToAPInt() const { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); uint64_t Data[] = { Floats[0].bitcastToAPInt().getRawData()[0], Floats[1].bitcastToAPInt().getRawData()[0], }; return APInt(128, 2, Data); } Expected DoubleAPFloat::convertFromString(StringRef S, roundingMode RM) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat Tmp(semPPCDoubleDoubleLegacy); auto Ret = Tmp.convertFromString(S, RM); *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); return Ret; } APFloat::opStatus DoubleAPFloat::next(bool nextDown) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); auto Ret = Tmp.next(nextDown); *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); return Ret; } APFloat::opStatus DoubleAPFloat::convertToInteger(MutableArrayRef Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt()) .convertToInteger(Input, Width, IsSigned, RM, IsExact); } APFloat::opStatus DoubleAPFloat::convertFromAPInt(const APInt &Input, bool IsSigned, roundingMode RM) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat Tmp(semPPCDoubleDoubleLegacy); auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM); *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); return Ret; } APFloat::opStatus DoubleAPFloat::convertFromSignExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat Tmp(semPPCDoubleDoubleLegacy); auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM); *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); return Ret; } APFloat::opStatus DoubleAPFloat::convertFromZeroExtendedInteger(const integerPart *Input, unsigned int InputSize, bool IsSigned, roundingMode RM) { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat Tmp(semPPCDoubleDoubleLegacy); auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM); *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt()); return Ret; } unsigned int DoubleAPFloat::convertToHexString(char *DST, unsigned int HexDigits, bool UpperCase, roundingMode RM) const { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt()) .convertToHexString(DST, HexDigits, UpperCase, RM); } bool DoubleAPFloat::isDenormal() const { return getCategory() == fcNormal && (Floats[0].isDenormal() || Floats[1].isDenormal() || // (double)(Hi + Lo) == Hi defines a normal number. Floats[0].compare(Floats[0] + Floats[1]) != cmpEqual); } bool DoubleAPFloat::isSmallest() const { if (getCategory() != fcNormal) return false; DoubleAPFloat Tmp(*this); Tmp.makeSmallest(this->isNegative()); return Tmp.compare(*this) == cmpEqual; } bool DoubleAPFloat::isLargest() const { if (getCategory() != fcNormal) return false; DoubleAPFloat Tmp(*this); Tmp.makeLargest(this->isNegative()); return Tmp.compare(*this) == cmpEqual; } bool DoubleAPFloat::isInteger() const { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); return Floats[0].isInteger() && Floats[1].isInteger(); } void DoubleAPFloat::toString(SmallVectorImpl &Str, unsigned FormatPrecision, unsigned FormatMaxPadding, bool TruncateZero) const { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt()) .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero); } bool DoubleAPFloat::getExactInverse(APFloat *inv) const { assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt()); if (!inv) return Tmp.getExactInverse(nullptr); APFloat Inv(semPPCDoubleDoubleLegacy); auto Ret = Tmp.getExactInverse(&Inv); *inv = APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt()); return Ret; } DoubleAPFloat scalbn(DoubleAPFloat Arg, int Exp, APFloat::roundingMode RM) { assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); return DoubleAPFloat(semPPCDoubleDouble, scalbn(Arg.Floats[0], Exp, RM), scalbn(Arg.Floats[1], Exp, RM)); } DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp, APFloat::roundingMode RM) { assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics"); APFloat First = frexp(Arg.Floats[0], Exp, RM); APFloat Second = Arg.Floats[1]; if (Arg.getCategory() == APFloat::fcNormal) Second = scalbn(Second, -Exp, RM); return DoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second)); } } // End detail namespace APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) { if (usesLayout(Semantics)) { new (&IEEE) IEEEFloat(std::move(F)); return; } if (usesLayout(Semantics)) { const fltSemantics& S = F.getSemantics(); new (&Double) DoubleAPFloat(Semantics, APFloat(std::move(F), S), APFloat(semIEEEdouble)); return; } llvm_unreachable("Unexpected semantics"); } Expected APFloat::convertFromString(StringRef Str, roundingMode RM) { APFLOAT_DISPATCH_ON_SEMANTICS(convertFromString(Str, RM)); } hash_code hash_value(const APFloat &Arg) { if (APFloat::usesLayout(Arg.getSemantics())) return hash_value(Arg.U.IEEE); if (APFloat::usesLayout(Arg.getSemantics())) return hash_value(Arg.U.Double); llvm_unreachable("Unexpected semantics"); } APFloat::APFloat(const fltSemantics &Semantics, StringRef S) : APFloat(Semantics) { auto StatusOrErr = convertFromString(S, rmNearestTiesToEven); - assert(StatusOrErr && "Invalid floating point representation"); + if (!StatusOrErr) { + assert(false && "Invalid floating point representation"); + } } APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics, roundingMode RM, bool *losesInfo) { if (&getSemantics() == &ToSemantics) { *losesInfo = false; return opOK; } if (usesLayout(getSemantics()) && usesLayout(ToSemantics)) return U.IEEE.convert(ToSemantics, RM, losesInfo); if (usesLayout(getSemantics()) && usesLayout(ToSemantics)) { assert(&ToSemantics == &semPPCDoubleDouble); auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo); *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt()); return Ret; } if (usesLayout(getSemantics()) && usesLayout(ToSemantics)) { auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo); *this = APFloat(std::move(getIEEE()), ToSemantics); return Ret; } llvm_unreachable("Unexpected semantics"); } APFloat APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE) { if (isIEEE) { switch (BitWidth) { case 16: return APFloat(semIEEEhalf, APInt::getAllOnesValue(BitWidth)); case 32: return APFloat(semIEEEsingle, APInt::getAllOnesValue(BitWidth)); case 64: return APFloat(semIEEEdouble, APInt::getAllOnesValue(BitWidth)); case 80: return APFloat(semX87DoubleExtended, APInt::getAllOnesValue(BitWidth)); case 128: return APFloat(semIEEEquad, APInt::getAllOnesValue(BitWidth)); default: llvm_unreachable("Unknown floating bit width"); } } else { assert(BitWidth == 128); return APFloat(semPPCDoubleDouble, APInt::getAllOnesValue(BitWidth)); } } void APFloat::print(raw_ostream &OS) const { SmallVector Buffer; toString(Buffer); OS << Buffer << "\n"; } #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) LLVM_DUMP_METHOD void APFloat::dump() const { print(dbgs()); } #endif void APFloat::Profile(FoldingSetNodeID &NID) const { NID.Add(bitcastToAPInt()); } /* Same as convertToInteger(integerPart*, ...), except the result is returned in an APSInt, whose initial bit-width and signed-ness are used to determine the precision of the conversion. */ APFloat::opStatus APFloat::convertToInteger(APSInt &result, roundingMode rounding_mode, bool *isExact) const { unsigned bitWidth = result.getBitWidth(); SmallVector parts(result.getNumWords()); opStatus status = convertToInteger(parts, bitWidth, result.isSigned(), rounding_mode, isExact); // Keeps the original signed-ness. result = APInt(bitWidth, parts); return status; } } // End llvm namespace #undef APFLOAT_DISPATCH_ON_SEMANTICS diff --git a/llvm/lib/Support/StringRef.cpp b/llvm/lib/Support/StringRef.cpp index 4142d130d519..b5db172cc1a3 100644 --- a/llvm/lib/Support/StringRef.cpp +++ b/llvm/lib/Support/StringRef.cpp @@ -1,610 +1,610 @@ //===-- StringRef.cpp - Lightweight String References ---------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/ADT/StringRef.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APInt.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/edit_distance.h" #include "llvm/Support/Error.h" #include using namespace llvm; // MSVC emits references to this into the translation units which reference it. #ifndef _MSC_VER const size_t StringRef::npos; #endif // strncasecmp() is not available on non-POSIX systems, so define an // alternative function here. static int ascii_strncasecmp(const char *LHS, const char *RHS, size_t Length) { for (size_t I = 0; I < Length; ++I) { unsigned char LHC = toLower(LHS[I]); unsigned char RHC = toLower(RHS[I]); if (LHC != RHC) return LHC < RHC ? -1 : 1; } return 0; } /// compare_lower - Compare strings, ignoring case. int StringRef::compare_lower(StringRef RHS) const { if (int Res = ascii_strncasecmp(Data, RHS.Data, std::min(Length, RHS.Length))) return Res; if (Length == RHS.Length) return 0; return Length < RHS.Length ? -1 : 1; } /// Check if this string starts with the given \p Prefix, ignoring case. bool StringRef::startswith_lower(StringRef Prefix) const { return Length >= Prefix.Length && ascii_strncasecmp(Data, Prefix.Data, Prefix.Length) == 0; } /// Check if this string ends with the given \p Suffix, ignoring case. bool StringRef::endswith_lower(StringRef Suffix) const { return Length >= Suffix.Length && ascii_strncasecmp(end() - Suffix.Length, Suffix.Data, Suffix.Length) == 0; } size_t StringRef::find_lower(char C, size_t From) const { char L = toLower(C); return find_if([L](char D) { return toLower(D) == L; }, From); } /// compare_numeric - Compare strings, handle embedded numbers. int StringRef::compare_numeric(StringRef RHS) const { for (size_t I = 0, E = std::min(Length, RHS.Length); I != E; ++I) { // Check for sequences of digits. if (isDigit(Data[I]) && isDigit(RHS.Data[I])) { // The longer sequence of numbers is considered larger. // This doesn't really handle prefixed zeros well. size_t J; for (J = I + 1; J != E + 1; ++J) { bool ld = J < Length && isDigit(Data[J]); bool rd = J < RHS.Length && isDigit(RHS.Data[J]); if (ld != rd) return rd ? -1 : 1; if (!rd) break; } // The two number sequences have the same length (J-I), just memcmp them. if (int Res = compareMemory(Data + I, RHS.Data + I, J - I)) return Res < 0 ? -1 : 1; // Identical number sequences, continue search after the numbers. I = J - 1; continue; } if (Data[I] != RHS.Data[I]) return (unsigned char)Data[I] < (unsigned char)RHS.Data[I] ? -1 : 1; } if (Length == RHS.Length) return 0; return Length < RHS.Length ? -1 : 1; } // Compute the edit distance between the two given strings. unsigned StringRef::edit_distance(llvm::StringRef Other, bool AllowReplacements, unsigned MaxEditDistance) const { return llvm::ComputeEditDistance( makeArrayRef(data(), size()), makeArrayRef(Other.data(), Other.size()), AllowReplacements, MaxEditDistance); } //===----------------------------------------------------------------------===// // String Operations //===----------------------------------------------------------------------===// std::string StringRef::lower() const { std::string Result(size(), char()); for (size_type i = 0, e = size(); i != e; ++i) { Result[i] = toLower(Data[i]); } return Result; } std::string StringRef::upper() const { std::string Result(size(), char()); for (size_type i = 0, e = size(); i != e; ++i) { Result[i] = toUpper(Data[i]); } return Result; } //===----------------------------------------------------------------------===// // String Searching //===----------------------------------------------------------------------===// /// find - Search for the first string \arg Str in the string. /// /// \return - The index of the first occurrence of \arg Str, or npos if not /// found. size_t StringRef::find(StringRef Str, size_t From) const { if (From > Length) return npos; const char *Start = Data + From; size_t Size = Length - From; const char *Needle = Str.data(); size_t N = Str.size(); if (N == 0) return From; if (Size < N) return npos; if (N == 1) { const char *Ptr = (const char *)::memchr(Start, Needle[0], Size); return Ptr == nullptr ? npos : Ptr - Data; } const char *Stop = Start + (Size - N + 1); // For short haystacks or unsupported needles fall back to the naive algorithm if (Size < 16 || N > 255) { do { if (std::memcmp(Start, Needle, N) == 0) return Start - Data; ++Start; } while (Start < Stop); return npos; } // Build the bad char heuristic table, with uint8_t to reduce cache thrashing. uint8_t BadCharSkip[256]; std::memset(BadCharSkip, N, 256); for (unsigned i = 0; i != N-1; ++i) BadCharSkip[(uint8_t)Str[i]] = N-1-i; do { uint8_t Last = Start[N - 1]; if (LLVM_UNLIKELY(Last == (uint8_t)Needle[N - 1])) if (std::memcmp(Start, Needle, N - 1) == 0) return Start - Data; // Otherwise skip the appropriate number of bytes. Start += BadCharSkip[Last]; } while (Start < Stop); return npos; } size_t StringRef::find_lower(StringRef Str, size_t From) const { StringRef This = substr(From); while (This.size() >= Str.size()) { if (This.startswith_lower(Str)) return From; This = This.drop_front(); ++From; } return npos; } size_t StringRef::rfind_lower(char C, size_t From) const { From = std::min(From, Length); size_t i = From; while (i != 0) { --i; if (toLower(Data[i]) == toLower(C)) return i; } return npos; } /// rfind - Search for the last string \arg Str in the string. /// /// \return - The index of the last occurrence of \arg Str, or npos if not /// found. size_t StringRef::rfind(StringRef Str) const { size_t N = Str.size(); if (N > Length) return npos; for (size_t i = Length - N + 1, e = 0; i != e;) { --i; if (substr(i, N).equals(Str)) return i; } return npos; } size_t StringRef::rfind_lower(StringRef Str) const { size_t N = Str.size(); if (N > Length) return npos; for (size_t i = Length - N + 1, e = 0; i != e;) { --i; if (substr(i, N).equals_lower(Str)) return i; } return npos; } /// find_first_of - Find the first character in the string that is in \arg /// Chars, or npos if not found. /// /// Note: O(size() + Chars.size()) StringRef::size_type StringRef::find_first_of(StringRef Chars, size_t From) const { std::bitset<1 << CHAR_BIT> CharBits; for (size_type i = 0; i != Chars.size(); ++i) CharBits.set((unsigned char)Chars[i]); for (size_type i = std::min(From, Length), e = Length; i != e; ++i) if (CharBits.test((unsigned char)Data[i])) return i; return npos; } /// find_first_not_of - Find the first character in the string that is not /// \arg C or npos if not found. StringRef::size_type StringRef::find_first_not_of(char C, size_t From) const { for (size_type i = std::min(From, Length), e = Length; i != e; ++i) if (Data[i] != C) return i; return npos; } /// find_first_not_of - Find the first character in the string that is not /// in the string \arg Chars, or npos if not found. /// /// Note: O(size() + Chars.size()) StringRef::size_type StringRef::find_first_not_of(StringRef Chars, size_t From) const { std::bitset<1 << CHAR_BIT> CharBits; for (size_type i = 0; i != Chars.size(); ++i) CharBits.set((unsigned char)Chars[i]); for (size_type i = std::min(From, Length), e = Length; i != e; ++i) if (!CharBits.test((unsigned char)Data[i])) return i; return npos; } /// find_last_of - Find the last character in the string that is in \arg C, /// or npos if not found. /// /// Note: O(size() + Chars.size()) StringRef::size_type StringRef::find_last_of(StringRef Chars, size_t From) const { std::bitset<1 << CHAR_BIT> CharBits; for (size_type i = 0; i != Chars.size(); ++i) CharBits.set((unsigned char)Chars[i]); for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i) if (CharBits.test((unsigned char)Data[i])) return i; return npos; } /// find_last_not_of - Find the last character in the string that is not /// \arg C, or npos if not found. StringRef::size_type StringRef::find_last_not_of(char C, size_t From) const { for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i) if (Data[i] != C) return i; return npos; } /// find_last_not_of - Find the last character in the string that is not in /// \arg Chars, or npos if not found. /// /// Note: O(size() + Chars.size()) StringRef::size_type StringRef::find_last_not_of(StringRef Chars, size_t From) const { std::bitset<1 << CHAR_BIT> CharBits; for (size_type i = 0, e = Chars.size(); i != e; ++i) CharBits.set((unsigned char)Chars[i]); for (size_type i = std::min(From, Length) - 1, e = -1; i != e; --i) if (!CharBits.test((unsigned char)Data[i])) return i; return npos; } void StringRef::split(SmallVectorImpl &A, StringRef Separator, int MaxSplit, bool KeepEmpty) const { StringRef S = *this; // Count down from MaxSplit. When MaxSplit is -1, this will just split // "forever". This doesn't support splitting more than 2^31 times // intentionally; if we ever want that we can make MaxSplit a 64-bit integer // but that seems unlikely to be useful. while (MaxSplit-- != 0) { size_t Idx = S.find(Separator); if (Idx == npos) break; // Push this split. if (KeepEmpty || Idx > 0) A.push_back(S.slice(0, Idx)); // Jump forward. S = S.slice(Idx + Separator.size(), npos); } // Push the tail. if (KeepEmpty || !S.empty()) A.push_back(S); } void StringRef::split(SmallVectorImpl &A, char Separator, int MaxSplit, bool KeepEmpty) const { StringRef S = *this; // Count down from MaxSplit. When MaxSplit is -1, this will just split // "forever". This doesn't support splitting more than 2^31 times // intentionally; if we ever want that we can make MaxSplit a 64-bit integer // but that seems unlikely to be useful. while (MaxSplit-- != 0) { size_t Idx = S.find(Separator); if (Idx == npos) break; // Push this split. if (KeepEmpty || Idx > 0) A.push_back(S.slice(0, Idx)); // Jump forward. S = S.slice(Idx + 1, npos); } // Push the tail. if (KeepEmpty || !S.empty()) A.push_back(S); } //===----------------------------------------------------------------------===// // Helpful Algorithms //===----------------------------------------------------------------------===// /// count - Return the number of non-overlapped occurrences of \arg Str in /// the string. size_t StringRef::count(StringRef Str) const { size_t Count = 0; size_t N = Str.size(); if (!N || N > Length) return 0; for (size_t i = 0, e = Length - N + 1; i < e;) { if (substr(i, N).equals(Str)) { ++Count; i += N; } else ++i; } return Count; } static unsigned GetAutoSenseRadix(StringRef &Str) { if (Str.empty()) return 10; if (Str.startswith("0x") || Str.startswith("0X")) { Str = Str.substr(2); return 16; } if (Str.startswith("0b") || Str.startswith("0B")) { Str = Str.substr(2); return 2; } if (Str.startswith("0o")) { Str = Str.substr(2); return 8; } if (Str[0] == '0' && Str.size() > 1 && isDigit(Str[1])) { Str = Str.substr(1); return 8; } return 10; } bool llvm::consumeUnsignedInteger(StringRef &Str, unsigned Radix, unsigned long long &Result) { // Autosense radix if not specified. if (Radix == 0) Radix = GetAutoSenseRadix(Str); // Empty strings (after the radix autosense) are invalid. if (Str.empty()) return true; // Parse all the bytes of the string given this radix. Watch for overflow. StringRef Str2 = Str; Result = 0; while (!Str2.empty()) { unsigned CharVal; if (Str2[0] >= '0' && Str2[0] <= '9') CharVal = Str2[0] - '0'; else if (Str2[0] >= 'a' && Str2[0] <= 'z') CharVal = Str2[0] - 'a' + 10; else if (Str2[0] >= 'A' && Str2[0] <= 'Z') CharVal = Str2[0] - 'A' + 10; else break; // If the parsed value is larger than the integer radix, we cannot // consume any more characters. if (CharVal >= Radix) break; // Add in this character. unsigned long long PrevResult = Result; Result = Result * Radix + CharVal; // Check for overflow by shifting back and seeing if bits were lost. if (Result / Radix < PrevResult) return true; Str2 = Str2.substr(1); } // We consider the operation a failure if no characters were consumed // successfully. if (Str.size() == Str2.size()) return true; Str = Str2; return false; } bool llvm::consumeSignedInteger(StringRef &Str, unsigned Radix, long long &Result) { unsigned long long ULLVal; // Handle positive strings first. if (Str.empty() || Str.front() != '-') { if (consumeUnsignedInteger(Str, Radix, ULLVal) || // Check for value so large it overflows a signed value. (long long)ULLVal < 0) return true; Result = ULLVal; return false; } // Get the positive part of the value. StringRef Str2 = Str.drop_front(1); if (consumeUnsignedInteger(Str2, Radix, ULLVal) || // Reject values so large they'd overflow as negative signed, but allow // "-0". This negates the unsigned so that the negative isn't undefined // on signed overflow. (long long)-ULLVal > 0) return true; Str = Str2; Result = -ULLVal; return false; } /// GetAsUnsignedInteger - Workhorse method that converts a integer character /// sequence of radix up to 36 to an unsigned long long value. bool llvm::getAsUnsignedInteger(StringRef Str, unsigned Radix, unsigned long long &Result) { if (consumeUnsignedInteger(Str, Radix, Result)) return true; // For getAsUnsignedInteger, we require the whole string to be consumed or // else we consider it a failure. return !Str.empty(); } bool llvm::getAsSignedInteger(StringRef Str, unsigned Radix, long long &Result) { if (consumeSignedInteger(Str, Radix, Result)) return true; // For getAsSignedInteger, we require the whole string to be consumed or else // we consider it a failure. return !Str.empty(); } bool StringRef::getAsInteger(unsigned Radix, APInt &Result) const { StringRef Str = *this; // Autosense radix if not specified. if (Radix == 0) Radix = GetAutoSenseRadix(Str); assert(Radix > 1 && Radix <= 36); // Empty strings (after the radix autosense) are invalid. if (Str.empty()) return true; // Skip leading zeroes. This can be a significant improvement if // it means we don't need > 64 bits. while (!Str.empty() && Str.front() == '0') Str = Str.substr(1); // If it was nothing but zeroes.... if (Str.empty()) { Result = APInt(64, 0); return false; } // (Over-)estimate the required number of bits. unsigned Log2Radix = 0; while ((1U << Log2Radix) < Radix) Log2Radix++; bool IsPowerOf2Radix = ((1U << Log2Radix) == Radix); unsigned BitWidth = Log2Radix * Str.size(); if (BitWidth < Result.getBitWidth()) BitWidth = Result.getBitWidth(); // don't shrink the result else if (BitWidth > Result.getBitWidth()) Result = Result.zext(BitWidth); APInt RadixAP, CharAP; // unused unless !IsPowerOf2Radix if (!IsPowerOf2Radix) { // These must have the same bit-width as Result. RadixAP = APInt(BitWidth, Radix); CharAP = APInt(BitWidth, 0); } // Parse all the bytes of the string given this radix. Result = 0; while (!Str.empty()) { unsigned CharVal; if (Str[0] >= '0' && Str[0] <= '9') CharVal = Str[0]-'0'; else if (Str[0] >= 'a' && Str[0] <= 'z') CharVal = Str[0]-'a'+10; else if (Str[0] >= 'A' && Str[0] <= 'Z') CharVal = Str[0]-'A'+10; else return true; // If the parsed value is larger than the integer radix, the string is // invalid. if (CharVal >= Radix) return true; // Add in this character. if (IsPowerOf2Radix) { Result <<= Log2Radix; Result |= CharVal; } else { Result *= RadixAP; CharAP = CharVal; Result += CharAP; } Str = Str.substr(1); } return false; } bool StringRef::getAsDouble(double &Result, bool AllowInexact) const { APFloat F(0.0); auto ErrOrStatus = F.convertFromString(*this, APFloat::rmNearestTiesToEven); if (!ErrOrStatus) { - assert("Invalid floating point representation"); + assert(false && "Invalid floating point representation"); return true; } APFloat::opStatus Status = *ErrOrStatus; if (Status != APFloat::opOK) { if (!AllowInexact || !(Status & APFloat::opInexact)) return true; } Result = F.convertToDouble(); return false; } // Implementation of StringRef hashing. hash_code llvm::hash_value(StringRef S) { return hash_combine_range(S.begin(), S.end()); } diff --git a/llvm/unittests/ADT/APFloatTest.cpp b/llvm/unittests/ADT/APFloatTest.cpp index 927e1fe13671..db529a094c37 100644 --- a/llvm/unittests/ADT/APFloatTest.cpp +++ b/llvm/unittests/ADT/APFloatTest.cpp @@ -1,4132 +1,4118 @@ //===- llvm/unittest/ADT/APFloat.cpp - APFloat unit tests ---------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "llvm/ADT/APFloat.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Error.h" #include "llvm/Support/FormatVariadic.h" #include "gtest/gtest.h" #include #include #include #include using namespace llvm; static std::string convertToErrorFromString(StringRef Str) { llvm::APFloat F(0.0); auto ErrOrStatus = F.convertFromString(Str, llvm::APFloat::rmNearestTiesToEven); EXPECT_TRUE(!ErrOrStatus); return toString(ErrOrStatus.takeError()); } static double convertToDoubleFromString(StringRef Str) { llvm::APFloat F(0.0); EXPECT_FALSE(!F.convertFromString(Str, llvm::APFloat::rmNearestTiesToEven)); return F.convertToDouble(); } static std::string convertToString(double d, unsigned Prec, unsigned Pad, bool Tr = true) { llvm::SmallVector Buffer; llvm::APFloat F(d); F.toString(Buffer, Prec, Pad, Tr); return std::string(Buffer.data(), Buffer.size()); } namespace { TEST(APFloatTest, isSignaling) { // We test qNaN, -qNaN, +sNaN, -sNaN with and without payloads. *NOTE* The // positive/negative distinction is included only since the getQNaN/getSNaN // API provides the option. APInt payload = APInt::getOneBitSet(4, 2); EXPECT_FALSE(APFloat::getQNaN(APFloat::IEEEsingle(), false).isSignaling()); EXPECT_FALSE(APFloat::getQNaN(APFloat::IEEEsingle(), true).isSignaling()); EXPECT_FALSE(APFloat::getQNaN(APFloat::IEEEsingle(), false, &payload).isSignaling()); EXPECT_FALSE(APFloat::getQNaN(APFloat::IEEEsingle(), true, &payload).isSignaling()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle(), false).isSignaling()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle(), true).isSignaling()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle(), false, &payload).isSignaling()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle(), true, &payload).isSignaling()); } TEST(APFloatTest, next) { APFloat test(APFloat::IEEEquad(), APFloat::uninitialized); APFloat expected(APFloat::IEEEquad(), APFloat::uninitialized); // 1. Test Special Cases Values. // // Test all special values for nextUp and nextDown perscribed by IEEE-754R // 2008. These are: // 1. +inf // 2. -inf // 3. getLargest() // 4. -getLargest() // 5. getSmallest() // 6. -getSmallest() // 7. qNaN // 8. sNaN // 9. +0 // 10. -0 // nextUp(+inf) = +inf. test = APFloat::getInf(APFloat::IEEEquad(), false); expected = APFloat::getInf(APFloat::IEEEquad(), false); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isInfinity()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+inf) = -nextUp(-inf) = -(-getLargest()) = getLargest() test = APFloat::getInf(APFloat::IEEEquad(), false); expected = APFloat::getLargest(APFloat::IEEEquad(), false); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-inf) = -getLargest() test = APFloat::getInf(APFloat::IEEEquad(), true); expected = APFloat::getLargest(APFloat::IEEEquad(), true); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-inf) = -nextUp(+inf) = -(+inf) = -inf. test = APFloat::getInf(APFloat::IEEEquad(), true); expected = APFloat::getInf(APFloat::IEEEquad(), true); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isInfinity() && test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(getLargest()) = +inf test = APFloat::getLargest(APFloat::IEEEquad(), false); expected = APFloat::getInf(APFloat::IEEEquad(), false); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isInfinity() && !test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(getLargest()) = -nextUp(-getLargest()) // = -(-getLargest() + inc) // = getLargest() - inc. test = APFloat::getLargest(APFloat::IEEEquad(), false); expected = APFloat(APFloat::IEEEquad(), "0x1.fffffffffffffffffffffffffffep+16383"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(!test.isInfinity() && !test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-getLargest()) = -getLargest() + inc. test = APFloat::getLargest(APFloat::IEEEquad(), true); expected = APFloat(APFloat::IEEEquad(), "-0x1.fffffffffffffffffffffffffffep+16383"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-getLargest()) = -nextUp(getLargest()) = -(inf) = -inf. test = APFloat::getLargest(APFloat::IEEEquad(), true); expected = APFloat::getInf(APFloat::IEEEquad(), true); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isInfinity() && test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(getSmallest()) = getSmallest() + inc. test = APFloat(APFloat::IEEEquad(), "0x0.0000000000000000000000000001p-16382"); expected = APFloat(APFloat::IEEEquad(), "0x0.0000000000000000000000000002p-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(getSmallest()) = -nextUp(-getSmallest()) = -(-0) = +0. test = APFloat(APFloat::IEEEquad(), "0x0.0000000000000000000000000001p-16382"); expected = APFloat::getZero(APFloat::IEEEquad(), false); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isPosZero()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-getSmallest()) = -0. test = APFloat(APFloat::IEEEquad(), "-0x0.0000000000000000000000000001p-16382"); expected = APFloat::getZero(APFloat::IEEEquad(), true); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isNegZero()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-getSmallest()) = -nextUp(getSmallest()) = -getSmallest() - inc. test = APFloat(APFloat::IEEEquad(), "-0x0.0000000000000000000000000001p-16382"); expected = APFloat(APFloat::IEEEquad(), "-0x0.0000000000000000000000000002p-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(qNaN) = qNaN test = APFloat::getQNaN(APFloat::IEEEquad(), false); expected = APFloat::getQNaN(APFloat::IEEEquad(), false); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(qNaN) = qNaN test = APFloat::getQNaN(APFloat::IEEEquad(), false); expected = APFloat::getQNaN(APFloat::IEEEquad(), false); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(sNaN) = qNaN test = APFloat::getSNaN(APFloat::IEEEquad(), false); expected = APFloat::getQNaN(APFloat::IEEEquad(), false); EXPECT_EQ(test.next(false), APFloat::opInvalidOp); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(sNaN) = qNaN test = APFloat::getSNaN(APFloat::IEEEquad(), false); expected = APFloat::getQNaN(APFloat::IEEEquad(), false); EXPECT_EQ(test.next(true), APFloat::opInvalidOp); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(+0) = +getSmallest() test = APFloat::getZero(APFloat::IEEEquad(), false); expected = APFloat::getSmallest(APFloat::IEEEquad(), false); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+0) = -nextUp(-0) = -getSmallest() test = APFloat::getZero(APFloat::IEEEquad(), false); expected = APFloat::getSmallest(APFloat::IEEEquad(), true); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-0) = +getSmallest() test = APFloat::getZero(APFloat::IEEEquad(), true); expected = APFloat::getSmallest(APFloat::IEEEquad(), false); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-0) = -nextUp(0) = -getSmallest() test = APFloat::getZero(APFloat::IEEEquad(), true); expected = APFloat::getSmallest(APFloat::IEEEquad(), true); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // 2. Binade Boundary Tests. // 2a. Test denormal <-> normal binade boundaries. // * nextUp(+Largest Denormal) -> +Smallest Normal. // * nextDown(-Largest Denormal) -> -Smallest Normal. // * nextUp(-Smallest Normal) -> -Largest Denormal. // * nextDown(+Smallest Normal) -> +Largest Denormal. // nextUp(+Largest Denormal) -> +Smallest Normal. test = APFloat(APFloat::IEEEquad(), "0x0.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad(), "0x1.0000000000000000000000000000p-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-Largest Denormal) -> -Smallest Normal. test = APFloat(APFloat::IEEEquad(), "-0x0.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad(), "-0x1.0000000000000000000000000000p-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-Smallest Normal) -> -LargestDenormal. test = APFloat(APFloat::IEEEquad(), "-0x1.0000000000000000000000000000p-16382"); expected = APFloat(APFloat::IEEEquad(), "-0x0.ffffffffffffffffffffffffffffp-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+Smallest Normal) -> +Largest Denormal. test = APFloat(APFloat::IEEEquad(), "+0x1.0000000000000000000000000000p-16382"); expected = APFloat(APFloat::IEEEquad(), "+0x0.ffffffffffffffffffffffffffffp-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // 2b. Test normal <-> normal binade boundaries. // * nextUp(-Normal Binade Boundary) -> -Normal Binade Boundary + 1. // * nextDown(+Normal Binade Boundary) -> +Normal Binade Boundary - 1. // * nextUp(+Normal Binade Boundary - 1) -> +Normal Binade Boundary. // * nextDown(-Normal Binade Boundary + 1) -> -Normal Binade Boundary. // nextUp(-Normal Binade Boundary) -> -Normal Binade Boundary + 1. test = APFloat(APFloat::IEEEquad(), "-0x1p+1"); expected = APFloat(APFloat::IEEEquad(), "-0x1.ffffffffffffffffffffffffffffp+0"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+Normal Binade Boundary) -> +Normal Binade Boundary - 1. test = APFloat(APFloat::IEEEquad(), "0x1p+1"); expected = APFloat(APFloat::IEEEquad(), "0x1.ffffffffffffffffffffffffffffp+0"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(+Normal Binade Boundary - 1) -> +Normal Binade Boundary. test = APFloat(APFloat::IEEEquad(), "0x1.ffffffffffffffffffffffffffffp+0"); expected = APFloat(APFloat::IEEEquad(), "0x1p+1"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-Normal Binade Boundary + 1) -> -Normal Binade Boundary. test = APFloat(APFloat::IEEEquad(), "-0x1.ffffffffffffffffffffffffffffp+0"); expected = APFloat(APFloat::IEEEquad(), "-0x1p+1"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // 2c. Test using next at binade boundaries with a direction away from the // binade boundary. Away from denormal <-> normal boundaries. // // This is to make sure that even though we are at a binade boundary, since // we are rounding away, we do not trigger the binade boundary code. Thus we // test: // * nextUp(-Largest Denormal) -> -Largest Denormal + inc. // * nextDown(+Largest Denormal) -> +Largest Denormal - inc. // * nextUp(+Smallest Normal) -> +Smallest Normal + inc. // * nextDown(-Smallest Normal) -> -Smallest Normal - inc. // nextUp(-Largest Denormal) -> -Largest Denormal + inc. test = APFloat(APFloat::IEEEquad(), "-0x0.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad(), "-0x0.fffffffffffffffffffffffffffep-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+Largest Denormal) -> +Largest Denormal - inc. test = APFloat(APFloat::IEEEquad(), "0x0.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad(), "0x0.fffffffffffffffffffffffffffep-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(+Smallest Normal) -> +Smallest Normal + inc. test = APFloat(APFloat::IEEEquad(), "0x1.0000000000000000000000000000p-16382"); expected = APFloat(APFloat::IEEEquad(), "0x1.0000000000000000000000000001p-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-Smallest Normal) -> -Smallest Normal - inc. test = APFloat(APFloat::IEEEquad(), "-0x1.0000000000000000000000000000p-16382"); expected = APFloat(APFloat::IEEEquad(), "-0x1.0000000000000000000000000001p-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // 2d. Test values which cause our exponent to go to min exponent. This // is to ensure that guards in the code to check for min exponent // trigger properly. // * nextUp(-0x1p-16381) -> -0x1.ffffffffffffffffffffffffffffp-16382 // * nextDown(-0x1.ffffffffffffffffffffffffffffp-16382) -> // -0x1p-16381 // * nextUp(0x1.ffffffffffffffffffffffffffffp-16382) -> 0x1p-16382 // * nextDown(0x1p-16382) -> 0x1.ffffffffffffffffffffffffffffp-16382 // nextUp(-0x1p-16381) -> -0x1.ffffffffffffffffffffffffffffp-16382 test = APFloat(APFloat::IEEEquad(), "-0x1p-16381"); expected = APFloat(APFloat::IEEEquad(), "-0x1.ffffffffffffffffffffffffffffp-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-0x1.ffffffffffffffffffffffffffffp-16382) -> // -0x1p-16381 test = APFloat(APFloat::IEEEquad(), "-0x1.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad(), "-0x1p-16381"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(0x1.ffffffffffffffffffffffffffffp-16382) -> 0x1p-16381 test = APFloat(APFloat::IEEEquad(), "0x1.ffffffffffffffffffffffffffffp-16382"); expected = APFloat(APFloat::IEEEquad(), "0x1p-16381"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(0x1p-16381) -> 0x1.ffffffffffffffffffffffffffffp-16382 test = APFloat(APFloat::IEEEquad(), "0x1p-16381"); expected = APFloat(APFloat::IEEEquad(), "0x1.ffffffffffffffffffffffffffffp-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // 3. Now we test both denormal/normal computation which will not cause us // to go across binade boundaries. Specifically we test: // * nextUp(+Denormal) -> +Denormal. // * nextDown(+Denormal) -> +Denormal. // * nextUp(-Denormal) -> -Denormal. // * nextDown(-Denormal) -> -Denormal. // * nextUp(+Normal) -> +Normal. // * nextDown(+Normal) -> +Normal. // * nextUp(-Normal) -> -Normal. // * nextDown(-Normal) -> -Normal. // nextUp(+Denormal) -> +Denormal. test = APFloat(APFloat::IEEEquad(), "0x0.ffffffffffffffffffffffff000cp-16382"); expected = APFloat(APFloat::IEEEquad(), "0x0.ffffffffffffffffffffffff000dp-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+Denormal) -> +Denormal. test = APFloat(APFloat::IEEEquad(), "0x0.ffffffffffffffffffffffff000cp-16382"); expected = APFloat(APFloat::IEEEquad(), "0x0.ffffffffffffffffffffffff000bp-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-Denormal) -> -Denormal. test = APFloat(APFloat::IEEEquad(), "-0x0.ffffffffffffffffffffffff000cp-16382"); expected = APFloat(APFloat::IEEEquad(), "-0x0.ffffffffffffffffffffffff000bp-16382"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-Denormal) -> -Denormal test = APFloat(APFloat::IEEEquad(), "-0x0.ffffffffffffffffffffffff000cp-16382"); expected = APFloat(APFloat::IEEEquad(), "-0x0.ffffffffffffffffffffffff000dp-16382"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(+Normal) -> +Normal. test = APFloat(APFloat::IEEEquad(), "0x1.ffffffffffffffffffffffff000cp-16000"); expected = APFloat(APFloat::IEEEquad(), "0x1.ffffffffffffffffffffffff000dp-16000"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(+Normal) -> +Normal. test = APFloat(APFloat::IEEEquad(), "0x1.ffffffffffffffffffffffff000cp-16000"); expected = APFloat(APFloat::IEEEquad(), "0x1.ffffffffffffffffffffffff000bp-16000"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(!test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextUp(-Normal) -> -Normal. test = APFloat(APFloat::IEEEquad(), "-0x1.ffffffffffffffffffffffff000cp-16000"); expected = APFloat(APFloat::IEEEquad(), "-0x1.ffffffffffffffffffffffff000bp-16000"); EXPECT_EQ(test.next(false), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); // nextDown(-Normal) -> -Normal. test = APFloat(APFloat::IEEEquad(), "-0x1.ffffffffffffffffffffffff000cp-16000"); expected = APFloat(APFloat::IEEEquad(), "-0x1.ffffffffffffffffffffffff000dp-16000"); EXPECT_EQ(test.next(true), APFloat::opOK); EXPECT_TRUE(!test.isDenormal()); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); } TEST(APFloatTest, FMA) { APFloat::roundingMode rdmd = APFloat::rmNearestTiesToEven; { APFloat f1(14.5f); APFloat f2(-14.5f); APFloat f3(225.0f); f1.fusedMultiplyAdd(f2, f3, APFloat::rmNearestTiesToEven); EXPECT_EQ(14.75f, f1.convertToFloat()); } { APFloat Val2(2.0f); APFloat f1((float)1.17549435e-38F); APFloat f2((float)1.17549435e-38F); f1.divide(Val2, rdmd); f2.divide(Val2, rdmd); APFloat f3(12.0f); f1.fusedMultiplyAdd(f2, f3, APFloat::rmNearestTiesToEven); EXPECT_EQ(12.0f, f1.convertToFloat()); } // Test for correct zero sign when answer is exactly zero. // fma(1.0, -1.0, 1.0) -> +ve 0. { APFloat f1(1.0); APFloat f2(-1.0); APFloat f3(1.0); f1.fusedMultiplyAdd(f2, f3, APFloat::rmNearestTiesToEven); EXPECT_TRUE(!f1.isNegative() && f1.isZero()); } // Test for correct zero sign when answer is exactly zero and rounding towards // negative. // fma(1.0, -1.0, 1.0) -> +ve 0. { APFloat f1(1.0); APFloat f2(-1.0); APFloat f3(1.0); f1.fusedMultiplyAdd(f2, f3, APFloat::rmTowardNegative); EXPECT_TRUE(f1.isNegative() && f1.isZero()); } // Test for correct (in this case -ve) sign when adding like signed zeros. // Test fma(0.0, -0.0, -0.0) -> -ve 0. { APFloat f1(0.0); APFloat f2(-0.0); APFloat f3(-0.0); f1.fusedMultiplyAdd(f2, f3, APFloat::rmNearestTiesToEven); EXPECT_TRUE(f1.isNegative() && f1.isZero()); } // Test -ve sign preservation when small negative results underflow. { APFloat f1(APFloat::IEEEdouble(), "-0x1p-1074"); APFloat f2(APFloat::IEEEdouble(), "+0x1p-1074"); APFloat f3(0.0); f1.fusedMultiplyAdd(f2, f3, APFloat::rmNearestTiesToEven); EXPECT_TRUE(f1.isNegative() && f1.isZero()); } // Test x87 extended precision case from http://llvm.org/PR20728. { APFloat M1(APFloat::x87DoubleExtended(), 1); APFloat M2(APFloat::x87DoubleExtended(), 1); APFloat A(APFloat::x87DoubleExtended(), 3); bool losesInfo = false; M1.fusedMultiplyAdd(M1, A, APFloat::rmNearestTiesToEven); M1.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_FALSE(losesInfo); EXPECT_EQ(4.0f, M1.convertToFloat()); } // Regression test that failed an assertion. { APFloat f1(-8.85242279E-41f); APFloat f2(2.0f); APFloat f3(8.85242279E-41f); f1.fusedMultiplyAdd(f2, f3, APFloat::rmNearestTiesToEven); EXPECT_EQ(-8.85242279E-41f, f1.convertToFloat()); } } TEST(APFloatTest, MinNum) { APFloat f1(1.0); APFloat f2(2.0); APFloat nan = APFloat::getNaN(APFloat::IEEEdouble()); EXPECT_EQ(1.0, minnum(f1, f2).convertToDouble()); EXPECT_EQ(1.0, minnum(f2, f1).convertToDouble()); EXPECT_EQ(1.0, minnum(f1, nan).convertToDouble()); EXPECT_EQ(1.0, minnum(nan, f1).convertToDouble()); } TEST(APFloatTest, MaxNum) { APFloat f1(1.0); APFloat f2(2.0); APFloat nan = APFloat::getNaN(APFloat::IEEEdouble()); EXPECT_EQ(2.0, maxnum(f1, f2).convertToDouble()); EXPECT_EQ(2.0, maxnum(f2, f1).convertToDouble()); EXPECT_EQ(1.0, maxnum(f1, nan).convertToDouble()); EXPECT_EQ(1.0, maxnum(nan, f1).convertToDouble()); } TEST(APFloatTest, Minimum) { APFloat f1(1.0); APFloat f2(2.0); APFloat zp(0.0); APFloat zn(-0.0); APFloat nan = APFloat::getNaN(APFloat::IEEEdouble()); EXPECT_EQ(1.0, minimum(f1, f2).convertToDouble()); EXPECT_EQ(1.0, minimum(f2, f1).convertToDouble()); EXPECT_EQ(-0.0, minimum(zp, zn).convertToDouble()); EXPECT_EQ(-0.0, minimum(zn, zp).convertToDouble()); EXPECT_TRUE(std::isnan(minimum(f1, nan).convertToDouble())); EXPECT_TRUE(std::isnan(minimum(nan, f1).convertToDouble())); } TEST(APFloatTest, Maximum) { APFloat f1(1.0); APFloat f2(2.0); APFloat zp(0.0); APFloat zn(-0.0); APFloat nan = APFloat::getNaN(APFloat::IEEEdouble()); EXPECT_EQ(2.0, maximum(f1, f2).convertToDouble()); EXPECT_EQ(2.0, maximum(f2, f1).convertToDouble()); EXPECT_EQ(0.0, maximum(zp, zn).convertToDouble()); EXPECT_EQ(0.0, maximum(zn, zp).convertToDouble()); EXPECT_TRUE(std::isnan(maximum(f1, nan).convertToDouble())); EXPECT_TRUE(std::isnan(maximum(nan, f1).convertToDouble())); } TEST(APFloatTest, Denormal) { APFloat::roundingMode rdmd = APFloat::rmNearestTiesToEven; // Test single precision { const char *MinNormalStr = "1.17549435082228750797e-38"; EXPECT_FALSE(APFloat(APFloat::IEEEsingle(), MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::IEEEsingle(), 0).isDenormal()); APFloat Val2(APFloat::IEEEsingle(), 2); APFloat T(APFloat::IEEEsingle(), MinNormalStr); T.divide(Val2, rdmd); EXPECT_TRUE(T.isDenormal()); } // Test double precision { const char *MinNormalStr = "2.22507385850720138309e-308"; EXPECT_FALSE(APFloat(APFloat::IEEEdouble(), MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::IEEEdouble(), 0).isDenormal()); APFloat Val2(APFloat::IEEEdouble(), 2); APFloat T(APFloat::IEEEdouble(), MinNormalStr); T.divide(Val2, rdmd); EXPECT_TRUE(T.isDenormal()); } // Test Intel double-ext { const char *MinNormalStr = "3.36210314311209350626e-4932"; EXPECT_FALSE(APFloat(APFloat::x87DoubleExtended(), MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::x87DoubleExtended(), 0).isDenormal()); APFloat Val2(APFloat::x87DoubleExtended(), 2); APFloat T(APFloat::x87DoubleExtended(), MinNormalStr); T.divide(Val2, rdmd); EXPECT_TRUE(T.isDenormal()); } // Test quadruple precision { const char *MinNormalStr = "3.36210314311209350626267781732175260e-4932"; EXPECT_FALSE(APFloat(APFloat::IEEEquad(), MinNormalStr).isDenormal()); EXPECT_FALSE(APFloat(APFloat::IEEEquad(), 0).isDenormal()); APFloat Val2(APFloat::IEEEquad(), 2); APFloat T(APFloat::IEEEquad(), MinNormalStr); T.divide(Val2, rdmd); EXPECT_TRUE(T.isDenormal()); } } TEST(APFloatTest, Zero) { EXPECT_EQ(0.0f, APFloat(0.0f).convertToFloat()); EXPECT_EQ(-0.0f, APFloat(-0.0f).convertToFloat()); EXPECT_TRUE(APFloat(-0.0f).isNegative()); EXPECT_EQ(0.0, APFloat(0.0).convertToDouble()); EXPECT_EQ(-0.0, APFloat(-0.0).convertToDouble()); EXPECT_TRUE(APFloat(-0.0).isNegative()); } TEST(APFloatTest, DecimalStringsWithoutNullTerminators) { // Make sure that we can parse strings without null terminators. // rdar://14323230. - APFloat Val(APFloat::IEEEdouble()); - Val.convertFromString(StringRef("0.00", 3), - llvm::APFloat::rmNearestTiesToEven); - EXPECT_EQ(Val.convertToDouble(), 0.0); - Val.convertFromString(StringRef("0.01", 3), - llvm::APFloat::rmNearestTiesToEven); - EXPECT_EQ(Val.convertToDouble(), 0.0); - Val.convertFromString(StringRef("0.09", 3), - llvm::APFloat::rmNearestTiesToEven); - EXPECT_EQ(Val.convertToDouble(), 0.0); - Val.convertFromString(StringRef("0.095", 4), - llvm::APFloat::rmNearestTiesToEven); - EXPECT_EQ(Val.convertToDouble(), 0.09); - Val.convertFromString(StringRef("0.00e+3", 7), - llvm::APFloat::rmNearestTiesToEven); - EXPECT_EQ(Val.convertToDouble(), 0.00); - Val.convertFromString(StringRef("0e+3", 4), - llvm::APFloat::rmNearestTiesToEven); - EXPECT_EQ(Val.convertToDouble(), 0.00); - + EXPECT_EQ(convertToDoubleFromString(StringRef("0.00", 3)), 0.0); + EXPECT_EQ(convertToDoubleFromString(StringRef("0.01", 3)), 0.0); + EXPECT_EQ(convertToDoubleFromString(StringRef("0.09", 3)), 0.0); + EXPECT_EQ(convertToDoubleFromString(StringRef("0.095", 4)), 0.09); + EXPECT_EQ(convertToDoubleFromString(StringRef("0.00e+3", 7)), 0.00); + EXPECT_EQ(convertToDoubleFromString(StringRef("0e+3", 4)), 0.00); } TEST(APFloatTest, fromZeroDecimalString) { EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0.").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0.").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0.").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), ".0").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+.0").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-.0").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0.0").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0.0").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0.0").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "00000.").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+00000.").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-00000.").convertToDouble()); EXPECT_EQ(0.0, APFloat(APFloat::IEEEdouble(), ".00000").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+.00000").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-.00000").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0000.00000").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0000.00000").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0000.00000").convertToDouble()); } TEST(APFloatTest, fromZeroDecimalSingleExponentString) { EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0e1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0e1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0e1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0e+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0e+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0e+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0e-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0e-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0e-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0.e1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0.e1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0.e1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0.e+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0.e+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0.e+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0.e-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0.e-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0.e-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), ".0e1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+.0e1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-.0e1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), ".0e+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+.0e+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-.0e+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), ".0e-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+.0e-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-.0e-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0.0e1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0.0e1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0.0e1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0.0e+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0.0e+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0.0e+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0.0e-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0.0e-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0.0e-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "000.0000e1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+000.0000e+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-000.0000e+1").convertToDouble()); } TEST(APFloatTest, fromZeroDecimalLargeExponentString) { EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0e1234").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0e1234").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0e1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0e+1234").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0e+1234").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0e+1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0e-1234").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0e-1234").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0e-1234").convertToDouble()); EXPECT_EQ(0.0, APFloat(APFloat::IEEEdouble(), "000.0000e1234").convertToDouble()); EXPECT_EQ(0.0, APFloat(APFloat::IEEEdouble(), "000.0000e-1234").convertToDouble()); EXPECT_EQ(0.0, APFloat(APFloat::IEEEdouble(), StringRef("0e1234" "\0" "2", 6)).convertToDouble()); } TEST(APFloatTest, fromZeroHexadecimalString) { EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0p1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x0p1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x0p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0p+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x0p+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x0p+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0p-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x0p-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x0p-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0.p1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x0.p1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x0.p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0.p+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x0.p+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x0.p+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0.p-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x0.p-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x0.p-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x.0p1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x.0p1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x.0p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x.0p+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x.0p+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x.0p+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x.0p-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x.0p-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x.0p-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0.0p1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x0.0p1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x0.0p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0.0p+1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x0.0p+1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x0.0p+1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0.0p-1").convertToDouble()); EXPECT_EQ(+0.0, APFloat(APFloat::IEEEdouble(), "+0x0.0p-1").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x0.0p-1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x00000.p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0000.00000p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x.00000p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0.p1").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0p1234").convertToDouble()); EXPECT_EQ(-0.0, APFloat(APFloat::IEEEdouble(), "-0x0p1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x00000.p1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0000.00000p1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x.00000p1234").convertToDouble()); EXPECT_EQ( 0.0, APFloat(APFloat::IEEEdouble(), "0x0.p1234").convertToDouble()); } TEST(APFloatTest, fromDecimalString) { EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "1").convertToDouble()); EXPECT_EQ(2.0, APFloat(APFloat::IEEEdouble(), "2.").convertToDouble()); EXPECT_EQ(0.5, APFloat(APFloat::IEEEdouble(), ".5").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "1.0").convertToDouble()); EXPECT_EQ(-2.0, APFloat(APFloat::IEEEdouble(), "-2").convertToDouble()); EXPECT_EQ(-4.0, APFloat(APFloat::IEEEdouble(), "-4.").convertToDouble()); EXPECT_EQ(-0.5, APFloat(APFloat::IEEEdouble(), "-.5").convertToDouble()); EXPECT_EQ(-1.5, APFloat(APFloat::IEEEdouble(), "-1.5").convertToDouble()); EXPECT_EQ(1.25e12, APFloat(APFloat::IEEEdouble(), "1.25e12").convertToDouble()); EXPECT_EQ(1.25e+12, APFloat(APFloat::IEEEdouble(), "1.25e+12").convertToDouble()); EXPECT_EQ(1.25e-12, APFloat(APFloat::IEEEdouble(), "1.25e-12").convertToDouble()); EXPECT_EQ(1024.0, APFloat(APFloat::IEEEdouble(), "1024.").convertToDouble()); EXPECT_EQ(1024.05, APFloat(APFloat::IEEEdouble(), "1024.05000").convertToDouble()); EXPECT_EQ(0.05, APFloat(APFloat::IEEEdouble(), ".05000").convertToDouble()); EXPECT_EQ(2.0, APFloat(APFloat::IEEEdouble(), "2.").convertToDouble()); EXPECT_EQ(2.0e2, APFloat(APFloat::IEEEdouble(), "2.e2").convertToDouble()); EXPECT_EQ(2.0e+2, APFloat(APFloat::IEEEdouble(), "2.e+2").convertToDouble()); EXPECT_EQ(2.0e-2, APFloat(APFloat::IEEEdouble(), "2.e-2").convertToDouble()); EXPECT_EQ(2.05e2, APFloat(APFloat::IEEEdouble(), "002.05000e2").convertToDouble()); EXPECT_EQ(2.05e+2, APFloat(APFloat::IEEEdouble(), "002.05000e+2").convertToDouble()); EXPECT_EQ(2.05e-2, APFloat(APFloat::IEEEdouble(), "002.05000e-2").convertToDouble()); EXPECT_EQ(2.05e12, APFloat(APFloat::IEEEdouble(), "002.05000e12").convertToDouble()); EXPECT_EQ(2.05e+12, APFloat(APFloat::IEEEdouble(), "002.05000e+12").convertToDouble()); EXPECT_EQ(2.05e-12, APFloat(APFloat::IEEEdouble(), "002.05000e-12").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "1e").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "+1e").convertToDouble()); EXPECT_EQ(-1.0, APFloat(APFloat::IEEEdouble(), "-1e").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "1.e").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "+1.e").convertToDouble()); EXPECT_EQ(-1.0, APFloat(APFloat::IEEEdouble(), "-1.e").convertToDouble()); EXPECT_EQ(0.1, APFloat(APFloat::IEEEdouble(), ".1e").convertToDouble()); EXPECT_EQ(0.1, APFloat(APFloat::IEEEdouble(), "+.1e").convertToDouble()); EXPECT_EQ(-0.1, APFloat(APFloat::IEEEdouble(), "-.1e").convertToDouble()); EXPECT_EQ(1.1, APFloat(APFloat::IEEEdouble(), "1.1e").convertToDouble()); EXPECT_EQ(1.1, APFloat(APFloat::IEEEdouble(), "+1.1e").convertToDouble()); EXPECT_EQ(-1.1, APFloat(APFloat::IEEEdouble(), "-1.1e").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "1e+").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "1e-").convertToDouble()); EXPECT_EQ(0.1, APFloat(APFloat::IEEEdouble(), ".1e").convertToDouble()); EXPECT_EQ(0.1, APFloat(APFloat::IEEEdouble(), ".1e+").convertToDouble()); EXPECT_EQ(0.1, APFloat(APFloat::IEEEdouble(), ".1e-").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "1.0e").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "1.0e+").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "1.0e-").convertToDouble()); // These are "carefully selected" to overflow the fast log-base // calculations in APFloat.cpp EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "99e99999").isInfinity()); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "-99e99999").isInfinity()); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "1e-99999").isPosZero()); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "-1e-99999").isNegZero()); EXPECT_EQ(2.71828, convertToDoubleFromString("2.71828")); } TEST(APFloatTest, fromToStringSpecials) { auto expects = [] (const char *first, const char *second) { std::string roundtrip = convertToString(convertToDoubleFromString(second), 0, 3); EXPECT_STREQ(first, roundtrip.c_str()); }; expects("+Inf", "+Inf"); expects("+Inf", "INFINITY"); expects("+Inf", "inf"); expects("-Inf", "-Inf"); expects("-Inf", "-INFINITY"); expects("-Inf", "-inf"); expects("NaN", "NaN"); expects("NaN", "nan"); expects("NaN", "-NaN"); expects("NaN", "-nan"); } TEST(APFloatTest, fromHexadecimalString) { EXPECT_EQ( 1.0, APFloat(APFloat::IEEEdouble(), "0x1p0").convertToDouble()); EXPECT_EQ(+1.0, APFloat(APFloat::IEEEdouble(), "+0x1p0").convertToDouble()); EXPECT_EQ(-1.0, APFloat(APFloat::IEEEdouble(), "-0x1p0").convertToDouble()); EXPECT_EQ( 1.0, APFloat(APFloat::IEEEdouble(), "0x1p+0").convertToDouble()); EXPECT_EQ(+1.0, APFloat(APFloat::IEEEdouble(), "+0x1p+0").convertToDouble()); EXPECT_EQ(-1.0, APFloat(APFloat::IEEEdouble(), "-0x1p+0").convertToDouble()); EXPECT_EQ( 1.0, APFloat(APFloat::IEEEdouble(), "0x1p-0").convertToDouble()); EXPECT_EQ(+1.0, APFloat(APFloat::IEEEdouble(), "+0x1p-0").convertToDouble()); EXPECT_EQ(-1.0, APFloat(APFloat::IEEEdouble(), "-0x1p-0").convertToDouble()); EXPECT_EQ( 2.0, APFloat(APFloat::IEEEdouble(), "0x1p1").convertToDouble()); EXPECT_EQ(+2.0, APFloat(APFloat::IEEEdouble(), "+0x1p1").convertToDouble()); EXPECT_EQ(-2.0, APFloat(APFloat::IEEEdouble(), "-0x1p1").convertToDouble()); EXPECT_EQ( 2.0, APFloat(APFloat::IEEEdouble(), "0x1p+1").convertToDouble()); EXPECT_EQ(+2.0, APFloat(APFloat::IEEEdouble(), "+0x1p+1").convertToDouble()); EXPECT_EQ(-2.0, APFloat(APFloat::IEEEdouble(), "-0x1p+1").convertToDouble()); EXPECT_EQ( 0.5, APFloat(APFloat::IEEEdouble(), "0x1p-1").convertToDouble()); EXPECT_EQ(+0.5, APFloat(APFloat::IEEEdouble(), "+0x1p-1").convertToDouble()); EXPECT_EQ(-0.5, APFloat(APFloat::IEEEdouble(), "-0x1p-1").convertToDouble()); EXPECT_EQ( 3.0, APFloat(APFloat::IEEEdouble(), "0x1.8p1").convertToDouble()); EXPECT_EQ(+3.0, APFloat(APFloat::IEEEdouble(), "+0x1.8p1").convertToDouble()); EXPECT_EQ(-3.0, APFloat(APFloat::IEEEdouble(), "-0x1.8p1").convertToDouble()); EXPECT_EQ( 3.0, APFloat(APFloat::IEEEdouble(), "0x1.8p+1").convertToDouble()); EXPECT_EQ(+3.0, APFloat(APFloat::IEEEdouble(), "+0x1.8p+1").convertToDouble()); EXPECT_EQ(-3.0, APFloat(APFloat::IEEEdouble(), "-0x1.8p+1").convertToDouble()); EXPECT_EQ( 0.75, APFloat(APFloat::IEEEdouble(), "0x1.8p-1").convertToDouble()); EXPECT_EQ(+0.75, APFloat(APFloat::IEEEdouble(), "+0x1.8p-1").convertToDouble()); EXPECT_EQ(-0.75, APFloat(APFloat::IEEEdouble(), "-0x1.8p-1").convertToDouble()); EXPECT_EQ( 8192.0, APFloat(APFloat::IEEEdouble(), "0x1000.000p1").convertToDouble()); EXPECT_EQ(+8192.0, APFloat(APFloat::IEEEdouble(), "+0x1000.000p1").convertToDouble()); EXPECT_EQ(-8192.0, APFloat(APFloat::IEEEdouble(), "-0x1000.000p1").convertToDouble()); EXPECT_EQ( 8192.0, APFloat(APFloat::IEEEdouble(), "0x1000.000p+1").convertToDouble()); EXPECT_EQ(+8192.0, APFloat(APFloat::IEEEdouble(), "+0x1000.000p+1").convertToDouble()); EXPECT_EQ(-8192.0, APFloat(APFloat::IEEEdouble(), "-0x1000.000p+1").convertToDouble()); EXPECT_EQ( 2048.0, APFloat(APFloat::IEEEdouble(), "0x1000.000p-1").convertToDouble()); EXPECT_EQ(+2048.0, APFloat(APFloat::IEEEdouble(), "+0x1000.000p-1").convertToDouble()); EXPECT_EQ(-2048.0, APFloat(APFloat::IEEEdouble(), "-0x1000.000p-1").convertToDouble()); EXPECT_EQ( 8192.0, APFloat(APFloat::IEEEdouble(), "0x1000p1").convertToDouble()); EXPECT_EQ(+8192.0, APFloat(APFloat::IEEEdouble(), "+0x1000p1").convertToDouble()); EXPECT_EQ(-8192.0, APFloat(APFloat::IEEEdouble(), "-0x1000p1").convertToDouble()); EXPECT_EQ( 8192.0, APFloat(APFloat::IEEEdouble(), "0x1000p+1").convertToDouble()); EXPECT_EQ(+8192.0, APFloat(APFloat::IEEEdouble(), "+0x1000p+1").convertToDouble()); EXPECT_EQ(-8192.0, APFloat(APFloat::IEEEdouble(), "-0x1000p+1").convertToDouble()); EXPECT_EQ( 2048.0, APFloat(APFloat::IEEEdouble(), "0x1000p-1").convertToDouble()); EXPECT_EQ(+2048.0, APFloat(APFloat::IEEEdouble(), "+0x1000p-1").convertToDouble()); EXPECT_EQ(-2048.0, APFloat(APFloat::IEEEdouble(), "-0x1000p-1").convertToDouble()); EXPECT_EQ( 16384.0, APFloat(APFloat::IEEEdouble(), "0x10p10").convertToDouble()); EXPECT_EQ(+16384.0, APFloat(APFloat::IEEEdouble(), "+0x10p10").convertToDouble()); EXPECT_EQ(-16384.0, APFloat(APFloat::IEEEdouble(), "-0x10p10").convertToDouble()); EXPECT_EQ( 16384.0, APFloat(APFloat::IEEEdouble(), "0x10p+10").convertToDouble()); EXPECT_EQ(+16384.0, APFloat(APFloat::IEEEdouble(), "+0x10p+10").convertToDouble()); EXPECT_EQ(-16384.0, APFloat(APFloat::IEEEdouble(), "-0x10p+10").convertToDouble()); EXPECT_EQ( 0.015625, APFloat(APFloat::IEEEdouble(), "0x10p-10").convertToDouble()); EXPECT_EQ(+0.015625, APFloat(APFloat::IEEEdouble(), "+0x10p-10").convertToDouble()); EXPECT_EQ(-0.015625, APFloat(APFloat::IEEEdouble(), "-0x10p-10").convertToDouble()); EXPECT_EQ(1.0625, APFloat(APFloat::IEEEdouble(), "0x1.1p0").convertToDouble()); EXPECT_EQ(1.0, APFloat(APFloat::IEEEdouble(), "0x1p0").convertToDouble()); EXPECT_EQ(convertToDoubleFromString("0x1p-150"), convertToDoubleFromString("+0x800000000000000001.p-221")); EXPECT_EQ(2251799813685248.5, convertToDoubleFromString("0x80000000000004000000.010p-28")); } TEST(APFloatTest, toString) { ASSERT_EQ("10", convertToString(10.0, 6, 3)); ASSERT_EQ("1.0E+1", convertToString(10.0, 6, 0)); ASSERT_EQ("10100", convertToString(1.01E+4, 5, 2)); ASSERT_EQ("1.01E+4", convertToString(1.01E+4, 4, 2)); ASSERT_EQ("1.01E+4", convertToString(1.01E+4, 5, 1)); ASSERT_EQ("0.0101", convertToString(1.01E-2, 5, 2)); ASSERT_EQ("0.0101", convertToString(1.01E-2, 4, 2)); ASSERT_EQ("1.01E-2", convertToString(1.01E-2, 5, 1)); ASSERT_EQ("0.78539816339744828", convertToString(0.78539816339744830961, 0, 3)); ASSERT_EQ("4.9406564584124654E-324", convertToString(4.9406564584124654e-324, 0, 3)); ASSERT_EQ("873.18340000000001", convertToString(873.1834, 0, 1)); ASSERT_EQ("8.7318340000000001E+2", convertToString(873.1834, 0, 0)); ASSERT_EQ("1.7976931348623157E+308", convertToString(1.7976931348623157E+308, 0, 0)); ASSERT_EQ("10", convertToString(10.0, 6, 3, false)); ASSERT_EQ("1.000000e+01", convertToString(10.0, 6, 0, false)); ASSERT_EQ("10100", convertToString(1.01E+4, 5, 2, false)); ASSERT_EQ("1.0100e+04", convertToString(1.01E+4, 4, 2, false)); ASSERT_EQ("1.01000e+04", convertToString(1.01E+4, 5, 1, false)); ASSERT_EQ("0.0101", convertToString(1.01E-2, 5, 2, false)); ASSERT_EQ("0.0101", convertToString(1.01E-2, 4, 2, false)); ASSERT_EQ("1.01000e-02", convertToString(1.01E-2, 5, 1, false)); ASSERT_EQ("0.78539816339744828", convertToString(0.78539816339744830961, 0, 3, false)); ASSERT_EQ("4.94065645841246540e-324", convertToString(4.9406564584124654e-324, 0, 3, false)); ASSERT_EQ("873.18340000000001", convertToString(873.1834, 0, 1, false)); ASSERT_EQ("8.73183400000000010e+02", convertToString(873.1834, 0, 0, false)); ASSERT_EQ("1.79769313486231570e+308", convertToString(1.7976931348623157E+308, 0, 0, false)); { SmallString<64> Str; APFloat UnnormalZero(APFloat::x87DoubleExtended(), APInt(80, {0, 1})); UnnormalZero.toString(Str); ASSERT_EQ("NaN", Str); } } TEST(APFloatTest, toInteger) { bool isExact = false; APSInt result(5, /*isUnsigned=*/true); EXPECT_EQ(APFloat::opOK, APFloat(APFloat::IEEEdouble(), "10") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_TRUE(isExact); EXPECT_EQ(APSInt(APInt(5, 10), true), result); EXPECT_EQ(APFloat::opInvalidOp, APFloat(APFloat::IEEEdouble(), "-10") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_FALSE(isExact); EXPECT_EQ(APSInt::getMinValue(5, true), result); EXPECT_EQ(APFloat::opInvalidOp, APFloat(APFloat::IEEEdouble(), "32") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_FALSE(isExact); EXPECT_EQ(APSInt::getMaxValue(5, true), result); EXPECT_EQ(APFloat::opInexact, APFloat(APFloat::IEEEdouble(), "7.9") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_FALSE(isExact); EXPECT_EQ(APSInt(APInt(5, 7), true), result); result.setIsUnsigned(false); EXPECT_EQ(APFloat::opOK, APFloat(APFloat::IEEEdouble(), "-10") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_TRUE(isExact); EXPECT_EQ(APSInt(APInt(5, -10, true), false), result); EXPECT_EQ(APFloat::opInvalidOp, APFloat(APFloat::IEEEdouble(), "-17") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_FALSE(isExact); EXPECT_EQ(APSInt::getMinValue(5, false), result); EXPECT_EQ(APFloat::opInvalidOp, APFloat(APFloat::IEEEdouble(), "16") .convertToInteger(result, APFloat::rmTowardZero, &isExact)); EXPECT_FALSE(isExact); EXPECT_EQ(APSInt::getMaxValue(5, false), result); } static APInt nanbitsFromAPInt(const fltSemantics &Sem, bool SNaN, bool Negative, uint64_t payload) { APInt appayload(64, payload); if (SNaN) return APFloat::getSNaN(Sem, Negative, &appayload).bitcastToAPInt(); else return APFloat::getQNaN(Sem, Negative, &appayload).bitcastToAPInt(); } TEST(APFloatTest, makeNaN) { const struct { uint64_t expected; const fltSemantics &semantics; bool SNaN; bool Negative; uint64_t payload; } tests[] = { /* expected semantics SNaN Neg payload */ { 0x7fc00000ULL, APFloat::IEEEsingle(), false, false, 0x00000000ULL }, { 0xffc00000ULL, APFloat::IEEEsingle(), false, true, 0x00000000ULL }, { 0x7fc0ae72ULL, APFloat::IEEEsingle(), false, false, 0x0000ae72ULL }, { 0x7fffae72ULL, APFloat::IEEEsingle(), false, false, 0xffffae72ULL }, { 0x7fdaae72ULL, APFloat::IEEEsingle(), false, false, 0x00daae72ULL }, { 0x7fa00000ULL, APFloat::IEEEsingle(), true, false, 0x00000000ULL }, { 0xffa00000ULL, APFloat::IEEEsingle(), true, true, 0x00000000ULL }, { 0x7f80ae72ULL, APFloat::IEEEsingle(), true, false, 0x0000ae72ULL }, { 0x7fbfae72ULL, APFloat::IEEEsingle(), true, false, 0xffffae72ULL }, { 0x7f9aae72ULL, APFloat::IEEEsingle(), true, false, 0x001aae72ULL }, { 0x7ff8000000000000ULL, APFloat::IEEEdouble(), false, false, 0x0000000000000000ULL }, { 0xfff8000000000000ULL, APFloat::IEEEdouble(), false, true, 0x0000000000000000ULL }, { 0x7ff800000000ae72ULL, APFloat::IEEEdouble(), false, false, 0x000000000000ae72ULL }, { 0x7fffffffffffae72ULL, APFloat::IEEEdouble(), false, false, 0xffffffffffffae72ULL }, { 0x7ffdaaaaaaaaae72ULL, APFloat::IEEEdouble(), false, false, 0x000daaaaaaaaae72ULL }, { 0x7ff4000000000000ULL, APFloat::IEEEdouble(), true, false, 0x0000000000000000ULL }, { 0xfff4000000000000ULL, APFloat::IEEEdouble(), true, true, 0x0000000000000000ULL }, { 0x7ff000000000ae72ULL, APFloat::IEEEdouble(), true, false, 0x000000000000ae72ULL }, { 0x7ff7ffffffffae72ULL, APFloat::IEEEdouble(), true, false, 0xffffffffffffae72ULL }, { 0x7ff1aaaaaaaaae72ULL, APFloat::IEEEdouble(), true, false, 0x0001aaaaaaaaae72ULL }, }; for (const auto &t : tests) { ASSERT_EQ(t.expected, nanbitsFromAPInt(t.semantics, t.SNaN, t.Negative, t.payload)); } } #ifdef GTEST_HAS_DEATH_TEST #ifndef NDEBUG TEST(APFloatTest, SemanticsDeath) { EXPECT_DEATH(APFloat(APFloat::IEEEsingle(), 0).convertToDouble(), "Float semantics are not IEEEdouble"); EXPECT_DEATH(APFloat(APFloat::IEEEdouble(), 0).convertToFloat(), "Float semantics are not IEEEsingle"); } #endif #endif TEST(APFloatTest, StringDecimalError) { EXPECT_EQ("Invalid string length", convertToErrorFromString("")); EXPECT_EQ("String has no digits", convertToErrorFromString("+")); EXPECT_EQ("String has no digits", convertToErrorFromString("-")); EXPECT_EQ("Invalid character in significand", convertToErrorFromString(StringRef("\0", 1))); EXPECT_EQ("Invalid character in significand", convertToErrorFromString(StringRef("1\0", 2))); EXPECT_EQ("Invalid character in significand", convertToErrorFromString(StringRef("1" "\0" "2", 3))); EXPECT_EQ("Invalid character in significand", convertToErrorFromString(StringRef("1" "\0" "2e1", 5))); EXPECT_EQ("Invalid character in exponent", convertToErrorFromString(StringRef("1e\0", 3))); EXPECT_EQ("Invalid character in exponent", convertToErrorFromString(StringRef("1e1\0", 4))); EXPECT_EQ("Invalid character in exponent", convertToErrorFromString(StringRef("1e1" "\0" "2", 5))); EXPECT_EQ("Invalid character in significand", convertToErrorFromString("1.0f")); EXPECT_EQ("String contains multiple dots", convertToErrorFromString("..")); EXPECT_EQ("String contains multiple dots", convertToErrorFromString("..0")); EXPECT_EQ("String contains multiple dots", convertToErrorFromString("1.0.0")); } TEST(APFloatTest, StringDecimalSignificandError) { EXPECT_EQ("Significand has no digits", convertToErrorFromString( ".")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+.")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-.")); EXPECT_EQ("Significand has no digits", convertToErrorFromString( "e")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+e")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-e")); EXPECT_EQ("Significand has no digits", convertToErrorFromString( "e1")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+e1")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-e1")); EXPECT_EQ("Significand has no digits", convertToErrorFromString( ".e1")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+.e1")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-.e1")); EXPECT_EQ("Significand has no digits", convertToErrorFromString( ".e")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+.e")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-.e")); } TEST(APFloatTest, StringHexadecimalError) { EXPECT_EQ("Invalid string", convertToErrorFromString( "0x")); EXPECT_EQ("Invalid string", convertToErrorFromString("+0x")); EXPECT_EQ("Invalid string", convertToErrorFromString("-0x")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString( "0x0")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString("+0x0")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString("-0x0")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString( "0x0.")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString("+0x0.")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString("-0x0.")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString( "0x.0")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString("+0x.0")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString("-0x.0")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString( "0x0.0")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString("+0x0.0")); EXPECT_EQ("Hex strings require an exponent", convertToErrorFromString("-0x0.0")); EXPECT_EQ("Invalid character in significand", convertToErrorFromString(StringRef("0x\0", 3))); EXPECT_EQ("Invalid character in significand", convertToErrorFromString(StringRef("0x1\0", 4))); EXPECT_EQ("Invalid character in significand", convertToErrorFromString(StringRef("0x1" "\0" "2", 5))); EXPECT_EQ("Invalid character in significand", convertToErrorFromString(StringRef("0x1" "\0" "2p1", 7))); EXPECT_EQ("Invalid character in exponent", convertToErrorFromString(StringRef("0x1p\0", 5))); EXPECT_EQ("Invalid character in exponent", convertToErrorFromString(StringRef("0x1p1\0", 6))); EXPECT_EQ("Invalid character in exponent", convertToErrorFromString(StringRef("0x1p1" "\0" "2", 7))); EXPECT_EQ("Invalid character in exponent", convertToErrorFromString("0x1p0f")); EXPECT_EQ("String contains multiple dots", convertToErrorFromString("0x..p1")); EXPECT_EQ("String contains multiple dots", convertToErrorFromString("0x..0p1")); EXPECT_EQ("String contains multiple dots", convertToErrorFromString("0x1.0.0p1")); } TEST(APFloatTest, StringHexadecimalSignificandError) { EXPECT_EQ("Significand has no digits", convertToErrorFromString( "0x.")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+0x.")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-0x.")); EXPECT_EQ("Significand has no digits", convertToErrorFromString( "0xp")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+0xp")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-0xp")); EXPECT_EQ("Significand has no digits", convertToErrorFromString( "0xp+")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+0xp+")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-0xp+")); EXPECT_EQ("Significand has no digits", convertToErrorFromString( "0xp-")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+0xp-")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-0xp-")); EXPECT_EQ("Significand has no digits", convertToErrorFromString( "0x.p")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+0x.p")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-0x.p")); EXPECT_EQ("Significand has no digits", convertToErrorFromString( "0x.p+")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+0x.p+")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-0x.p+")); EXPECT_EQ("Significand has no digits", convertToErrorFromString( "0x.p-")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("+0x.p-")); EXPECT_EQ("Significand has no digits", convertToErrorFromString("-0x.p-")); } TEST(APFloatTest, StringHexadecimalExponentError) { EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x1p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x1p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x1p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x1p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x1p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x1p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x1p-")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x1p-")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x1p-")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x1.p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x1.p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x1.p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x1.p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x1.p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x1.p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x1.p-")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x1.p-")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x1.p-")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x.1p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x.1p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x.1p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x.1p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x.1p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x.1p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x.1p-")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x.1p-")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x.1p-")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x1.1p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x1.1p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x1.1p")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x1.1p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x1.1p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x1.1p+")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString( "0x1.1p-")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("+0x1.1p-")); EXPECT_EQ("Exponent has no digits", convertToErrorFromString("-0x1.1p-")); } TEST(APFloatTest, exactInverse) { APFloat inv(0.0f); // Trivial operation. EXPECT_TRUE(APFloat(2.0).getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(0.5))); EXPECT_TRUE(APFloat(2.0f).getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(0.5f))); EXPECT_TRUE(APFloat(APFloat::IEEEquad(), "2.0").getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(APFloat::IEEEquad(), "0.5"))); EXPECT_TRUE(APFloat(APFloat::PPCDoubleDouble(), "2.0").getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(APFloat::PPCDoubleDouble(), "0.5"))); EXPECT_TRUE(APFloat(APFloat::x87DoubleExtended(), "2.0").getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(APFloat::x87DoubleExtended(), "0.5"))); // FLT_MIN EXPECT_TRUE(APFloat(1.17549435e-38f).getExactInverse(&inv)); EXPECT_TRUE(inv.bitwiseIsEqual(APFloat(8.5070592e+37f))); // Large float, inverse is a denormal. EXPECT_FALSE(APFloat(1.7014118e38f).getExactInverse(nullptr)); // Zero EXPECT_FALSE(APFloat(0.0).getExactInverse(nullptr)); // Denormalized float EXPECT_FALSE(APFloat(1.40129846e-45f).getExactInverse(nullptr)); } TEST(APFloatTest, roundToIntegral) { APFloat T(-0.5), S(3.14), R(APFloat::getLargest(APFloat::IEEEdouble())), P(0.0); P = T; P.roundToIntegral(APFloat::rmTowardZero); EXPECT_EQ(-0.0, P.convertToDouble()); P = T; P.roundToIntegral(APFloat::rmTowardNegative); EXPECT_EQ(-1.0, P.convertToDouble()); P = T; P.roundToIntegral(APFloat::rmTowardPositive); EXPECT_EQ(-0.0, P.convertToDouble()); P = T; P.roundToIntegral(APFloat::rmNearestTiesToEven); EXPECT_EQ(-0.0, P.convertToDouble()); P = S; P.roundToIntegral(APFloat::rmTowardZero); EXPECT_EQ(3.0, P.convertToDouble()); P = S; P.roundToIntegral(APFloat::rmTowardNegative); EXPECT_EQ(3.0, P.convertToDouble()); P = S; P.roundToIntegral(APFloat::rmTowardPositive); EXPECT_EQ(4.0, P.convertToDouble()); P = S; P.roundToIntegral(APFloat::rmNearestTiesToEven); EXPECT_EQ(3.0, P.convertToDouble()); P = R; P.roundToIntegral(APFloat::rmTowardZero); EXPECT_EQ(R.convertToDouble(), P.convertToDouble()); P = R; P.roundToIntegral(APFloat::rmTowardNegative); EXPECT_EQ(R.convertToDouble(), P.convertToDouble()); P = R; P.roundToIntegral(APFloat::rmTowardPositive); EXPECT_EQ(R.convertToDouble(), P.convertToDouble()); P = R; P.roundToIntegral(APFloat::rmNearestTiesToEven); EXPECT_EQ(R.convertToDouble(), P.convertToDouble()); P = APFloat::getZero(APFloat::IEEEdouble()); P.roundToIntegral(APFloat::rmTowardZero); EXPECT_EQ(0.0, P.convertToDouble()); P = APFloat::getZero(APFloat::IEEEdouble(), true); P.roundToIntegral(APFloat::rmTowardZero); EXPECT_EQ(-0.0, P.convertToDouble()); P = APFloat::getNaN(APFloat::IEEEdouble()); P.roundToIntegral(APFloat::rmTowardZero); EXPECT_TRUE(std::isnan(P.convertToDouble())); P = APFloat::getInf(APFloat::IEEEdouble()); P.roundToIntegral(APFloat::rmTowardZero); EXPECT_TRUE(std::isinf(P.convertToDouble()) && P.convertToDouble() > 0.0); P = APFloat::getInf(APFloat::IEEEdouble(), true); P.roundToIntegral(APFloat::rmTowardZero); EXPECT_TRUE(std::isinf(P.convertToDouble()) && P.convertToDouble() < 0.0); } TEST(APFloatTest, isInteger) { APFloat T(-0.0); EXPECT_TRUE(T.isInteger()); T = APFloat(3.14159); EXPECT_FALSE(T.isInteger()); T = APFloat::getNaN(APFloat::IEEEdouble()); EXPECT_FALSE(T.isInteger()); T = APFloat::getInf(APFloat::IEEEdouble()); EXPECT_FALSE(T.isInteger()); T = APFloat::getInf(APFloat::IEEEdouble(), true); EXPECT_FALSE(T.isInteger()); T = APFloat::getLargest(APFloat::IEEEdouble()); EXPECT_TRUE(T.isInteger()); } TEST(DoubleAPFloatTest, isInteger) { APFloat F1(-0.0); APFloat F2(-0.0); llvm::detail::DoubleAPFloat T(APFloat::PPCDoubleDouble(), std::move(F1), std::move(F2)); EXPECT_TRUE(T.isInteger()); APFloat F3(3.14159); APFloat F4(-0.0); llvm::detail::DoubleAPFloat T2(APFloat::PPCDoubleDouble(), std::move(F3), std::move(F4)); EXPECT_FALSE(T2.isInteger()); APFloat F5(-0.0); APFloat F6(3.14159); llvm::detail::DoubleAPFloat T3(APFloat::PPCDoubleDouble(), std::move(F5), std::move(F6)); EXPECT_FALSE(T3.isInteger()); } TEST(APFloatTest, getLargest) { EXPECT_EQ(3.402823466e+38f, APFloat::getLargest(APFloat::IEEEsingle()).convertToFloat()); EXPECT_EQ(1.7976931348623158e+308, APFloat::getLargest(APFloat::IEEEdouble()).convertToDouble()); } TEST(APFloatTest, getSmallest) { APFloat test = APFloat::getSmallest(APFloat::IEEEsingle(), false); APFloat expected = APFloat(APFloat::IEEEsingle(), "0x0.000002p-126"); EXPECT_FALSE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallest(APFloat::IEEEsingle(), true); expected = APFloat(APFloat::IEEEsingle(), "-0x0.000002p-126"); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallest(APFloat::IEEEquad(), false); expected = APFloat(APFloat::IEEEquad(), "0x0.0000000000000000000000000001p-16382"); EXPECT_FALSE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallest(APFloat::IEEEquad(), true); expected = APFloat(APFloat::IEEEquad(), "-0x0.0000000000000000000000000001p-16382"); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_TRUE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); } TEST(APFloatTest, getSmallestNormalized) { APFloat test = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), false); APFloat expected = APFloat(APFloat::IEEEsingle(), "0x1p-126"); EXPECT_FALSE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), true); expected = APFloat(APFloat::IEEEsingle(), "-0x1p-126"); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallestNormalized(APFloat::IEEEquad(), false); expected = APFloat(APFloat::IEEEquad(), "0x1p-16382"); EXPECT_FALSE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); test = APFloat::getSmallestNormalized(APFloat::IEEEquad(), true); expected = APFloat(APFloat::IEEEquad(), "-0x1p-16382"); EXPECT_TRUE(test.isNegative()); EXPECT_TRUE(test.isFiniteNonZero()); EXPECT_FALSE(test.isDenormal()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); } TEST(APFloatTest, getZero) { struct { const fltSemantics *semantics; const bool sign; const unsigned long long bitPattern[2]; const unsigned bitPatternLength; } const GetZeroTest[] = { { &APFloat::IEEEhalf(), false, {0, 0}, 1}, { &APFloat::IEEEhalf(), true, {0x8000ULL, 0}, 1}, { &APFloat::IEEEsingle(), false, {0, 0}, 1}, { &APFloat::IEEEsingle(), true, {0x80000000ULL, 0}, 1}, { &APFloat::IEEEdouble(), false, {0, 0}, 1}, { &APFloat::IEEEdouble(), true, {0x8000000000000000ULL, 0}, 1}, { &APFloat::IEEEquad(), false, {0, 0}, 2}, { &APFloat::IEEEquad(), true, {0, 0x8000000000000000ULL}, 2}, { &APFloat::PPCDoubleDouble(), false, {0, 0}, 2}, { &APFloat::PPCDoubleDouble(), true, {0x8000000000000000ULL, 0}, 2}, { &APFloat::x87DoubleExtended(), false, {0, 0}, 2}, { &APFloat::x87DoubleExtended(), true, {0, 0x8000ULL}, 2}, }; const unsigned NumGetZeroTests = 12; for (unsigned i = 0; i < NumGetZeroTests; ++i) { APFloat test = APFloat::getZero(*GetZeroTest[i].semantics, GetZeroTest[i].sign); const char *pattern = GetZeroTest[i].sign? "-0x0p+0" : "0x0p+0"; APFloat expected = APFloat(*GetZeroTest[i].semantics, pattern); EXPECT_TRUE(test.isZero()); EXPECT_TRUE(GetZeroTest[i].sign? test.isNegative() : !test.isNegative()); EXPECT_TRUE(test.bitwiseIsEqual(expected)); for (unsigned j = 0, je = GetZeroTest[i].bitPatternLength; j < je; ++j) { EXPECT_EQ(GetZeroTest[i].bitPattern[j], test.bitcastToAPInt().getRawData()[j]); } } } TEST(APFloatTest, copySign) { EXPECT_TRUE(APFloat(-42.0).bitwiseIsEqual( APFloat::copySign(APFloat(42.0), APFloat(-1.0)))); EXPECT_TRUE(APFloat(42.0).bitwiseIsEqual( APFloat::copySign(APFloat(-42.0), APFloat(1.0)))); EXPECT_TRUE(APFloat(-42.0).bitwiseIsEqual( APFloat::copySign(APFloat(-42.0), APFloat(-1.0)))); EXPECT_TRUE(APFloat(42.0).bitwiseIsEqual( APFloat::copySign(APFloat(42.0), APFloat(1.0)))); } TEST(APFloatTest, convert) { bool losesInfo; APFloat test(APFloat::IEEEdouble(), "1.0"); test.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_EQ(1.0f, test.convertToFloat()); EXPECT_FALSE(losesInfo); test = APFloat(APFloat::x87DoubleExtended(), "0x1p-53"); test.add(APFloat(APFloat::x87DoubleExtended(), "1.0"), APFloat::rmNearestTiesToEven); test.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_EQ(1.0, test.convertToDouble()); EXPECT_TRUE(losesInfo); test = APFloat(APFloat::IEEEquad(), "0x1p-53"); test.add(APFloat(APFloat::IEEEquad(), "1.0"), APFloat::rmNearestTiesToEven); test.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_EQ(1.0, test.convertToDouble()); EXPECT_TRUE(losesInfo); test = APFloat(APFloat::x87DoubleExtended(), "0xf.fffffffp+28"); test.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_EQ(4294967295.0, test.convertToDouble()); EXPECT_FALSE(losesInfo); test = APFloat::getSNaN(APFloat::IEEEsingle()); APFloat X87SNaN = APFloat::getSNaN(APFloat::x87DoubleExtended()); test.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_TRUE(test.bitwiseIsEqual(X87SNaN)); EXPECT_FALSE(losesInfo); test = APFloat::getQNaN(APFloat::IEEEsingle()); APFloat X87QNaN = APFloat::getQNaN(APFloat::x87DoubleExtended()); test.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_TRUE(test.bitwiseIsEqual(X87QNaN)); EXPECT_FALSE(losesInfo); test = APFloat::getSNaN(APFloat::x87DoubleExtended()); test.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_TRUE(test.bitwiseIsEqual(X87SNaN)); EXPECT_FALSE(losesInfo); test = APFloat::getQNaN(APFloat::x87DoubleExtended()); test.convert(APFloat::x87DoubleExtended(), APFloat::rmNearestTiesToEven, &losesInfo); EXPECT_TRUE(test.bitwiseIsEqual(X87QNaN)); EXPECT_FALSE(losesInfo); } TEST(APFloatTest, PPCDoubleDouble) { APFloat test(APFloat::PPCDoubleDouble(), "1.0"); EXPECT_EQ(0x3ff0000000000000ull, test.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0x0000000000000000ull, test.bitcastToAPInt().getRawData()[1]); // LDBL_MAX test = APFloat(APFloat::PPCDoubleDouble(), "1.79769313486231580793728971405301e+308"); EXPECT_EQ(0x7fefffffffffffffull, test.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0x7c8ffffffffffffeull, test.bitcastToAPInt().getRawData()[1]); // LDBL_MIN test = APFloat(APFloat::PPCDoubleDouble(), "2.00416836000897277799610805135016e-292"); EXPECT_EQ(0x0360000000000000ull, test.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0x0000000000000000ull, test.bitcastToAPInt().getRawData()[1]); // PR30869 { auto Result = APFloat(APFloat::PPCDoubleDouble(), "1.0") + APFloat(APFloat::PPCDoubleDouble(), "1.0"); EXPECT_EQ(&APFloat::PPCDoubleDouble(), &Result.getSemantics()); Result = APFloat(APFloat::PPCDoubleDouble(), "1.0") - APFloat(APFloat::PPCDoubleDouble(), "1.0"); EXPECT_EQ(&APFloat::PPCDoubleDouble(), &Result.getSemantics()); Result = APFloat(APFloat::PPCDoubleDouble(), "1.0") * APFloat(APFloat::PPCDoubleDouble(), "1.0"); EXPECT_EQ(&APFloat::PPCDoubleDouble(), &Result.getSemantics()); Result = APFloat(APFloat::PPCDoubleDouble(), "1.0") / APFloat(APFloat::PPCDoubleDouble(), "1.0"); EXPECT_EQ(&APFloat::PPCDoubleDouble(), &Result.getSemantics()); int Exp; Result = frexp(APFloat(APFloat::PPCDoubleDouble(), "1.0"), Exp, APFloat::rmNearestTiesToEven); EXPECT_EQ(&APFloat::PPCDoubleDouble(), &Result.getSemantics()); Result = scalbn(APFloat(APFloat::PPCDoubleDouble(), "1.0"), 1, APFloat::rmNearestTiesToEven); EXPECT_EQ(&APFloat::PPCDoubleDouble(), &Result.getSemantics()); } } TEST(APFloatTest, isNegative) { APFloat t(APFloat::IEEEsingle(), "0x1p+0"); EXPECT_FALSE(t.isNegative()); t = APFloat(APFloat::IEEEsingle(), "-0x1p+0"); EXPECT_TRUE(t.isNegative()); EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle(), false).isNegative()); EXPECT_TRUE(APFloat::getInf(APFloat::IEEEsingle(), true).isNegative()); EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle(), false).isNegative()); EXPECT_TRUE(APFloat::getZero(APFloat::IEEEsingle(), true).isNegative()); EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle(), false).isNegative()); EXPECT_TRUE(APFloat::getNaN(APFloat::IEEEsingle(), true).isNegative()); EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle(), false).isNegative()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle(), true).isNegative()); } TEST(APFloatTest, isNormal) { APFloat t(APFloat::IEEEsingle(), "0x1p+0"); EXPECT_TRUE(t.isNormal()); EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle(), false).isNormal()); EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle(), false).isNormal()); EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle(), false).isNormal()); EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle(), false).isNormal()); EXPECT_FALSE(APFloat(APFloat::IEEEsingle(), "0x1p-149").isNormal()); } TEST(APFloatTest, isFinite) { APFloat t(APFloat::IEEEsingle(), "0x1p+0"); EXPECT_TRUE(t.isFinite()); EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle(), false).isFinite()); EXPECT_TRUE(APFloat::getZero(APFloat::IEEEsingle(), false).isFinite()); EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle(), false).isFinite()); EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle(), false).isFinite()); EXPECT_TRUE(APFloat(APFloat::IEEEsingle(), "0x1p-149").isFinite()); } TEST(APFloatTest, isInfinity) { APFloat t(APFloat::IEEEsingle(), "0x1p+0"); EXPECT_FALSE(t.isInfinity()); EXPECT_TRUE(APFloat::getInf(APFloat::IEEEsingle(), false).isInfinity()); EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle(), false).isInfinity()); EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle(), false).isInfinity()); EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle(), false).isInfinity()); EXPECT_FALSE(APFloat(APFloat::IEEEsingle(), "0x1p-149").isInfinity()); } TEST(APFloatTest, isNaN) { APFloat t(APFloat::IEEEsingle(), "0x1p+0"); EXPECT_FALSE(t.isNaN()); EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle(), false).isNaN()); EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle(), false).isNaN()); EXPECT_TRUE(APFloat::getNaN(APFloat::IEEEsingle(), false).isNaN()); EXPECT_TRUE(APFloat::getSNaN(APFloat::IEEEsingle(), false).isNaN()); EXPECT_FALSE(APFloat(APFloat::IEEEsingle(), "0x1p-149").isNaN()); } TEST(APFloatTest, isFiniteNonZero) { // Test positive/negative normal value. EXPECT_TRUE(APFloat(APFloat::IEEEsingle(), "0x1p+0").isFiniteNonZero()); EXPECT_TRUE(APFloat(APFloat::IEEEsingle(), "-0x1p+0").isFiniteNonZero()); // Test positive/negative denormal value. EXPECT_TRUE(APFloat(APFloat::IEEEsingle(), "0x1p-149").isFiniteNonZero()); EXPECT_TRUE(APFloat(APFloat::IEEEsingle(), "-0x1p-149").isFiniteNonZero()); // Test +/- Infinity. EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle(), false).isFiniteNonZero()); EXPECT_FALSE(APFloat::getInf(APFloat::IEEEsingle(), true).isFiniteNonZero()); // Test +/- Zero. EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle(), false).isFiniteNonZero()); EXPECT_FALSE(APFloat::getZero(APFloat::IEEEsingle(), true).isFiniteNonZero()); // Test +/- qNaN. +/- dont mean anything with qNaN but paranoia can't hurt in // this instance. EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle(), false).isFiniteNonZero()); EXPECT_FALSE(APFloat::getNaN(APFloat::IEEEsingle(), true).isFiniteNonZero()); // Test +/- sNaN. +/- dont mean anything with sNaN but paranoia can't hurt in // this instance. EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle(), false).isFiniteNonZero()); EXPECT_FALSE(APFloat::getSNaN(APFloat::IEEEsingle(), true).isFiniteNonZero()); } TEST(APFloatTest, add) { // Test Special Cases against each other and normal values. // TODOS/NOTES: // 1. Since we perform only default exception handling all operations with // signaling NaNs should have a result that is a quiet NaN. Currently they // return sNaN. APFloat PInf = APFloat::getInf(APFloat::IEEEsingle(), false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle(), true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle(), false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle(), true); APFloat QNaN = APFloat::getNaN(APFloat::IEEEsingle(), false); APFloat SNaN = APFloat::getSNaN(APFloat::IEEEsingle(), false); APFloat PNormalValue = APFloat(APFloat::IEEEsingle(), "0x1p+0"); APFloat MNormalValue = APFloat(APFloat::IEEEsingle(), "-0x1p+0"); APFloat PLargestValue = APFloat::getLargest(APFloat::IEEEsingle(), false); APFloat MLargestValue = APFloat::getLargest(APFloat::IEEEsingle(), true); APFloat PSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle(), false); APFloat MSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle(), true); APFloat PSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), false); APFloat MSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), true); const int OverflowStatus = APFloat::opOverflow | APFloat::opInexact; const unsigned NumTests = 169; struct { APFloat x; APFloat y; const char *result; int status; int category; } SpecialCaseTests[NumTests] = { { PInf, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, PZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PInf, PNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MInf, PNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PZero, PNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PZero, MNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PZero, PLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PZero, MLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PZero, PSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PZero, MSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PZero, PSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PZero, MSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MZero, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MZero, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MZero, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MZero, PNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MZero, MNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MZero, PLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MZero, MLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MZero, PSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MZero, MSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MZero, PSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MZero, MSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { QNaN, PInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { QNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { QNaN, PNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { SNaN, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, QNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, PZero, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MZero, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PNormalValue, "0x1p+1", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, PSmallestValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MSmallestValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, PSmallestNormalized, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MSmallestNormalized, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, PZero, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MZero, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MNormalValue, PNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, MNormalValue, "-0x1p+1", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PSmallestValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MSmallestValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PSmallestNormalized, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MSmallestNormalized, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, PZero, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MZero, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PLargestValue, PNormalValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MNormalValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PLargestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, MLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, PSmallestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MSmallestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PSmallestNormalized, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MSmallestNormalized, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, PZero, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MZero, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MLargestValue, PNormalValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MNormalValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, MLargestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, PSmallestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MSmallestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PSmallestNormalized, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MSmallestNormalized, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, PZero, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MZero, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestValue, PNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, MNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PSmallestValue, "0x1p-148", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, PSmallestNormalized, "0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MSmallestNormalized, "-0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, PZero, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MZero, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestValue, PNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, MNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, PSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, MSmallestValue, "-0x1p-148", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PSmallestNormalized, "0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MSmallestNormalized, "-0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, PZero, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MZero, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestNormalized, PNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, MNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, PSmallestValue, "0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MSmallestValue, "0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PSmallestNormalized, "0x1p-125", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, PZero, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MZero, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestNormalized, PNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, MNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, PLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, MLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, PSmallestValue, "-0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MSmallestValue, "-0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, MSmallestNormalized, "-0x1p-125", APFloat::opOK, APFloat::fcNormal } }; for (size_t i = 0; i < NumTests; ++i) { APFloat x(SpecialCaseTests[i].x); APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.add(y, APFloat::rmNearestTiesToEven); APFloat result(APFloat::IEEEsingle(), SpecialCaseTests[i].result); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); EXPECT_TRUE((int)x.getCategory() == SpecialCaseTests[i].category); } } TEST(APFloatTest, subtract) { // Test Special Cases against each other and normal values. // TODOS/NOTES: // 1. Since we perform only default exception handling all operations with // signaling NaNs should have a result that is a quiet NaN. Currently they // return sNaN. APFloat PInf = APFloat::getInf(APFloat::IEEEsingle(), false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle(), true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle(), false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle(), true); APFloat QNaN = APFloat::getNaN(APFloat::IEEEsingle(), false); APFloat SNaN = APFloat::getSNaN(APFloat::IEEEsingle(), false); APFloat PNormalValue = APFloat(APFloat::IEEEsingle(), "0x1p+0"); APFloat MNormalValue = APFloat(APFloat::IEEEsingle(), "-0x1p+0"); APFloat PLargestValue = APFloat::getLargest(APFloat::IEEEsingle(), false); APFloat MLargestValue = APFloat::getLargest(APFloat::IEEEsingle(), true); APFloat PSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle(), false); APFloat MSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle(), true); APFloat PSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), false); APFloat MSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), true); const int OverflowStatus = APFloat::opOverflow | APFloat::opInexact; const unsigned NumTests = 169; struct { APFloat x; APFloat y; const char *result; int status; int category; } SpecialCaseTests[NumTests] = { { PInf, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PInf, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PInf, PNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, PZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MInf, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MInf, PNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PZero, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PZero, PNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PZero, MNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PZero, PLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PZero, MLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PZero, PSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PZero, MSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PZero, PSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PZero, MSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MZero, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MZero, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MZero, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MZero, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MZero, PNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MZero, MNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MZero, PLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MZero, MLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MZero, PSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MZero, MSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MZero, PSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MZero, MSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { QNaN, PInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { QNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { QNaN, PNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { SNaN, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, QNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, PZero, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MZero, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PNormalValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, MNormalValue, "0x1p+1", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, PSmallestValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MSmallestValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, PSmallestNormalized, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PNormalValue, MSmallestNormalized, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, PZero, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MZero, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MNormalValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MNormalValue, PNormalValue, "-0x1p+1", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PSmallestValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MSmallestValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, PSmallestNormalized, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MNormalValue, MSmallestNormalized, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, PZero, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MZero, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PLargestValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PLargestValue, PNormalValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MNormalValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, MLargestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, PSmallestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MSmallestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, PSmallestNormalized, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PLargestValue, MSmallestNormalized, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, PZero, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MZero, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MLargestValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MLargestValue, PNormalValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MNormalValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PLargestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, MLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, PSmallestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MSmallestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, PSmallestNormalized, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MLargestValue, MSmallestNormalized, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, PZero, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MZero, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestValue, PNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, MNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestValue, PSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, MSmallestValue, "0x1p-148", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PSmallestNormalized, "-0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MSmallestNormalized, "0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, PZero, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MZero, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestValue, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestValue, PNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, MNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestValue, PSmallestValue, "-0x1p-148", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, PSmallestNormalized, "-0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MSmallestNormalized, "0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, PZero, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MZero, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestNormalized, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestNormalized, PNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, MNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { PSmallestNormalized, PSmallestValue, "0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MSmallestValue, "0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestNormalized, MSmallestNormalized, "0x1p-125", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, PZero, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MZero, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, QNaN, "-nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestNormalized, SNaN, "-nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestNormalized, PNormalValue, "-0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, MNormalValue, "0x1p+0", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, PLargestValue, "-0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, MLargestValue, "0x1.fffffep+127", APFloat::opInexact, APFloat::fcNormal }, { MSmallestNormalized, PSmallestValue, "-0x1.000002p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MSmallestValue, "-0x1.fffffcp-127", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PSmallestNormalized, "-0x1p-125", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero } }; for (size_t i = 0; i < NumTests; ++i) { APFloat x(SpecialCaseTests[i].x); APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.subtract(y, APFloat::rmNearestTiesToEven); APFloat result(APFloat::IEEEsingle(), SpecialCaseTests[i].result); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); EXPECT_TRUE((int)x.getCategory() == SpecialCaseTests[i].category); } } TEST(APFloatTest, multiply) { // Test Special Cases against each other and normal values. // TODOS/NOTES: // 1. Since we perform only default exception handling all operations with // signaling NaNs should have a result that is a quiet NaN. Currently they // return sNaN. APFloat PInf = APFloat::getInf(APFloat::IEEEsingle(), false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle(), true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle(), false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle(), true); APFloat QNaN = APFloat::getNaN(APFloat::IEEEsingle(), false); APFloat SNaN = APFloat::getSNaN(APFloat::IEEEsingle(), false); APFloat PNormalValue = APFloat(APFloat::IEEEsingle(), "0x1p+0"); APFloat MNormalValue = APFloat(APFloat::IEEEsingle(), "-0x1p+0"); APFloat PLargestValue = APFloat::getLargest(APFloat::IEEEsingle(), false); APFloat MLargestValue = APFloat::getLargest(APFloat::IEEEsingle(), true); APFloat PSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle(), false); APFloat MSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle(), true); APFloat PSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), false); APFloat MSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), true); APFloat MaxQuad(APFloat::IEEEquad(), "0x1.ffffffffffffffffffffffffffffp+16383"); APFloat MinQuad(APFloat::IEEEquad(), "0x0.0000000000000000000000000001p-16382"); APFloat NMinQuad(APFloat::IEEEquad(), "-0x0.0000000000000000000000000001p-16382"); const int OverflowStatus = APFloat::opOverflow | APFloat::opInexact; const int UnderflowStatus = APFloat::opUnderflow | APFloat::opInexact; struct { APFloat x; APFloat y; const char *result; int status; int category; APFloat::roundingMode roundingMode = APFloat::rmNearestTiesToEven; } SpecialCaseTests[] = { { PInf, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PInf, PNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MInf, PNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PZero, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PZero, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PZero, PNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MNormalValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MLargestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MSmallestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MSmallestNormalized, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MZero, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MZero, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MZero, PNormalValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PLargestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PSmallestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PSmallestNormalized, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { QNaN, PInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { QNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { QNaN, PNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { SNaN, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, QNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PNormalValue, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, PLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, PSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, PSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MNormalValue, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MNormalValue, PNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PLargestValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MLargestValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PSmallestValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MSmallestValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PSmallestNormalized, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MSmallestNormalized, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PLargestValue, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PLargestValue, PNormalValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MNormalValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PLargestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, MLargestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, PSmallestValue, "0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MSmallestValue, "-0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PSmallestNormalized, "0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MSmallestNormalized, "-0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MLargestValue, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MLargestValue, PNormalValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MNormalValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, PLargestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, MLargestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, PSmallestValue, "-0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MSmallestValue, "0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, PSmallestNormalized, "-0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MSmallestNormalized, "0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestValue, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestValue, PNormalValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MNormalValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PLargestValue, "0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MLargestValue, "-0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PSmallestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestValue, MSmallestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestValue, PSmallestNormalized, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestValue, MSmallestNormalized, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestValue, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestValue, PNormalValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MNormalValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PLargestValue, "-0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MLargestValue, "0x1.fffffep-22", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PSmallestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, MSmallestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, PSmallestNormalized, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, MSmallestNormalized, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, PInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, MInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PSmallestNormalized, PZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestNormalized, MZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestNormalized, PNormalValue, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MNormalValue, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PLargestValue, "0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MLargestValue, "-0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PSmallestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, MSmallestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, PSmallestNormalized, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, MSmallestNormalized, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, PInf, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, MInf, "inf", APFloat::opOK, APFloat::fcInfinity }, { MSmallestNormalized, PZero, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, MZero, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestNormalized, PNormalValue, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MNormalValue, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PLargestValue, "-0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MLargestValue, "0x1.fffffep+1", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PSmallestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, MSmallestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, PSmallestNormalized, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, MSmallestNormalized, "0x0p+0", UnderflowStatus, APFloat::fcZero }, {MaxQuad, MinQuad, "0x1.ffffffffffffffffffffffffffffp-111", APFloat::opOK, APFloat::fcNormal, APFloat::rmNearestTiesToEven}, {MaxQuad, MinQuad, "0x1.ffffffffffffffffffffffffffffp-111", APFloat::opOK, APFloat::fcNormal, APFloat::rmTowardPositive}, {MaxQuad, MinQuad, "0x1.ffffffffffffffffffffffffffffp-111", APFloat::opOK, APFloat::fcNormal, APFloat::rmTowardNegative}, {MaxQuad, MinQuad, "0x1.ffffffffffffffffffffffffffffp-111", APFloat::opOK, APFloat::fcNormal, APFloat::rmTowardZero}, {MaxQuad, MinQuad, "0x1.ffffffffffffffffffffffffffffp-111", APFloat::opOK, APFloat::fcNormal, APFloat::rmNearestTiesToAway}, {MaxQuad, NMinQuad, "-0x1.ffffffffffffffffffffffffffffp-111", APFloat::opOK, APFloat::fcNormal, APFloat::rmNearestTiesToEven}, {MaxQuad, NMinQuad, "-0x1.ffffffffffffffffffffffffffffp-111", APFloat::opOK, APFloat::fcNormal, APFloat::rmTowardPositive}, {MaxQuad, NMinQuad, "-0x1.ffffffffffffffffffffffffffffp-111", APFloat::opOK, APFloat::fcNormal, APFloat::rmTowardNegative}, {MaxQuad, NMinQuad, "-0x1.ffffffffffffffffffffffffffffp-111", APFloat::opOK, APFloat::fcNormal, APFloat::rmTowardZero}, {MaxQuad, NMinQuad, "-0x1.ffffffffffffffffffffffffffffp-111", APFloat::opOK, APFloat::fcNormal, APFloat::rmNearestTiesToAway}, {MaxQuad, MaxQuad, "inf", OverflowStatus, APFloat::fcInfinity, APFloat::rmNearestTiesToEven}, {MaxQuad, MaxQuad, "inf", OverflowStatus, APFloat::fcInfinity, APFloat::rmTowardPositive}, {MaxQuad, MaxQuad, "0x1.ffffffffffffffffffffffffffffp+16383", APFloat::opInexact, APFloat::fcNormal, APFloat::rmTowardNegative}, {MaxQuad, MaxQuad, "0x1.ffffffffffffffffffffffffffffp+16383", APFloat::opInexact, APFloat::fcNormal, APFloat::rmTowardZero}, {MaxQuad, MaxQuad, "inf", OverflowStatus, APFloat::fcInfinity, APFloat::rmNearestTiesToAway}, {MinQuad, MinQuad, "0", UnderflowStatus, APFloat::fcZero, APFloat::rmNearestTiesToEven}, {MinQuad, MinQuad, "0x0.0000000000000000000000000001p-16382", UnderflowStatus, APFloat::fcNormal, APFloat::rmTowardPositive}, {MinQuad, MinQuad, "0", UnderflowStatus, APFloat::fcZero, APFloat::rmTowardNegative}, {MinQuad, MinQuad, "0", UnderflowStatus, APFloat::fcZero, APFloat::rmTowardZero}, {MinQuad, MinQuad, "0", UnderflowStatus, APFloat::fcZero, APFloat::rmNearestTiesToAway}, {MinQuad, NMinQuad, "-0", UnderflowStatus, APFloat::fcZero, APFloat::rmNearestTiesToEven}, {MinQuad, NMinQuad, "-0", UnderflowStatus, APFloat::fcZero, APFloat::rmTowardPositive}, {MinQuad, NMinQuad, "-0x0.0000000000000000000000000001p-16382", UnderflowStatus, APFloat::fcNormal, APFloat::rmTowardNegative}, {MinQuad, NMinQuad, "-0", UnderflowStatus, APFloat::fcZero, APFloat::rmTowardZero}, {MinQuad, NMinQuad, "-0", UnderflowStatus, APFloat::fcZero, APFloat::rmNearestTiesToAway}, }; for (size_t i = 0; i < array_lengthof(SpecialCaseTests); ++i) { APFloat x(SpecialCaseTests[i].x); APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.multiply(y, SpecialCaseTests[i].roundingMode); APFloat result(x.getSemantics(), SpecialCaseTests[i].result); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); EXPECT_TRUE((int)x.getCategory() == SpecialCaseTests[i].category); } } TEST(APFloatTest, divide) { // Test Special Cases against each other and normal values. // TODOS/NOTES: // 1. Since we perform only default exception handling all operations with // signaling NaNs should have a result that is a quiet NaN. Currently they // return sNaN. APFloat PInf = APFloat::getInf(APFloat::IEEEsingle(), false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle(), true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle(), false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle(), true); APFloat QNaN = APFloat::getNaN(APFloat::IEEEsingle(), false); APFloat SNaN = APFloat::getSNaN(APFloat::IEEEsingle(), false); APFloat PNormalValue = APFloat(APFloat::IEEEsingle(), "0x1p+0"); APFloat MNormalValue = APFloat(APFloat::IEEEsingle(), "-0x1p+0"); APFloat PLargestValue = APFloat::getLargest(APFloat::IEEEsingle(), false); APFloat MLargestValue = APFloat::getLargest(APFloat::IEEEsingle(), true); APFloat PSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle(), false); APFloat MSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle(), true); APFloat PSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), false); APFloat MSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), true); APFloat MaxQuad(APFloat::IEEEquad(), "0x1.ffffffffffffffffffffffffffffp+16383"); APFloat MinQuad(APFloat::IEEEquad(), "0x0.0000000000000000000000000001p-16382"); APFloat NMinQuad(APFloat::IEEEquad(), "-0x0.0000000000000000000000000001p-16382"); const int OverflowStatus = APFloat::opOverflow | APFloat::opInexact; const int UnderflowStatus = APFloat::opUnderflow | APFloat::opInexact; struct { APFloat x; APFloat y; const char *result; int status; int category; APFloat::roundingMode roundingMode = APFloat::rmNearestTiesToEven; } SpecialCaseTests[] = { { PInf, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PInf, PZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PInf, PNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, PSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PInf, MSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MInf, PZero, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MZero, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MInf, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MInf, PNormalValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MNormalValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PLargestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MLargestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestValue, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestValue, "inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, PSmallestNormalized, "-inf", APFloat::opOK, APFloat::fcInfinity }, { MInf, MSmallestNormalized, "inf", APFloat::opOK, APFloat::fcInfinity }, { PZero, PInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PZero, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { PZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PZero, PNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MNormalValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MLargestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MSmallestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, PSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PZero, MSmallestNormalized, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MZero, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { MZero, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MZero, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MZero, PNormalValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MNormalValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PLargestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MLargestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PSmallestValue, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MSmallestValue, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, PSmallestNormalized, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MZero, MSmallestNormalized, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { QNaN, PInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MInf, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MZero, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { QNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { QNaN, PNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MNormalValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MLargestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestValue, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, PSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, { QNaN, MSmallestNormalized, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { SNaN, PInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MInf, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MZero, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, QNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MNormalValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MLargestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestValue, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, PSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, { SNaN, MSmallestNormalized, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, MInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PNormalValue, PZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PNormalValue, MZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PNormalValue, PNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, PLargestValue, "0x1p-128", UnderflowStatus, APFloat::fcNormal }, { PNormalValue, MLargestValue, "-0x1p-128", UnderflowStatus, APFloat::fcNormal }, { PNormalValue, PSmallestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { PNormalValue, MSmallestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { PNormalValue, PSmallestNormalized, "0x1p+126", APFloat::opOK, APFloat::fcNormal }, { PNormalValue, MSmallestNormalized, "-0x1p+126", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, MInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MNormalValue, PZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MNormalValue, MZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MNormalValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MNormalValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MNormalValue, PNormalValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MNormalValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, PLargestValue, "-0x1p-128", UnderflowStatus, APFloat::fcNormal }, { MNormalValue, MLargestValue, "0x1p-128", UnderflowStatus, APFloat::fcNormal }, { MNormalValue, PSmallestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { MNormalValue, MSmallestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { MNormalValue, PSmallestNormalized, "-0x1p+126", APFloat::opOK, APFloat::fcNormal }, { MNormalValue, MSmallestNormalized, "0x1p+126", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, MInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PLargestValue, PZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PLargestValue, MZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PLargestValue, PNormalValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MNormalValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PLargestValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, MLargestValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PLargestValue, PSmallestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, MSmallestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, PSmallestNormalized, "inf", OverflowStatus, APFloat::fcInfinity }, { PLargestValue, MSmallestNormalized, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, PInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, MInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MLargestValue, PZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MLargestValue, MZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MLargestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MLargestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MLargestValue, PNormalValue, "-0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MNormalValue, "0x1.fffffep+127", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, PLargestValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, MLargestValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MLargestValue, PSmallestValue, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, MSmallestValue, "inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, PSmallestNormalized, "-inf", OverflowStatus, APFloat::fcInfinity }, { MLargestValue, MSmallestNormalized, "inf", OverflowStatus, APFloat::fcInfinity }, { PSmallestValue, PInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, MInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestValue, PZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PSmallestValue, MZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestValue, PNormalValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MNormalValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PLargestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestValue, MLargestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestValue, PSmallestValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MSmallestValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, PSmallestNormalized, "0x1p-23", APFloat::opOK, APFloat::fcNormal }, { PSmallestValue, MSmallestNormalized, "-0x1p-23", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, MInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestValue, PZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MSmallestValue, MZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MSmallestValue, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestValue, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestValue, PNormalValue, "-0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MNormalValue, "0x1p-149", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PLargestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, MLargestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestValue, PSmallestValue, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MSmallestValue, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, PSmallestNormalized, "-0x1p-23", APFloat::opOK, APFloat::fcNormal }, { MSmallestValue, MSmallestNormalized, "0x1p-23", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestNormalized, MInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { PSmallestNormalized, PZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PSmallestNormalized, MZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { PSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { PSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { PSmallestNormalized, PNormalValue, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MNormalValue, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PLargestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, MLargestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { PSmallestNormalized, PSmallestValue, "0x1p+23", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MSmallestValue, "-0x1p+23", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, PSmallestNormalized, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, { PSmallestNormalized, MSmallestNormalized, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PInf, "-0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, MInf, "0x0p+0", APFloat::opOK, APFloat::fcZero }, { MSmallestNormalized, PZero, "-inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MSmallestNormalized, MZero, "inf", APFloat::opDivByZero, APFloat::fcInfinity }, { MSmallestNormalized, QNaN, "nan", APFloat::opOK, APFloat::fcNaN }, #if 0 // See Note 1. { MSmallestNormalized, SNaN, "nan", APFloat::opInvalidOp, APFloat::fcNaN }, #endif { MSmallestNormalized, PNormalValue, "-0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MNormalValue, "0x1p-126", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PLargestValue, "-0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, MLargestValue, "0x0p+0", UnderflowStatus, APFloat::fcZero }, { MSmallestNormalized, PSmallestValue, "-0x1p+23", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MSmallestValue, "0x1p+23", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, PSmallestNormalized, "-0x1p+0", APFloat::opOK, APFloat::fcNormal }, { MSmallestNormalized, MSmallestNormalized, "0x1p+0", APFloat::opOK, APFloat::fcNormal }, {MaxQuad, NMinQuad, "-inf", OverflowStatus, APFloat::fcInfinity, APFloat::rmNearestTiesToEven}, {MaxQuad, NMinQuad, "-0x1.ffffffffffffffffffffffffffffp+16383", APFloat::opInexact, APFloat::fcNormal, APFloat::rmTowardPositive}, {MaxQuad, NMinQuad, "-inf", OverflowStatus, APFloat::fcInfinity, APFloat::rmTowardNegative}, {MaxQuad, NMinQuad, "-0x1.ffffffffffffffffffffffffffffp+16383", APFloat::opInexact, APFloat::fcNormal, APFloat::rmTowardZero}, {MaxQuad, NMinQuad, "-inf", OverflowStatus, APFloat::fcInfinity, APFloat::rmNearestTiesToAway}, {MinQuad, MaxQuad, "0", UnderflowStatus, APFloat::fcZero, APFloat::rmNearestTiesToEven}, {MinQuad, MaxQuad, "0x0.0000000000000000000000000001p-16382", UnderflowStatus, APFloat::fcNormal, APFloat::rmTowardPositive}, {MinQuad, MaxQuad, "0", UnderflowStatus, APFloat::fcZero, APFloat::rmTowardNegative}, {MinQuad, MaxQuad, "0", UnderflowStatus, APFloat::fcZero, APFloat::rmTowardZero}, {MinQuad, MaxQuad, "0", UnderflowStatus, APFloat::fcZero, APFloat::rmNearestTiesToAway}, {NMinQuad, MaxQuad, "-0", UnderflowStatus, APFloat::fcZero, APFloat::rmNearestTiesToEven}, {NMinQuad, MaxQuad, "-0", UnderflowStatus, APFloat::fcZero, APFloat::rmTowardPositive}, {NMinQuad, MaxQuad, "-0x0.0000000000000000000000000001p-16382", UnderflowStatus, APFloat::fcNormal, APFloat::rmTowardNegative}, {NMinQuad, MaxQuad, "-0", UnderflowStatus, APFloat::fcZero, APFloat::rmTowardZero}, {NMinQuad, MaxQuad, "-0", UnderflowStatus, APFloat::fcZero, APFloat::rmNearestTiesToAway}, }; for (size_t i = 0; i < array_lengthof(SpecialCaseTests); ++i) { APFloat x(SpecialCaseTests[i].x); APFloat y(SpecialCaseTests[i].y); APFloat::opStatus status = x.divide(y, SpecialCaseTests[i].roundingMode); APFloat result(x.getSemantics(), SpecialCaseTests[i].result); EXPECT_TRUE(result.bitwiseIsEqual(x)); EXPECT_TRUE((int)status == SpecialCaseTests[i].status); EXPECT_TRUE((int)x.getCategory() == SpecialCaseTests[i].category); } } TEST(APFloatTest, operatorOverloads) { // This is mostly testing that these operator overloads compile. APFloat One = APFloat(APFloat::IEEEsingle(), "0x1p+0"); APFloat Two = APFloat(APFloat::IEEEsingle(), "0x2p+0"); EXPECT_TRUE(Two.bitwiseIsEqual(One + One)); EXPECT_TRUE(One.bitwiseIsEqual(Two - One)); EXPECT_TRUE(Two.bitwiseIsEqual(One * Two)); EXPECT_TRUE(One.bitwiseIsEqual(Two / Two)); } TEST(APFloatTest, abs) { APFloat PInf = APFloat::getInf(APFloat::IEEEsingle(), false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle(), true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle(), false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle(), true); APFloat PQNaN = APFloat::getNaN(APFloat::IEEEsingle(), false); APFloat MQNaN = APFloat::getNaN(APFloat::IEEEsingle(), true); APFloat PSNaN = APFloat::getSNaN(APFloat::IEEEsingle(), false); APFloat MSNaN = APFloat::getSNaN(APFloat::IEEEsingle(), true); APFloat PNormalValue = APFloat(APFloat::IEEEsingle(), "0x1p+0"); APFloat MNormalValue = APFloat(APFloat::IEEEsingle(), "-0x1p+0"); APFloat PLargestValue = APFloat::getLargest(APFloat::IEEEsingle(), false); APFloat MLargestValue = APFloat::getLargest(APFloat::IEEEsingle(), true); APFloat PSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle(), false); APFloat MSmallestValue = APFloat::getSmallest(APFloat::IEEEsingle(), true); APFloat PSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), false); APFloat MSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEsingle(), true); EXPECT_TRUE(PInf.bitwiseIsEqual(abs(PInf))); EXPECT_TRUE(PInf.bitwiseIsEqual(abs(MInf))); EXPECT_TRUE(PZero.bitwiseIsEqual(abs(PZero))); EXPECT_TRUE(PZero.bitwiseIsEqual(abs(MZero))); EXPECT_TRUE(PQNaN.bitwiseIsEqual(abs(PQNaN))); EXPECT_TRUE(PQNaN.bitwiseIsEqual(abs(MQNaN))); EXPECT_TRUE(PSNaN.bitwiseIsEqual(abs(PSNaN))); EXPECT_TRUE(PSNaN.bitwiseIsEqual(abs(MSNaN))); EXPECT_TRUE(PNormalValue.bitwiseIsEqual(abs(PNormalValue))); EXPECT_TRUE(PNormalValue.bitwiseIsEqual(abs(MNormalValue))); EXPECT_TRUE(PLargestValue.bitwiseIsEqual(abs(PLargestValue))); EXPECT_TRUE(PLargestValue.bitwiseIsEqual(abs(MLargestValue))); EXPECT_TRUE(PSmallestValue.bitwiseIsEqual(abs(PSmallestValue))); EXPECT_TRUE(PSmallestValue.bitwiseIsEqual(abs(MSmallestValue))); EXPECT_TRUE(PSmallestNormalized.bitwiseIsEqual(abs(PSmallestNormalized))); EXPECT_TRUE(PSmallestNormalized.bitwiseIsEqual(abs(MSmallestNormalized))); } TEST(APFloatTest, neg) { APFloat One = APFloat(APFloat::IEEEsingle(), "1.0"); APFloat NegOne = APFloat(APFloat::IEEEsingle(), "-1.0"); APFloat Zero = APFloat::getZero(APFloat::IEEEsingle(), false); APFloat NegZero = APFloat::getZero(APFloat::IEEEsingle(), true); APFloat Inf = APFloat::getInf(APFloat::IEEEsingle(), false); APFloat NegInf = APFloat::getInf(APFloat::IEEEsingle(), true); APFloat QNaN = APFloat::getNaN(APFloat::IEEEsingle(), false); APFloat NegQNaN = APFloat::getNaN(APFloat::IEEEsingle(), true); EXPECT_TRUE(NegOne.bitwiseIsEqual(neg(One))); EXPECT_TRUE(One.bitwiseIsEqual(neg(NegOne))); EXPECT_TRUE(NegZero.bitwiseIsEqual(neg(Zero))); EXPECT_TRUE(Zero.bitwiseIsEqual(neg(NegZero))); EXPECT_TRUE(NegInf.bitwiseIsEqual(neg(Inf))); EXPECT_TRUE(Inf.bitwiseIsEqual(neg(NegInf))); EXPECT_TRUE(NegInf.bitwiseIsEqual(neg(Inf))); EXPECT_TRUE(Inf.bitwiseIsEqual(neg(NegInf))); EXPECT_TRUE(NegQNaN.bitwiseIsEqual(neg(QNaN))); EXPECT_TRUE(QNaN.bitwiseIsEqual(neg(NegQNaN))); } TEST(APFloatTest, ilogb) { EXPECT_EQ(-1074, ilogb(APFloat::getSmallest(APFloat::IEEEdouble(), false))); EXPECT_EQ(-1074, ilogb(APFloat::getSmallest(APFloat::IEEEdouble(), true))); EXPECT_EQ(-1023, ilogb(APFloat(APFloat::IEEEdouble(), "0x1.ffffffffffffep-1024"))); EXPECT_EQ(-1023, ilogb(APFloat(APFloat::IEEEdouble(), "0x1.ffffffffffffep-1023"))); EXPECT_EQ(-1023, ilogb(APFloat(APFloat::IEEEdouble(), "-0x1.ffffffffffffep-1023"))); EXPECT_EQ(-51, ilogb(APFloat(APFloat::IEEEdouble(), "0x1p-51"))); EXPECT_EQ(-1023, ilogb(APFloat(APFloat::IEEEdouble(), "0x1.c60f120d9f87cp-1023"))); EXPECT_EQ(-2, ilogb(APFloat(APFloat::IEEEdouble(), "0x0.ffffp-1"))); EXPECT_EQ(-1023, ilogb(APFloat(APFloat::IEEEdouble(), "0x1.fffep-1023"))); EXPECT_EQ(1023, ilogb(APFloat::getLargest(APFloat::IEEEdouble(), false))); EXPECT_EQ(1023, ilogb(APFloat::getLargest(APFloat::IEEEdouble(), true))); EXPECT_EQ(0, ilogb(APFloat(APFloat::IEEEsingle(), "0x1p+0"))); EXPECT_EQ(0, ilogb(APFloat(APFloat::IEEEsingle(), "-0x1p+0"))); EXPECT_EQ(42, ilogb(APFloat(APFloat::IEEEsingle(), "0x1p+42"))); EXPECT_EQ(-42, ilogb(APFloat(APFloat::IEEEsingle(), "0x1p-42"))); EXPECT_EQ(APFloat::IEK_Inf, ilogb(APFloat::getInf(APFloat::IEEEsingle(), false))); EXPECT_EQ(APFloat::IEK_Inf, ilogb(APFloat::getInf(APFloat::IEEEsingle(), true))); EXPECT_EQ(APFloat::IEK_Zero, ilogb(APFloat::getZero(APFloat::IEEEsingle(), false))); EXPECT_EQ(APFloat::IEK_Zero, ilogb(APFloat::getZero(APFloat::IEEEsingle(), true))); EXPECT_EQ(APFloat::IEK_NaN, ilogb(APFloat::getNaN(APFloat::IEEEsingle(), false))); EXPECT_EQ(APFloat::IEK_NaN, ilogb(APFloat::getSNaN(APFloat::IEEEsingle(), false))); EXPECT_EQ(127, ilogb(APFloat::getLargest(APFloat::IEEEsingle(), false))); EXPECT_EQ(127, ilogb(APFloat::getLargest(APFloat::IEEEsingle(), true))); EXPECT_EQ(-149, ilogb(APFloat::getSmallest(APFloat::IEEEsingle(), false))); EXPECT_EQ(-149, ilogb(APFloat::getSmallest(APFloat::IEEEsingle(), true))); EXPECT_EQ(-126, ilogb(APFloat::getSmallestNormalized(APFloat::IEEEsingle(), false))); EXPECT_EQ(-126, ilogb(APFloat::getSmallestNormalized(APFloat::IEEEsingle(), true))); } TEST(APFloatTest, scalbn) { const APFloat::roundingMode RM = APFloat::rmNearestTiesToEven; EXPECT_TRUE( APFloat(APFloat::IEEEsingle(), "0x1p+0") .bitwiseIsEqual(scalbn(APFloat(APFloat::IEEEsingle(), "0x1p+0"), 0, RM))); EXPECT_TRUE( APFloat(APFloat::IEEEsingle(), "0x1p+42") .bitwiseIsEqual(scalbn(APFloat(APFloat::IEEEsingle(), "0x1p+0"), 42, RM))); EXPECT_TRUE( APFloat(APFloat::IEEEsingle(), "0x1p-42") .bitwiseIsEqual(scalbn(APFloat(APFloat::IEEEsingle(), "0x1p+0"), -42, RM))); APFloat PInf = APFloat::getInf(APFloat::IEEEsingle(), false); APFloat MInf = APFloat::getInf(APFloat::IEEEsingle(), true); APFloat PZero = APFloat::getZero(APFloat::IEEEsingle(), false); APFloat MZero = APFloat::getZero(APFloat::IEEEsingle(), true); APFloat QPNaN = APFloat::getNaN(APFloat::IEEEsingle(), false); APFloat QMNaN = APFloat::getNaN(APFloat::IEEEsingle(), true); APFloat SNaN = APFloat::getSNaN(APFloat::IEEEsingle(), false); EXPECT_TRUE(PInf.bitwiseIsEqual(scalbn(PInf, 0, RM))); EXPECT_TRUE(MInf.bitwiseIsEqual(scalbn(MInf, 0, RM))); EXPECT_TRUE(PZero.bitwiseIsEqual(scalbn(PZero, 0, RM))); EXPECT_TRUE(MZero.bitwiseIsEqual(scalbn(MZero, 0, RM))); EXPECT_TRUE(QPNaN.bitwiseIsEqual(scalbn(QPNaN, 0, RM))); EXPECT_TRUE(QMNaN.bitwiseIsEqual(scalbn(QMNaN, 0, RM))); EXPECT_FALSE(scalbn(SNaN, 0, RM).isSignaling()); APFloat ScalbnSNaN = scalbn(SNaN, 1, RM); EXPECT_TRUE(ScalbnSNaN.isNaN() && !ScalbnSNaN.isSignaling()); // Make sure highest bit of payload is preserved. const APInt Payload(64, (UINT64_C(1) << 50) | (UINT64_C(1) << 49) | (UINT64_C(1234) << 32) | 1); APFloat SNaNWithPayload = APFloat::getSNaN(APFloat::IEEEdouble(), false, &Payload); APFloat QuietPayload = scalbn(SNaNWithPayload, 1, RM); EXPECT_TRUE(QuietPayload.isNaN() && !QuietPayload.isSignaling()); EXPECT_EQ(Payload, QuietPayload.bitcastToAPInt().getLoBits(51)); EXPECT_TRUE(PInf.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle(), "0x1p+0"), 128, RM))); EXPECT_TRUE(MInf.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle(), "-0x1p+0"), 128, RM))); EXPECT_TRUE(PInf.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle(), "0x1p+127"), 1, RM))); EXPECT_TRUE(PZero.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle(), "0x1p-127"), -127, RM))); EXPECT_TRUE(MZero.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle(), "-0x1p-127"), -127, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEsingle(), "-0x1p-149").bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle(), "-0x1p-127"), -22, RM))); EXPECT_TRUE(PZero.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEsingle(), "0x1p-126"), -24, RM))); APFloat SmallestF64 = APFloat::getSmallest(APFloat::IEEEdouble(), false); APFloat NegSmallestF64 = APFloat::getSmallest(APFloat::IEEEdouble(), true); APFloat LargestF64 = APFloat::getLargest(APFloat::IEEEdouble(), false); APFloat NegLargestF64 = APFloat::getLargest(APFloat::IEEEdouble(), true); APFloat SmallestNormalizedF64 = APFloat::getSmallestNormalized(APFloat::IEEEdouble(), false); APFloat NegSmallestNormalizedF64 = APFloat::getSmallestNormalized(APFloat::IEEEdouble(), true); APFloat LargestDenormalF64(APFloat::IEEEdouble(), "0x1.ffffffffffffep-1023"); APFloat NegLargestDenormalF64(APFloat::IEEEdouble(), "-0x1.ffffffffffffep-1023"); EXPECT_TRUE(SmallestF64.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEdouble(), "0x1p-1074"), 0, RM))); EXPECT_TRUE(NegSmallestF64.bitwiseIsEqual( scalbn(APFloat(APFloat::IEEEdouble(), "-0x1p-1074"), 0, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1p+1023") .bitwiseIsEqual(scalbn(SmallestF64, 2097, RM))); EXPECT_TRUE(scalbn(SmallestF64, -2097, RM).isPosZero()); EXPECT_TRUE(scalbn(SmallestF64, -2098, RM).isPosZero()); EXPECT_TRUE(scalbn(SmallestF64, -2099, RM).isPosZero()); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1p+1022") .bitwiseIsEqual(scalbn(SmallestF64, 2096, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1p+1023") .bitwiseIsEqual(scalbn(SmallestF64, 2097, RM))); EXPECT_TRUE(scalbn(SmallestF64, 2098, RM).isInfinity()); EXPECT_TRUE(scalbn(SmallestF64, 2099, RM).isInfinity()); // Test for integer overflows when adding to exponent. EXPECT_TRUE(scalbn(SmallestF64, -INT_MAX, RM).isPosZero()); EXPECT_TRUE(scalbn(LargestF64, INT_MAX, RM).isInfinity()); EXPECT_TRUE(LargestDenormalF64 .bitwiseIsEqual(scalbn(LargestDenormalF64, 0, RM))); EXPECT_TRUE(NegLargestDenormalF64 .bitwiseIsEqual(scalbn(NegLargestDenormalF64, 0, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.ffffffffffffep-1022") .bitwiseIsEqual(scalbn(LargestDenormalF64, 1, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "-0x1.ffffffffffffep-1021") .bitwiseIsEqual(scalbn(NegLargestDenormalF64, 2, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.ffffffffffffep+1") .bitwiseIsEqual(scalbn(LargestDenormalF64, 1024, RM))); EXPECT_TRUE(scalbn(LargestDenormalF64, -1023, RM).isPosZero()); EXPECT_TRUE(scalbn(LargestDenormalF64, -1024, RM).isPosZero()); EXPECT_TRUE(scalbn(LargestDenormalF64, -2048, RM).isPosZero()); EXPECT_TRUE(scalbn(LargestDenormalF64, 2047, RM).isInfinity()); EXPECT_TRUE(scalbn(LargestDenormalF64, 2098, RM).isInfinity()); EXPECT_TRUE(scalbn(LargestDenormalF64, 2099, RM).isInfinity()); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.ffffffffffffep-2") .bitwiseIsEqual(scalbn(LargestDenormalF64, 1021, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.ffffffffffffep-1") .bitwiseIsEqual(scalbn(LargestDenormalF64, 1022, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.ffffffffffffep+0") .bitwiseIsEqual(scalbn(LargestDenormalF64, 1023, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.ffffffffffffep+1023") .bitwiseIsEqual(scalbn(LargestDenormalF64, 2046, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1p+974") .bitwiseIsEqual(scalbn(SmallestF64, 2048, RM))); APFloat RandomDenormalF64(APFloat::IEEEdouble(), "0x1.c60f120d9f87cp+51"); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.c60f120d9f87cp-972") .bitwiseIsEqual(scalbn(RandomDenormalF64, -1023, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.c60f120d9f87cp-1") .bitwiseIsEqual(scalbn(RandomDenormalF64, -52, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.c60f120d9f87cp-2") .bitwiseIsEqual(scalbn(RandomDenormalF64, -53, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.c60f120d9f87cp+0") .bitwiseIsEqual(scalbn(RandomDenormalF64, -51, RM))); EXPECT_TRUE(scalbn(RandomDenormalF64, -2097, RM).isPosZero()); EXPECT_TRUE(scalbn(RandomDenormalF64, -2090, RM).isPosZero()); EXPECT_TRUE( APFloat(APFloat::IEEEdouble(), "-0x1p-1073") .bitwiseIsEqual(scalbn(NegLargestF64, -2097, RM))); EXPECT_TRUE( APFloat(APFloat::IEEEdouble(), "-0x1p-1024") .bitwiseIsEqual(scalbn(NegLargestF64, -2048, RM))); EXPECT_TRUE( APFloat(APFloat::IEEEdouble(), "0x1p-1073") .bitwiseIsEqual(scalbn(LargestF64, -2097, RM))); EXPECT_TRUE( APFloat(APFloat::IEEEdouble(), "0x1p-1074") .bitwiseIsEqual(scalbn(LargestF64, -2098, RM))); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "-0x1p-1074") .bitwiseIsEqual(scalbn(NegLargestF64, -2098, RM))); EXPECT_TRUE(scalbn(NegLargestF64, -2099, RM).isNegZero()); EXPECT_TRUE(scalbn(LargestF64, 1, RM).isInfinity()); EXPECT_TRUE( APFloat(APFloat::IEEEdouble(), "0x1p+0") .bitwiseIsEqual(scalbn(APFloat(APFloat::IEEEdouble(), "0x1p+52"), -52, RM))); EXPECT_TRUE( APFloat(APFloat::IEEEdouble(), "0x1p-103") .bitwiseIsEqual(scalbn(APFloat(APFloat::IEEEdouble(), "0x1p-51"), -52, RM))); } TEST(APFloatTest, frexp) { const APFloat::roundingMode RM = APFloat::rmNearestTiesToEven; APFloat PZero = APFloat::getZero(APFloat::IEEEdouble(), false); APFloat MZero = APFloat::getZero(APFloat::IEEEdouble(), true); APFloat One(1.0); APFloat MOne(-1.0); APFloat Two(2.0); APFloat MTwo(-2.0); APFloat LargestDenormal(APFloat::IEEEdouble(), "0x1.ffffffffffffep-1023"); APFloat NegLargestDenormal(APFloat::IEEEdouble(), "-0x1.ffffffffffffep-1023"); APFloat Smallest = APFloat::getSmallest(APFloat::IEEEdouble(), false); APFloat NegSmallest = APFloat::getSmallest(APFloat::IEEEdouble(), true); APFloat Largest = APFloat::getLargest(APFloat::IEEEdouble(), false); APFloat NegLargest = APFloat::getLargest(APFloat::IEEEdouble(), true); APFloat PInf = APFloat::getInf(APFloat::IEEEdouble(), false); APFloat MInf = APFloat::getInf(APFloat::IEEEdouble(), true); APFloat QPNaN = APFloat::getNaN(APFloat::IEEEdouble(), false); APFloat QMNaN = APFloat::getNaN(APFloat::IEEEdouble(), true); APFloat SNaN = APFloat::getSNaN(APFloat::IEEEdouble(), false); // Make sure highest bit of payload is preserved. const APInt Payload(64, (UINT64_C(1) << 50) | (UINT64_C(1) << 49) | (UINT64_C(1234) << 32) | 1); APFloat SNaNWithPayload = APFloat::getSNaN(APFloat::IEEEdouble(), false, &Payload); APFloat SmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEdouble(), false); APFloat NegSmallestNormalized = APFloat::getSmallestNormalized(APFloat::IEEEdouble(), true); int Exp; APFloat Frac(APFloat::IEEEdouble()); Frac = frexp(PZero, Exp, RM); EXPECT_EQ(0, Exp); EXPECT_TRUE(Frac.isPosZero()); Frac = frexp(MZero, Exp, RM); EXPECT_EQ(0, Exp); EXPECT_TRUE(Frac.isNegZero()); Frac = frexp(One, Exp, RM); EXPECT_EQ(1, Exp); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1p-1").bitwiseIsEqual(Frac)); Frac = frexp(MOne, Exp, RM); EXPECT_EQ(1, Exp); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "-0x1p-1").bitwiseIsEqual(Frac)); Frac = frexp(LargestDenormal, Exp, RM); EXPECT_EQ(-1022, Exp); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.ffffffffffffep-1").bitwiseIsEqual(Frac)); Frac = frexp(NegLargestDenormal, Exp, RM); EXPECT_EQ(-1022, Exp); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "-0x1.ffffffffffffep-1").bitwiseIsEqual(Frac)); Frac = frexp(Smallest, Exp, RM); EXPECT_EQ(-1073, Exp); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1p-1").bitwiseIsEqual(Frac)); Frac = frexp(NegSmallest, Exp, RM); EXPECT_EQ(-1073, Exp); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "-0x1p-1").bitwiseIsEqual(Frac)); Frac = frexp(Largest, Exp, RM); EXPECT_EQ(1024, Exp); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.fffffffffffffp-1").bitwiseIsEqual(Frac)); Frac = frexp(NegLargest, Exp, RM); EXPECT_EQ(1024, Exp); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "-0x1.fffffffffffffp-1").bitwiseIsEqual(Frac)); Frac = frexp(PInf, Exp, RM); EXPECT_EQ(INT_MAX, Exp); EXPECT_TRUE(Frac.isInfinity() && !Frac.isNegative()); Frac = frexp(MInf, Exp, RM); EXPECT_EQ(INT_MAX, Exp); EXPECT_TRUE(Frac.isInfinity() && Frac.isNegative()); Frac = frexp(QPNaN, Exp, RM); EXPECT_EQ(INT_MIN, Exp); EXPECT_TRUE(Frac.isNaN()); Frac = frexp(QMNaN, Exp, RM); EXPECT_EQ(INT_MIN, Exp); EXPECT_TRUE(Frac.isNaN()); Frac = frexp(SNaN, Exp, RM); EXPECT_EQ(INT_MIN, Exp); EXPECT_TRUE(Frac.isNaN() && !Frac.isSignaling()); Frac = frexp(SNaNWithPayload, Exp, RM); EXPECT_EQ(INT_MIN, Exp); EXPECT_TRUE(Frac.isNaN() && !Frac.isSignaling()); EXPECT_EQ(Payload, Frac.bitcastToAPInt().getLoBits(51)); Frac = frexp(APFloat(APFloat::IEEEdouble(), "0x0.ffffp-1"), Exp, RM); EXPECT_EQ(-1, Exp); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.fffep-1").bitwiseIsEqual(Frac)); Frac = frexp(APFloat(APFloat::IEEEdouble(), "0x1p-51"), Exp, RM); EXPECT_EQ(-50, Exp); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1p-1").bitwiseIsEqual(Frac)); Frac = frexp(APFloat(APFloat::IEEEdouble(), "0x1.c60f120d9f87cp+51"), Exp, RM); EXPECT_EQ(52, Exp); EXPECT_TRUE(APFloat(APFloat::IEEEdouble(), "0x1.c60f120d9f87cp-1").bitwiseIsEqual(Frac)); } TEST(APFloatTest, mod) { { APFloat f1(APFloat::IEEEdouble(), "1.5"); APFloat f2(APFloat::IEEEdouble(), "1.0"); APFloat expected(APFloat::IEEEdouble(), "0.5"); EXPECT_EQ(f1.mod(f2), APFloat::opOK); EXPECT_TRUE(f1.bitwiseIsEqual(expected)); } { APFloat f1(APFloat::IEEEdouble(), "0.5"); APFloat f2(APFloat::IEEEdouble(), "1.0"); APFloat expected(APFloat::IEEEdouble(), "0.5"); EXPECT_EQ(f1.mod(f2), APFloat::opOK); EXPECT_TRUE(f1.bitwiseIsEqual(expected)); } { APFloat f1(APFloat::IEEEdouble(), "0x1.3333333333333p-2"); // 0.3 APFloat f2(APFloat::IEEEdouble(), "0x1.47ae147ae147bp-7"); // 0.01 APFloat expected(APFloat::IEEEdouble(), "0x1.47ae147ae1471p-7"); // 0.009999999999999983 EXPECT_EQ(f1.mod(f2), APFloat::opOK); EXPECT_TRUE(f1.bitwiseIsEqual(expected)); } { APFloat f1(APFloat::IEEEdouble(), "0x1p64"); // 1.8446744073709552e19 APFloat f2(APFloat::IEEEdouble(), "1.5"); APFloat expected(APFloat::IEEEdouble(), "1.0"); EXPECT_EQ(f1.mod(f2), APFloat::opOK); EXPECT_TRUE(f1.bitwiseIsEqual(expected)); } { APFloat f1(APFloat::IEEEdouble(), "0x1p1000"); APFloat f2(APFloat::IEEEdouble(), "0x1p-1000"); APFloat expected(APFloat::IEEEdouble(), "0.0"); EXPECT_EQ(f1.mod(f2), APFloat::opOK); EXPECT_TRUE(f1.bitwiseIsEqual(expected)); } { APFloat f1(APFloat::IEEEdouble(), "0.0"); APFloat f2(APFloat::IEEEdouble(), "1.0"); APFloat expected(APFloat::IEEEdouble(), "0.0"); EXPECT_EQ(f1.mod(f2), APFloat::opOK); EXPECT_TRUE(f1.bitwiseIsEqual(expected)); } { APFloat f1(APFloat::IEEEdouble(), "1.0"); APFloat f2(APFloat::IEEEdouble(), "0.0"); EXPECT_EQ(f1.mod(f2), APFloat::opInvalidOp); EXPECT_TRUE(f1.isNaN()); } { APFloat f1(APFloat::IEEEdouble(), "0.0"); APFloat f2(APFloat::IEEEdouble(), "0.0"); EXPECT_EQ(f1.mod(f2), APFloat::opInvalidOp); EXPECT_TRUE(f1.isNaN()); } { APFloat f1 = APFloat::getInf(APFloat::IEEEdouble(), false); APFloat f2(APFloat::IEEEdouble(), "1.0"); EXPECT_EQ(f1.mod(f2), APFloat::opInvalidOp); EXPECT_TRUE(f1.isNaN()); } { APFloat f1(APFloat::IEEEdouble(), "-4.0"); APFloat f2(APFloat::IEEEdouble(), "-2.0"); APFloat expected(APFloat::IEEEdouble(), "-0.0"); EXPECT_EQ(f1.mod(f2), APFloat::opOK); EXPECT_TRUE(f1.bitwiseIsEqual(expected)); } { APFloat f1(APFloat::IEEEdouble(), "-4.0"); APFloat f2(APFloat::IEEEdouble(), "2.0"); APFloat expected(APFloat::IEEEdouble(), "-0.0"); EXPECT_EQ(f1.mod(f2), APFloat::opOK); EXPECT_TRUE(f1.bitwiseIsEqual(expected)); } } TEST(APFloatTest, PPCDoubleDoubleAddSpecial) { using DataType = std::tuple; DataType Data[] = { // (1 + 0) + (-1 + 0) = fcZero std::make_tuple(0x3ff0000000000000ull, 0, 0xbff0000000000000ull, 0, APFloat::fcZero, APFloat::rmNearestTiesToEven), // LDBL_MAX + (1.1 >> (1023 - 106) + 0)) = fcInfinity std::make_tuple(0x7fefffffffffffffull, 0x7c8ffffffffffffeull, 0x7948000000000000ull, 0ull, APFloat::fcInfinity, APFloat::rmNearestTiesToEven), // TODO: change the 4th 0x75effffffffffffe to 0x75efffffffffffff when // semPPCDoubleDoubleLegacy is gone. // LDBL_MAX + (1.011111... >> (1023 - 106) + (1.1111111...0 >> (1023 - // 160))) = fcNormal std::make_tuple(0x7fefffffffffffffull, 0x7c8ffffffffffffeull, 0x7947ffffffffffffull, 0x75effffffffffffeull, APFloat::fcNormal, APFloat::rmNearestTiesToEven), // LDBL_MAX + (1.1 >> (1023 - 106) + 0)) = fcInfinity std::make_tuple(0x7fefffffffffffffull, 0x7c8ffffffffffffeull, 0x7fefffffffffffffull, 0x7c8ffffffffffffeull, APFloat::fcInfinity, APFloat::rmNearestTiesToEven), // NaN + (1 + 0) = fcNaN std::make_tuple(0x7ff8000000000000ull, 0, 0x3ff0000000000000ull, 0, APFloat::fcNaN, APFloat::rmNearestTiesToEven), }; for (auto Tp : Data) { uint64_t Op1[2], Op2[2]; APFloat::fltCategory Expected; APFloat::roundingMode RM; std::tie(Op1[0], Op1[1], Op2[0], Op2[1], Expected, RM) = Tp; { APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A1.add(A2, RM); EXPECT_EQ(Expected, A1.getCategory()) << formatv("({0:x} + {1:x}) + ({2:x} + {3:x})", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); } { APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A2.add(A1, RM); EXPECT_EQ(Expected, A2.getCategory()) << formatv("({0:x} + {1:x}) + ({2:x} + {3:x})", Op2[0], Op2[1], Op1[0], Op1[1]) .str(); } } } TEST(APFloatTest, PPCDoubleDoubleAdd) { using DataType = std::tuple; DataType Data[] = { // (1 + 0) + (1e-105 + 0) = (1 + 1e-105) std::make_tuple(0x3ff0000000000000ull, 0, 0x3960000000000000ull, 0, 0x3ff0000000000000ull, 0x3960000000000000ull, APFloat::rmNearestTiesToEven), // (1 + 0) + (1e-106 + 0) = (1 + 1e-106) std::make_tuple(0x3ff0000000000000ull, 0, 0x3950000000000000ull, 0, 0x3ff0000000000000ull, 0x3950000000000000ull, APFloat::rmNearestTiesToEven), // (1 + 1e-106) + (1e-106 + 0) = (1 + 1e-105) std::make_tuple(0x3ff0000000000000ull, 0x3950000000000000ull, 0x3950000000000000ull, 0, 0x3ff0000000000000ull, 0x3960000000000000ull, APFloat::rmNearestTiesToEven), // (1 + 0) + (epsilon + 0) = (1 + epsilon) std::make_tuple(0x3ff0000000000000ull, 0, 0x0000000000000001ull, 0, 0x3ff0000000000000ull, 0x0000000000000001ull, APFloat::rmNearestTiesToEven), // TODO: change 0xf950000000000000 to 0xf940000000000000, when // semPPCDoubleDoubleLegacy is gone. // (DBL_MAX - 1 << (1023 - 105)) + (1 << (1023 - 53) + 0) = DBL_MAX + // 1.11111... << (1023 - 52) std::make_tuple(0x7fefffffffffffffull, 0xf950000000000000ull, 0x7c90000000000000ull, 0, 0x7fefffffffffffffull, 0x7c8ffffffffffffeull, APFloat::rmNearestTiesToEven), // TODO: change 0xf950000000000000 to 0xf940000000000000, when // semPPCDoubleDoubleLegacy is gone. // (1 << (1023 - 53) + 0) + (DBL_MAX - 1 << (1023 - 105)) = DBL_MAX + // 1.11111... << (1023 - 52) std::make_tuple(0x7c90000000000000ull, 0, 0x7fefffffffffffffull, 0xf950000000000000ull, 0x7fefffffffffffffull, 0x7c8ffffffffffffeull, APFloat::rmNearestTiesToEven), }; for (auto Tp : Data) { uint64_t Op1[2], Op2[2], Expected[2]; APFloat::roundingMode RM; std::tie(Op1[0], Op1[1], Op2[0], Op2[1], Expected[0], Expected[1], RM) = Tp; { APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A1.add(A2, RM); EXPECT_EQ(Expected[0], A1.bitcastToAPInt().getRawData()[0]) << formatv("({0:x} + {1:x}) + ({2:x} + {3:x})", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); EXPECT_EQ(Expected[1], A1.bitcastToAPInt().getRawData()[1]) << formatv("({0:x} + {1:x}) + ({2:x} + {3:x})", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); } { APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A2.add(A1, RM); EXPECT_EQ(Expected[0], A2.bitcastToAPInt().getRawData()[0]) << formatv("({0:x} + {1:x}) + ({2:x} + {3:x})", Op2[0], Op2[1], Op1[0], Op1[1]) .str(); EXPECT_EQ(Expected[1], A2.bitcastToAPInt().getRawData()[1]) << formatv("({0:x} + {1:x}) + ({2:x} + {3:x})", Op2[0], Op2[1], Op1[0], Op1[1]) .str(); } } } TEST(APFloatTest, PPCDoubleDoubleSubtract) { using DataType = std::tuple; DataType Data[] = { // (1 + 0) - (-1e-105 + 0) = (1 + 1e-105) std::make_tuple(0x3ff0000000000000ull, 0, 0xb960000000000000ull, 0, 0x3ff0000000000000ull, 0x3960000000000000ull, APFloat::rmNearestTiesToEven), // (1 + 0) - (-1e-106 + 0) = (1 + 1e-106) std::make_tuple(0x3ff0000000000000ull, 0, 0xb950000000000000ull, 0, 0x3ff0000000000000ull, 0x3950000000000000ull, APFloat::rmNearestTiesToEven), }; for (auto Tp : Data) { uint64_t Op1[2], Op2[2], Expected[2]; APFloat::roundingMode RM; std::tie(Op1[0], Op1[1], Op2[0], Op2[1], Expected[0], Expected[1], RM) = Tp; APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A1.subtract(A2, RM); EXPECT_EQ(Expected[0], A1.bitcastToAPInt().getRawData()[0]) << formatv("({0:x} + {1:x}) - ({2:x} + {3:x})", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); EXPECT_EQ(Expected[1], A1.bitcastToAPInt().getRawData()[1]) << formatv("({0:x} + {1:x}) - ({2:x} + {3:x})", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); } } TEST(APFloatTest, PPCDoubleDoubleMultiplySpecial) { using DataType = std::tuple; DataType Data[] = { // fcNaN * fcNaN = fcNaN std::make_tuple(0x7ff8000000000000ull, 0, 0x7ff8000000000000ull, 0, APFloat::fcNaN, APFloat::rmNearestTiesToEven), // fcNaN * fcZero = fcNaN std::make_tuple(0x7ff8000000000000ull, 0, 0, 0, APFloat::fcNaN, APFloat::rmNearestTiesToEven), // fcNaN * fcInfinity = fcNaN std::make_tuple(0x7ff8000000000000ull, 0, 0x7ff0000000000000ull, 0, APFloat::fcNaN, APFloat::rmNearestTiesToEven), // fcNaN * fcNormal = fcNaN std::make_tuple(0x7ff8000000000000ull, 0, 0x3ff0000000000000ull, 0, APFloat::fcNaN, APFloat::rmNearestTiesToEven), // fcInfinity * fcInfinity = fcInfinity std::make_tuple(0x7ff0000000000000ull, 0, 0x7ff0000000000000ull, 0, APFloat::fcInfinity, APFloat::rmNearestTiesToEven), // fcInfinity * fcZero = fcNaN std::make_tuple(0x7ff0000000000000ull, 0, 0, 0, APFloat::fcNaN, APFloat::rmNearestTiesToEven), // fcInfinity * fcNormal = fcInfinity std::make_tuple(0x7ff0000000000000ull, 0, 0x3ff0000000000000ull, 0, APFloat::fcInfinity, APFloat::rmNearestTiesToEven), // fcZero * fcZero = fcZero std::make_tuple(0, 0, 0, 0, APFloat::fcZero, APFloat::rmNearestTiesToEven), // fcZero * fcNormal = fcZero std::make_tuple(0, 0, 0x3ff0000000000000ull, 0, APFloat::fcZero, APFloat::rmNearestTiesToEven), }; for (auto Tp : Data) { uint64_t Op1[2], Op2[2]; APFloat::fltCategory Expected; APFloat::roundingMode RM; std::tie(Op1[0], Op1[1], Op2[0], Op2[1], Expected, RM) = Tp; { APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A1.multiply(A2, RM); EXPECT_EQ(Expected, A1.getCategory()) << formatv("({0:x} + {1:x}) * ({2:x} + {3:x})", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); } { APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A2.multiply(A1, RM); EXPECT_EQ(Expected, A2.getCategory()) << formatv("({0:x} + {1:x}) * ({2:x} + {3:x})", Op2[0], Op2[1], Op1[0], Op1[1]) .str(); } } } TEST(APFloatTest, PPCDoubleDoubleMultiply) { using DataType = std::tuple; DataType Data[] = { // 1/3 * 3 = 1.0 std::make_tuple(0x3fd5555555555555ull, 0x3c75555555555556ull, 0x4008000000000000ull, 0, 0x3ff0000000000000ull, 0, APFloat::rmNearestTiesToEven), // (1 + epsilon) * (1 + 0) = fcZero std::make_tuple(0x3ff0000000000000ull, 0x0000000000000001ull, 0x3ff0000000000000ull, 0, 0x3ff0000000000000ull, 0x0000000000000001ull, APFloat::rmNearestTiesToEven), // (1 + epsilon) * (1 + epsilon) = 1 + 2 * epsilon std::make_tuple(0x3ff0000000000000ull, 0x0000000000000001ull, 0x3ff0000000000000ull, 0x0000000000000001ull, 0x3ff0000000000000ull, 0x0000000000000002ull, APFloat::rmNearestTiesToEven), // -(1 + epsilon) * (1 + epsilon) = -1 std::make_tuple(0xbff0000000000000ull, 0x0000000000000001ull, 0x3ff0000000000000ull, 0x0000000000000001ull, 0xbff0000000000000ull, 0, APFloat::rmNearestTiesToEven), // (0.5 + 0) * (1 + 2 * epsilon) = 0.5 + epsilon std::make_tuple(0x3fe0000000000000ull, 0, 0x3ff0000000000000ull, 0x0000000000000002ull, 0x3fe0000000000000ull, 0x0000000000000001ull, APFloat::rmNearestTiesToEven), // (0.5 + 0) * (1 + epsilon) = 0.5 std::make_tuple(0x3fe0000000000000ull, 0, 0x3ff0000000000000ull, 0x0000000000000001ull, 0x3fe0000000000000ull, 0, APFloat::rmNearestTiesToEven), // __LDBL_MAX__ * (1 + 1 << 106) = inf std::make_tuple(0x7fefffffffffffffull, 0x7c8ffffffffffffeull, 0x3ff0000000000000ull, 0x3950000000000000ull, 0x7ff0000000000000ull, 0, APFloat::rmNearestTiesToEven), // __LDBL_MAX__ * (1 + 1 << 107) > __LDBL_MAX__, but not inf, yes =_=||| std::make_tuple(0x7fefffffffffffffull, 0x7c8ffffffffffffeull, 0x3ff0000000000000ull, 0x3940000000000000ull, 0x7fefffffffffffffull, 0x7c8fffffffffffffull, APFloat::rmNearestTiesToEven), // __LDBL_MAX__ * (1 + 1 << 108) = __LDBL_MAX__ std::make_tuple(0x7fefffffffffffffull, 0x7c8ffffffffffffeull, 0x3ff0000000000000ull, 0x3930000000000000ull, 0x7fefffffffffffffull, 0x7c8ffffffffffffeull, APFloat::rmNearestTiesToEven), }; for (auto Tp : Data) { uint64_t Op1[2], Op2[2], Expected[2]; APFloat::roundingMode RM; std::tie(Op1[0], Op1[1], Op2[0], Op2[1], Expected[0], Expected[1], RM) = Tp; { APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A1.multiply(A2, RM); EXPECT_EQ(Expected[0], A1.bitcastToAPInt().getRawData()[0]) << formatv("({0:x} + {1:x}) * ({2:x} + {3:x})", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); EXPECT_EQ(Expected[1], A1.bitcastToAPInt().getRawData()[1]) << formatv("({0:x} + {1:x}) * ({2:x} + {3:x})", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); } { APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A2.multiply(A1, RM); EXPECT_EQ(Expected[0], A2.bitcastToAPInt().getRawData()[0]) << formatv("({0:x} + {1:x}) * ({2:x} + {3:x})", Op2[0], Op2[1], Op1[0], Op1[1]) .str(); EXPECT_EQ(Expected[1], A2.bitcastToAPInt().getRawData()[1]) << formatv("({0:x} + {1:x}) * ({2:x} + {3:x})", Op2[0], Op2[1], Op1[0], Op1[1]) .str(); } } } TEST(APFloatTest, PPCDoubleDoubleDivide) { using DataType = std::tuple; // TODO: Only a sanity check for now. Add more edge cases when the // double-double algorithm is implemented. DataType Data[] = { // 1 / 3 = 1/3 std::make_tuple(0x3ff0000000000000ull, 0, 0x4008000000000000ull, 0, 0x3fd5555555555555ull, 0x3c75555555555556ull, APFloat::rmNearestTiesToEven), }; for (auto Tp : Data) { uint64_t Op1[2], Op2[2], Expected[2]; APFloat::roundingMode RM; std::tie(Op1[0], Op1[1], Op2[0], Op2[1], Expected[0], Expected[1], RM) = Tp; APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A1.divide(A2, RM); EXPECT_EQ(Expected[0], A1.bitcastToAPInt().getRawData()[0]) << formatv("({0:x} + {1:x}) / ({2:x} + {3:x})", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); EXPECT_EQ(Expected[1], A1.bitcastToAPInt().getRawData()[1]) << formatv("({0:x} + {1:x}) / ({2:x} + {3:x})", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); } } TEST(APFloatTest, PPCDoubleDoubleRemainder) { using DataType = std::tuple; DataType Data[] = { // remainder(3.0 + 3.0 << 53, 1.25 + 1.25 << 53) = (0.5 + 0.5 << 53) std::make_tuple(0x4008000000000000ull, 0x3cb8000000000000ull, 0x3ff4000000000000ull, 0x3ca4000000000000ull, 0x3fe0000000000000ull, 0x3c90000000000000ull), // remainder(3.0 + 3.0 << 53, 1.75 + 1.75 << 53) = (-0.5 - 0.5 << 53) std::make_tuple(0x4008000000000000ull, 0x3cb8000000000000ull, 0x3ffc000000000000ull, 0x3cac000000000000ull, 0xbfe0000000000000ull, 0xbc90000000000000ull), }; for (auto Tp : Data) { uint64_t Op1[2], Op2[2], Expected[2]; std::tie(Op1[0], Op1[1], Op2[0], Op2[1], Expected[0], Expected[1]) = Tp; APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A1.remainder(A2); EXPECT_EQ(Expected[0], A1.bitcastToAPInt().getRawData()[0]) << formatv("remainder({0:x} + {1:x}), ({2:x} + {3:x}))", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); EXPECT_EQ(Expected[1], A1.bitcastToAPInt().getRawData()[1]) << formatv("remainder(({0:x} + {1:x}), ({2:x} + {3:x}))", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); } } TEST(APFloatTest, PPCDoubleDoubleMod) { using DataType = std::tuple; DataType Data[] = { // mod(3.0 + 3.0 << 53, 1.25 + 1.25 << 53) = (0.5 + 0.5 << 53) std::make_tuple(0x4008000000000000ull, 0x3cb8000000000000ull, 0x3ff4000000000000ull, 0x3ca4000000000000ull, 0x3fe0000000000000ull, 0x3c90000000000000ull), // mod(3.0 + 3.0 << 53, 1.75 + 1.75 << 53) = (1.25 + 1.25 << 53) // 0xbc98000000000000 doesn't seem right, but it's what we currently have. // TODO: investigate std::make_tuple(0x4008000000000000ull, 0x3cb8000000000000ull, 0x3ffc000000000000ull, 0x3cac000000000000ull, 0x3ff4000000000001ull, 0xbc98000000000000ull), }; for (auto Tp : Data) { uint64_t Op1[2], Op2[2], Expected[2]; std::tie(Op1[0], Op1[1], Op2[0], Op2[1], Expected[0], Expected[1]) = Tp; APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); A1.mod(A2); EXPECT_EQ(Expected[0], A1.bitcastToAPInt().getRawData()[0]) << formatv("fmod(({0:x} + {1:x}), ({2:x} + {3:x}))", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); EXPECT_EQ(Expected[1], A1.bitcastToAPInt().getRawData()[1]) << formatv("fmod(({0:x} + {1:x}), ({2:x} + {3:x}))", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); } } TEST(APFloatTest, PPCDoubleDoubleFMA) { // Sanity check for now. APFloat A(APFloat::PPCDoubleDouble(), "2"); A.fusedMultiplyAdd(APFloat(APFloat::PPCDoubleDouble(), "3"), APFloat(APFloat::PPCDoubleDouble(), "4"), APFloat::rmNearestTiesToEven); EXPECT_EQ(APFloat::cmpEqual, APFloat(APFloat::PPCDoubleDouble(), "10").compare(A)); } TEST(APFloatTest, PPCDoubleDoubleRoundToIntegral) { { APFloat A(APFloat::PPCDoubleDouble(), "1.5"); A.roundToIntegral(APFloat::rmNearestTiesToEven); EXPECT_EQ(APFloat::cmpEqual, APFloat(APFloat::PPCDoubleDouble(), "2").compare(A)); } { APFloat A(APFloat::PPCDoubleDouble(), "2.5"); A.roundToIntegral(APFloat::rmNearestTiesToEven); EXPECT_EQ(APFloat::cmpEqual, APFloat(APFloat::PPCDoubleDouble(), "2").compare(A)); } } TEST(APFloatTest, PPCDoubleDoubleCompare) { using DataType = std::tuple; DataType Data[] = { // (1 + 0) = (1 + 0) std::make_tuple(0x3ff0000000000000ull, 0, 0x3ff0000000000000ull, 0, APFloat::cmpEqual), // (1 + 0) < (1.00...1 + 0) std::make_tuple(0x3ff0000000000000ull, 0, 0x3ff0000000000001ull, 0, APFloat::cmpLessThan), // (1.00...1 + 0) > (1 + 0) std::make_tuple(0x3ff0000000000001ull, 0, 0x3ff0000000000000ull, 0, APFloat::cmpGreaterThan), // (1 + 0) < (1 + epsilon) std::make_tuple(0x3ff0000000000000ull, 0, 0x3ff0000000000001ull, 0x0000000000000001ull, APFloat::cmpLessThan), // NaN != NaN std::make_tuple(0x7ff8000000000000ull, 0, 0x7ff8000000000000ull, 0, APFloat::cmpUnordered), // (1 + 0) != NaN std::make_tuple(0x3ff0000000000000ull, 0, 0x7ff8000000000000ull, 0, APFloat::cmpUnordered), // Inf = Inf std::make_tuple(0x7ff0000000000000ull, 0, 0x7ff0000000000000ull, 0, APFloat::cmpEqual), }; for (auto Tp : Data) { uint64_t Op1[2], Op2[2]; APFloat::cmpResult Expected; std::tie(Op1[0], Op1[1], Op2[0], Op2[1], Expected) = Tp; APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); EXPECT_EQ(Expected, A1.compare(A2)) << formatv("compare(({0:x} + {1:x}), ({2:x} + {3:x}))", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); } } TEST(APFloatTest, PPCDoubleDoubleBitwiseIsEqual) { using DataType = std::tuple; DataType Data[] = { // (1 + 0) = (1 + 0) std::make_tuple(0x3ff0000000000000ull, 0, 0x3ff0000000000000ull, 0, true), // (1 + 0) != (1.00...1 + 0) std::make_tuple(0x3ff0000000000000ull, 0, 0x3ff0000000000001ull, 0, false), // NaN = NaN std::make_tuple(0x7ff8000000000000ull, 0, 0x7ff8000000000000ull, 0, true), // NaN != NaN with a different bit pattern std::make_tuple(0x7ff8000000000000ull, 0, 0x7ff8000000000000ull, 0x3ff0000000000000ull, false), // Inf = Inf std::make_tuple(0x7ff0000000000000ull, 0, 0x7ff0000000000000ull, 0, true), }; for (auto Tp : Data) { uint64_t Op1[2], Op2[2]; bool Expected; std::tie(Op1[0], Op1[1], Op2[0], Op2[1], Expected) = Tp; APFloat A1(APFloat::PPCDoubleDouble(), APInt(128, 2, Op1)); APFloat A2(APFloat::PPCDoubleDouble(), APInt(128, 2, Op2)); EXPECT_EQ(Expected, A1.bitwiseIsEqual(A2)) << formatv("({0:x} + {1:x}) = ({2:x} + {3:x})", Op1[0], Op1[1], Op2[0], Op2[1]) .str(); } } TEST(APFloatTest, PPCDoubleDoubleHashValue) { uint64_t Data1[] = {0x3ff0000000000001ull, 0x0000000000000001ull}; uint64_t Data2[] = {0x3ff0000000000001ull, 0}; // The hash values are *hopefully* different. EXPECT_NE( hash_value(APFloat(APFloat::PPCDoubleDouble(), APInt(128, 2, Data1))), hash_value(APFloat(APFloat::PPCDoubleDouble(), APInt(128, 2, Data2)))); } TEST(APFloatTest, PPCDoubleDoubleChangeSign) { uint64_t Data[] = { 0x400f000000000000ull, 0xbcb0000000000000ull, }; APFloat Float(APFloat::PPCDoubleDouble(), APInt(128, 2, Data)); { APFloat Actual = APFloat::copySign(Float, APFloat(APFloat::IEEEdouble(), "1")); EXPECT_EQ(0x400f000000000000ull, Actual.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0xbcb0000000000000ull, Actual.bitcastToAPInt().getRawData()[1]); } { APFloat Actual = APFloat::copySign(Float, APFloat(APFloat::IEEEdouble(), "-1")); EXPECT_EQ(0xc00f000000000000ull, Actual.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0x3cb0000000000000ull, Actual.bitcastToAPInt().getRawData()[1]); } } TEST(APFloatTest, PPCDoubleDoubleFactories) { { uint64_t Data[] = { 0, 0, }; EXPECT_EQ(APInt(128, 2, Data), APFloat::getZero(APFloat::PPCDoubleDouble()).bitcastToAPInt()); } { uint64_t Data[] = { 0x7fefffffffffffffull, 0x7c8ffffffffffffeull, }; EXPECT_EQ(APInt(128, 2, Data), APFloat::getLargest(APFloat::PPCDoubleDouble()).bitcastToAPInt()); } { uint64_t Data[] = { 0x0000000000000001ull, 0, }; EXPECT_EQ( APInt(128, 2, Data), APFloat::getSmallest(APFloat::PPCDoubleDouble()).bitcastToAPInt()); } { uint64_t Data[] = {0x0360000000000000ull, 0}; EXPECT_EQ(APInt(128, 2, Data), APFloat::getSmallestNormalized(APFloat::PPCDoubleDouble()) .bitcastToAPInt()); } { uint64_t Data[] = { 0x8000000000000000ull, 0x0000000000000000ull, }; EXPECT_EQ( APInt(128, 2, Data), APFloat::getZero(APFloat::PPCDoubleDouble(), true).bitcastToAPInt()); } { uint64_t Data[] = { 0xffefffffffffffffull, 0xfc8ffffffffffffeull, }; EXPECT_EQ( APInt(128, 2, Data), APFloat::getLargest(APFloat::PPCDoubleDouble(), true).bitcastToAPInt()); } { uint64_t Data[] = { 0x8000000000000001ull, 0x0000000000000000ull, }; EXPECT_EQ(APInt(128, 2, Data), APFloat::getSmallest(APFloat::PPCDoubleDouble(), true) .bitcastToAPInt()); } { uint64_t Data[] = { 0x8360000000000000ull, 0x0000000000000000ull, }; EXPECT_EQ(APInt(128, 2, Data), APFloat::getSmallestNormalized(APFloat::PPCDoubleDouble(), true) .bitcastToAPInt()); } EXPECT_TRUE(APFloat::getSmallest(APFloat::PPCDoubleDouble()).isSmallest()); EXPECT_TRUE(APFloat::getLargest(APFloat::PPCDoubleDouble()).isLargest()); } TEST(APFloatTest, PPCDoubleDoubleIsDenormal) { EXPECT_TRUE(APFloat::getSmallest(APFloat::PPCDoubleDouble()).isDenormal()); EXPECT_FALSE(APFloat::getLargest(APFloat::PPCDoubleDouble()).isDenormal()); EXPECT_FALSE( APFloat::getSmallestNormalized(APFloat::PPCDoubleDouble()).isDenormal()); { // (4 + 3) is not normalized uint64_t Data[] = { 0x4010000000000000ull, 0x4008000000000000ull, }; EXPECT_TRUE( APFloat(APFloat::PPCDoubleDouble(), APInt(128, 2, Data)).isDenormal()); } } TEST(APFloatTest, PPCDoubleDoubleScalbn) { // 3.0 + 3.0 << 53 uint64_t Input[] = { 0x4008000000000000ull, 0x3cb8000000000000ull, }; APFloat Result = scalbn(APFloat(APFloat::PPCDoubleDouble(), APInt(128, 2, Input)), 1, APFloat::rmNearestTiesToEven); // 6.0 + 6.0 << 53 EXPECT_EQ(0x4018000000000000ull, Result.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0x3cc8000000000000ull, Result.bitcastToAPInt().getRawData()[1]); } TEST(APFloatTest, PPCDoubleDoubleFrexp) { // 3.0 + 3.0 << 53 uint64_t Input[] = { 0x4008000000000000ull, 0x3cb8000000000000ull, }; int Exp; // 0.75 + 0.75 << 53 APFloat Result = frexp(APFloat(APFloat::PPCDoubleDouble(), APInt(128, 2, Input)), Exp, APFloat::rmNearestTiesToEven); EXPECT_EQ(2, Exp); EXPECT_EQ(0x3fe8000000000000ull, Result.bitcastToAPInt().getRawData()[0]); EXPECT_EQ(0x3c98000000000000ull, Result.bitcastToAPInt().getRawData()[1]); } }