blob: 208950d7ab714b3052b51161b6025de441217307 [file] [log] [blame]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements a class to represent arbitrary precision floating
10// point values and provide a variety of arithmetic operations on them.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnere5256752007-12-08 19:00:03 +000014#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +000015#include "llvm/ADT/APSInt.h"
Mehdi Amini47b292d2016-04-16 07:51:28 +000016#include "llvm/ADT/ArrayRef.h"
Ted Kremenek6f30a072008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
Jordan Rosee1f76582013-01-18 21:45:30 +000019#include "llvm/ADT/StringExtras.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000020#include "llvm/ADT/StringRef.h"
Nico Weber432a3882018-04-30 14:59:11 +000021#include "llvm/Config/llvm-config.h"
Tim Shen44bde892016-12-12 21:59:30 +000022#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000023#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000024#include "llvm/Support/MathExtras.h"
Tim Shen44bde892016-12-12 21:59:30 +000025#include "llvm/Support/raw_ostream.h"
Chris Lattner17f71652008-08-17 07:19:36 +000026#include <cstring>
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000027#include <limits.h>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000028
Tim Shen601ba8c2017-01-27 02:11:07 +000029#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
30 do { \
31 if (usesLayout<IEEEFloat>(getSemantics())) \
32 return U.IEEE.METHOD_CALL; \
33 if (usesLayout<DoubleAPFloat>(getSemantics())) \
34 return U.Double.METHOD_CALL; \
35 llvm_unreachable("Unexpected semantics"); \
36 } while (false)
37
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000038using namespace llvm;
39
Michael Gottesman9b877e12013-06-24 09:57:57 +000040/// A macro used to combine two fcCategory enums into one key which can be used
41/// in a switch statement to classify how the interaction of two APFloat's
42/// categories affects an operation.
43///
44/// TODO: If clang source code is ever allowed to use constexpr in its own
45/// codebase, change this into a static inline function.
46#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000047
Neil Booth8f1946f2007-10-03 22:26:02 +000048/* Assumed in hexadecimal significand parsing, and conversion to
49 hexadecimal strings. */
Craig Topperc85be522017-06-18 18:15:41 +000050static_assert(APFloatBase::integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000051
52namespace llvm {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000053 /* Represents floating point arithmetic semantics. */
54 struct fltSemantics {
55 /* The largest E such that 2^E is representable; this matches the
56 definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000057 APFloatBase::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000058
59 /* The smallest E such that 2^E is a normalized number; this
60 matches the definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000061 APFloatBase::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000062
63 /* Number of bits in the significand. This includes the integer
64 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000065 unsigned int precision;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000066
67 /* Number of bits actually used in the semantics. */
68 unsigned int sizeInBits;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000069 };
70
Stephan Bergmann17c7f702016-12-14 11:57:17 +000071 static const fltSemantics semIEEEhalf = {15, -14, 11, 16};
72 static const fltSemantics semIEEEsingle = {127, -126, 24, 32};
73 static const fltSemantics semIEEEdouble = {1023, -1022, 53, 64};
74 static const fltSemantics semIEEEquad = {16383, -16382, 113, 128};
75 static const fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80};
76 static const fltSemantics semBogus = {0, 0, 0, 0};
Dale Johannesen007aa372007-10-11 18:07:22 +000077
Tim Shen7117e692017-01-26 00:11:07 +000078 /* The IBM double-double semantics. Such a number consists of a pair of IEEE
79 64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal,
80 (double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo.
81 Therefore it has two 53-bit mantissa parts that aren't necessarily adjacent
82 to each other, and two 11-bit exponents.
Michal Gorny21c12042017-01-03 16:33:50 +000083
84 Note: we need to make the value different from semBogus as otherwise
85 an unsafe optimization may collapse both values to a single address,
86 and we heavily rely on them having distinct addresses. */
87 static const fltSemantics semPPCDoubleDouble = {-1, 0, 0, 0};
Tim Shen139a58f2016-10-27 22:52:40 +000088
Tim Shenfd1e5aa2017-01-23 22:39:35 +000089 /* These are legacy semantics for the fallback, inaccrurate implementation of
90 IBM double-double, if the accurate semPPCDoubleDouble doesn't handle the
Tim Shen7117e692017-01-26 00:11:07 +000091 operation. It's equivalent to having an IEEE number with consecutive 106
92 bits of mantissa and 11 bits of exponent.
93
94 It's not equivalent to IBM double-double. For example, a legit IBM
95 double-double, 1 + epsilon:
96
97 1 + epsilon = 1 + (1 >> 1076)
98
99 is not representable by a consecutive 106 bits of mantissa.
Tim Shen139a58f2016-10-27 22:52:40 +0000100
Tim Shenfd1e5aa2017-01-23 22:39:35 +0000101 Currently, these semantics are used in the following way:
102
Tim Shen7117e692017-01-26 00:11:07 +0000103 semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) ->
104 (64-bit APInt, 64-bit APInt) -> (128-bit APInt) ->
105 semPPCDoubleDoubleLegacy -> IEEE operations
Tim Shenfd1e5aa2017-01-23 22:39:35 +0000106
107 We use bitcastToAPInt() to get the bit representation (in APInt) of the
108 underlying IEEEdouble, then use the APInt constructor to construct the
109 legacy IEEE float.
110
111 TODO: Implement all operations in semPPCDoubleDouble, and delete these
112 semantics. */
113 static const fltSemantics semPPCDoubleDoubleLegacy = {1023, -1022 + 53,
114 53 + 53, 128};
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000115
116 const fltSemantics &APFloatBase::IEEEhalf() {
117 return semIEEEhalf;
118 }
119 const fltSemantics &APFloatBase::IEEEsingle() {
120 return semIEEEsingle;
121 }
122 const fltSemantics &APFloatBase::IEEEdouble() {
123 return semIEEEdouble;
124 }
125 const fltSemantics &APFloatBase::IEEEquad() {
126 return semIEEEquad;
127 }
128 const fltSemantics &APFloatBase::x87DoubleExtended() {
129 return semX87DoubleExtended;
130 }
131 const fltSemantics &APFloatBase::Bogus() {
132 return semBogus;
133 }
134 const fltSemantics &APFloatBase::PPCDoubleDouble() {
135 return semPPCDoubleDouble;
136 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000137
138 /* A tight upper bound on number of parts required to hold the value
139 pow(5, power) is
140
Neil Booth91305512007-10-15 15:00:55 +0000141 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000142
Neil Boothb93d90e2007-10-12 16:02:31 +0000143 However, whilst the result may require only this many parts,
144 because we are multiplying two values to get it, the
145 multiplication may require an extra part with the excess part
146 being zero (consider the trivial case of 1 * 1, tcFullMultiply
147 requires two parts to hold the single-part result). So we add an
148 extra one to guarantee enough space whilst multiplying. */
149 const unsigned int maxExponent = 16383;
150 const unsigned int maxPrecision = 113;
151 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Craig Topperc85be522017-06-18 18:15:41 +0000152 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815) / (351 * APFloatBase::integerPartWidth));
Tim Shen85de51d2016-10-25 19:55:59 +0000153
154 unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
155 return semantics.precision;
156 }
157 APFloatBase::ExponentType
158 APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) {
159 return semantics.maxExponent;
160 }
161 APFloatBase::ExponentType
162 APFloatBase::semanticsMinExponent(const fltSemantics &semantics) {
163 return semantics.minExponent;
164 }
165 unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
166 return semantics.sizeInBits;
167 }
168
169 unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) {
170 return Sem.sizeInBits;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000171}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000172
Chris Lattner91702092009-03-12 23:59:55 +0000173/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000174
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000175static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000176partCountForBits(unsigned int bits)
177{
Craig Topperc85be522017-06-18 18:15:41 +0000178 return ((bits) + APFloatBase::integerPartWidth - 1) / APFloatBase::integerPartWidth;
Chris Lattner91702092009-03-12 23:59:55 +0000179}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000180
Chris Lattner91702092009-03-12 23:59:55 +0000181/* Returns 0U-9U. Return values >= 10U are not digits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000182static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000183decDigitValue(unsigned int c)
184{
185 return c - '0';
186}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000187
Chris Lattner91702092009-03-12 23:59:55 +0000188/* Return the value of a decimal exponent of the form
189 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000190
Chris Lattner91702092009-03-12 23:59:55 +0000191 If the exponent overflows, returns a large exponent with the
192 appropriate sign. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000193static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000194readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000195{
196 bool isNegative;
197 unsigned int absExponent;
198 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000199 StringRef::iterator p = begin;
200
Eli Friedman3dd72ea2019-03-28 21:12:28 +0000201 // Treat no exponent as 0 to match binutils
202 if (p == end || ((*p == '-' || *p == '+') && (p + 1) == end)) {
203 return 0;
204 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000205
Chris Lattner91702092009-03-12 23:59:55 +0000206 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000207 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000208 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000209 assert(p != end && "Exponent has no digits");
210 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000211
Chris Lattner91702092009-03-12 23:59:55 +0000212 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000213 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000214
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000215 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000216 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000217
Chris Lattner91702092009-03-12 23:59:55 +0000218 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000219 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000220
Chris Lattner91702092009-03-12 23:59:55 +0000221 value += absExponent * 10;
222 if (absExponent >= overlargeExponent) {
223 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000224 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000225 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000226 }
Chris Lattner91702092009-03-12 23:59:55 +0000227 absExponent = value;
228 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000229
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000230 assert(p == end && "Invalid exponent in exponent");
231
Chris Lattner91702092009-03-12 23:59:55 +0000232 if (isNegative)
233 return -(int) absExponent;
234 else
235 return (int) absExponent;
236}
237
238/* This is ugly and needs cleaning up, but I don't immediately see
239 how whilst remaining safe. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000240static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000241totalExponent(StringRef::iterator p, StringRef::iterator end,
242 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000243{
244 int unsignedExponent;
245 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000246 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000247
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000248 assert(p != end && "Exponent has no digits");
249
Chris Lattner91702092009-03-12 23:59:55 +0000250 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000251 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000252 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000253 assert(p != end && "Exponent has no digits");
254 }
Chris Lattner91702092009-03-12 23:59:55 +0000255
256 unsignedExponent = 0;
257 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000258 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000259 unsigned int value;
260
261 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000262 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000263
Chris Lattner91702092009-03-12 23:59:55 +0000264 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000265 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000266 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000267 break;
268 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000269 }
270
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000271 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000272 overflow = true;
273
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000274 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000275 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000276 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000277 exponent = -exponent;
278 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000279 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000280 overflow = true;
281 }
282
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000283 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000284 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000285
286 return exponent;
287}
288
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000289static StringRef::iterator
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000290skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
291 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000292{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000293 StringRef::iterator p = begin;
294 *dot = end;
Nick Lewycky095b92e2014-09-06 01:16:42 +0000295 while (p != end && *p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000296 p++;
297
Nick Lewycky095b92e2014-09-06 01:16:42 +0000298 if (p != end && *p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000299 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000300
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000301 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000302
Nick Lewycky095b92e2014-09-06 01:16:42 +0000303 while (p != end && *p == '0')
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000304 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000305 }
306
Chris Lattner91702092009-03-12 23:59:55 +0000307 return p;
308}
Neil Booth4ed401b2007-10-14 10:16:12 +0000309
Chris Lattner91702092009-03-12 23:59:55 +0000310/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000311
Chris Lattner91702092009-03-12 23:59:55 +0000312 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000313
Chris Lattner91702092009-03-12 23:59:55 +0000314 where the decimal point and exponent are optional, fill out the
315 structure D. Exponent is appropriate if the significand is
316 treated as an integer, and normalizedExponent if the significand
317 is taken to have the decimal point after a single leading
318 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000319
Chris Lattner91702092009-03-12 23:59:55 +0000320 If the value is zero, V->firstSigDigit points to a non-digit, and
321 the return exponent is zero.
322*/
323struct decimalInfo {
324 const char *firstSigDigit;
325 const char *lastSigDigit;
326 int exponent;
327 int normalizedExponent;
328};
Neil Booth4ed401b2007-10-14 10:16:12 +0000329
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000330static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000331interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
332 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000333{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000334 StringRef::iterator dot = end;
335 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000336
Chris Lattner91702092009-03-12 23:59:55 +0000337 D->firstSigDigit = p;
338 D->exponent = 0;
339 D->normalizedExponent = 0;
340
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000341 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000342 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000343 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000344 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000345 if (p == end)
346 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000347 }
Chris Lattner91702092009-03-12 23:59:55 +0000348 if (decDigitValue(*p) >= 10U)
349 break;
Chris Lattner91702092009-03-12 23:59:55 +0000350 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000351
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000352 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000353 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
354 assert(p != begin && "Significand has no digits");
355 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000356
357 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000358 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000359
Chris Lattner91702092009-03-12 23:59:55 +0000360 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000361 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000362 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000363 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000364
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000365 /* If number is all zeroes accept any exponent. */
366 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000367 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000368 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000369 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000370 do
371 p--;
372 while (p != begin && *p == '0');
373 while (p != begin && *p == '.');
374 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000375
Chris Lattner91702092009-03-12 23:59:55 +0000376 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000377 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000378 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000379 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000380 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000381 }
382
Chris Lattner91702092009-03-12 23:59:55 +0000383 D->lastSigDigit = p;
384}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000385
Chris Lattner91702092009-03-12 23:59:55 +0000386/* Return the trailing fraction of a hexadecimal number.
387 DIGITVALUE is the first hex digit of the fraction, P points to
388 the next digit. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000389static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000390trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
391 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000392{
393 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000394
Chris Lattner91702092009-03-12 23:59:55 +0000395 /* If the first trailing digit isn't 0 or 8 we can work out the
396 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000397 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000398 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000399 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000400 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000401
Eli Friedmand2eb07a2013-07-17 22:17:29 +0000402 // Otherwise we need to find the first non-zero digit.
403 while (p != end && (*p == '0' || *p == '.'))
Chris Lattner91702092009-03-12 23:59:55 +0000404 p++;
405
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000406 assert(p != end && "Invalid trailing hexadecimal fraction!");
407
Chris Lattner91702092009-03-12 23:59:55 +0000408 hexDigit = hexDigitValue(*p);
409
410 /* If we ran off the end it is exactly zero or one-half, otherwise
411 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000412 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000413 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
414 else
415 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
416}
417
418/* Return the fraction lost were a bignum truncated losing the least
419 significant BITS bits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000420static lostFraction
Craig Topperc85be522017-06-18 18:15:41 +0000421lostFractionThroughTruncation(const APFloatBase::integerPart *parts,
Chris Lattner91702092009-03-12 23:59:55 +0000422 unsigned int partCount,
423 unsigned int bits)
424{
425 unsigned int lsb;
426
427 lsb = APInt::tcLSB(parts, partCount);
428
429 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000430 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000431 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000432 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000433 return lfExactlyHalf;
Craig Topperc85be522017-06-18 18:15:41 +0000434 if (bits <= partCount * APFloatBase::integerPartWidth &&
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000435 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000436 return lfMoreThanHalf;
437
438 return lfLessThanHalf;
439}
440
441/* Shift DST right BITS bits noting lost fraction. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000442static lostFraction
Craig Topperc85be522017-06-18 18:15:41 +0000443shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
Chris Lattner91702092009-03-12 23:59:55 +0000444{
445 lostFraction lost_fraction;
446
447 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
448
449 APInt::tcShiftRight(dst, parts, bits);
450
451 return lost_fraction;
452}
453
454/* Combine the effect of two lost fractions. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000455static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000456combineLostFractions(lostFraction moreSignificant,
457 lostFraction lessSignificant)
458{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000459 if (lessSignificant != lfExactlyZero) {
460 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000461 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000462 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000463 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000464 }
465
Chris Lattner91702092009-03-12 23:59:55 +0000466 return moreSignificant;
467}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000468
Chris Lattner91702092009-03-12 23:59:55 +0000469/* The error from the true value, in half-ulps, on multiplying two
470 floating point numbers, which differ from the value they
471 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
472 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000473
Chris Lattner91702092009-03-12 23:59:55 +0000474 See "How to Read Floating Point Numbers Accurately" by William D
475 Clinger. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000476static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000477HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
478{
479 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000480
Chris Lattner91702092009-03-12 23:59:55 +0000481 if (HUerr1 + HUerr2 == 0)
482 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
483 else
484 return inexactMultiply + 2 * (HUerr1 + HUerr2);
485}
Neil Booth8f1946f2007-10-03 22:26:02 +0000486
Chris Lattner91702092009-03-12 23:59:55 +0000487/* The number of ulps from the boundary (zero, or half if ISNEAREST)
488 when the least significant BITS are truncated. BITS cannot be
489 zero. */
Craig Topperc85be522017-06-18 18:15:41 +0000490static APFloatBase::integerPart
491ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits,
492 bool isNearest) {
Chris Lattner91702092009-03-12 23:59:55 +0000493 unsigned int count, partBits;
Craig Topperc85be522017-06-18 18:15:41 +0000494 APFloatBase::integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000495
Evan Cheng67c90212009-10-27 21:35:42 +0000496 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000497
Chris Lattner91702092009-03-12 23:59:55 +0000498 bits--;
Craig Topperc85be522017-06-18 18:15:41 +0000499 count = bits / APFloatBase::integerPartWidth;
500 partBits = bits % APFloatBase::integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000501
Craig Topperc85be522017-06-18 18:15:41 +0000502 part = parts[count] & (~(APFloatBase::integerPart) 0 >> (APFloatBase::integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000503
Chris Lattner91702092009-03-12 23:59:55 +0000504 if (isNearest)
Craig Topperc85be522017-06-18 18:15:41 +0000505 boundary = (APFloatBase::integerPart) 1 << (partBits - 1);
Chris Lattner91702092009-03-12 23:59:55 +0000506 else
507 boundary = 0;
508
509 if (count == 0) {
510 if (part - boundary <= boundary - part)
511 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000512 else
Chris Lattner91702092009-03-12 23:59:55 +0000513 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000514 }
515
Chris Lattner91702092009-03-12 23:59:55 +0000516 if (part == boundary) {
517 while (--count)
518 if (parts[count])
Craig Topperc85be522017-06-18 18:15:41 +0000519 return ~(APFloatBase::integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000520
Chris Lattner91702092009-03-12 23:59:55 +0000521 return parts[0];
522 } else if (part == boundary - 1) {
523 while (--count)
524 if (~parts[count])
Craig Topperc85be522017-06-18 18:15:41 +0000525 return ~(APFloatBase::integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000526
Chris Lattner91702092009-03-12 23:59:55 +0000527 return -parts[0];
528 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000529
Craig Topperc85be522017-06-18 18:15:41 +0000530 return ~(APFloatBase::integerPart) 0; /* A lot. */
Chris Lattner91702092009-03-12 23:59:55 +0000531}
Neil Boothb93d90e2007-10-12 16:02:31 +0000532
Chris Lattner91702092009-03-12 23:59:55 +0000533/* Place pow(5, power) in DST, and return the number of parts used.
534 DST must be at least one part larger than size of the answer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000535static unsigned int
Craig Topperc85be522017-06-18 18:15:41 +0000536powerOf5(APFloatBase::integerPart *dst, unsigned int power) {
537 static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 };
538 APFloatBase::integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000539 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000540
Chris Lattner0bf18692009-03-13 00:03:51 +0000541 unsigned int partsCount[16] = { 1 };
Craig Topperc85be522017-06-18 18:15:41 +0000542 APFloatBase::integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
Chris Lattner91702092009-03-12 23:59:55 +0000543 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000544 assert(power <= maxExponent);
545
546 p1 = dst;
547 p2 = scratch;
548
549 *p1 = firstEightPowers[power & 7];
550 power >>= 3;
551
552 result = 1;
553 pow5 = pow5s;
554
555 for (unsigned int n = 0; power; power >>= 1, n++) {
556 unsigned int pc;
557
558 pc = partsCount[n];
559
560 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
561 if (pc == 0) {
562 pc = partsCount[n - 1];
563 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
564 pc *= 2;
565 if (pow5[pc - 1] == 0)
566 pc--;
567 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000568 }
569
Chris Lattner91702092009-03-12 23:59:55 +0000570 if (power & 1) {
Craig Topperc85be522017-06-18 18:15:41 +0000571 APFloatBase::integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000572
Chris Lattner91702092009-03-12 23:59:55 +0000573 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
574 result += pc;
575 if (p2[result - 1] == 0)
576 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000577
Chris Lattner91702092009-03-12 23:59:55 +0000578 /* Now result is in p1 with partsCount parts and p2 is scratch
579 space. */
Richard Trieu7a083812016-02-18 22:09:30 +0000580 tmp = p1;
581 p1 = p2;
582 p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000583 }
584
Chris Lattner91702092009-03-12 23:59:55 +0000585 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000586 }
587
Chris Lattner91702092009-03-12 23:59:55 +0000588 if (p1 != dst)
589 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000590
Chris Lattner91702092009-03-12 23:59:55 +0000591 return result;
592}
Neil Boothb93d90e2007-10-12 16:02:31 +0000593
Chris Lattner91702092009-03-12 23:59:55 +0000594/* Zero at the end to avoid modular arithmetic when adding one; used
595 when rounding up during hexadecimal output. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000596static const char hexDigitsLower[] = "0123456789abcdef0";
597static const char hexDigitsUpper[] = "0123456789ABCDEF0";
598static const char infinityL[] = "infinity";
599static const char infinityU[] = "INFINITY";
600static const char NaNL[] = "nan";
601static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000602
Chris Lattner91702092009-03-12 23:59:55 +0000603/* Write out an integerPart in hexadecimal, starting with the most
604 significant nibble. Write out exactly COUNT hexdigits, return
605 COUNT. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000606static unsigned int
Craig Topperc85be522017-06-18 18:15:41 +0000607partAsHex (char *dst, APFloatBase::integerPart part, unsigned int count,
Chris Lattner91702092009-03-12 23:59:55 +0000608 const char *hexDigitChars)
609{
610 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000611
Craig Topperc85be522017-06-18 18:15:41 +0000612 assert(count != 0 && count <= APFloatBase::integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000613
Craig Topperc85be522017-06-18 18:15:41 +0000614 part >>= (APFloatBase::integerPartWidth - 4 * count);
Chris Lattner91702092009-03-12 23:59:55 +0000615 while (count--) {
616 dst[count] = hexDigitChars[part & 0xf];
617 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000618 }
619
Chris Lattner91702092009-03-12 23:59:55 +0000620 return result;
621}
Neil Booth8f1946f2007-10-03 22:26:02 +0000622
Chris Lattner91702092009-03-12 23:59:55 +0000623/* Write out an unsigned decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000624static char *
Chris Lattner91702092009-03-12 23:59:55 +0000625writeUnsignedDecimal (char *dst, unsigned int n)
626{
627 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000628
Chris Lattner91702092009-03-12 23:59:55 +0000629 p = buff;
630 do
631 *p++ = '0' + n % 10;
632 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000633
Chris Lattner91702092009-03-12 23:59:55 +0000634 do
635 *dst++ = *--p;
636 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000637
Chris Lattner91702092009-03-12 23:59:55 +0000638 return dst;
639}
Neil Booth8f1946f2007-10-03 22:26:02 +0000640
Chris Lattner91702092009-03-12 23:59:55 +0000641/* Write out a signed decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000642static char *
Chris Lattner91702092009-03-12 23:59:55 +0000643writeSignedDecimal (char *dst, int value)
644{
645 if (value < 0) {
646 *dst++ = '-';
647 dst = writeUnsignedDecimal(dst, -(unsigned) value);
648 } else
649 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000650
Chris Lattner91702092009-03-12 23:59:55 +0000651 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000652}
653
Tim Shen85de51d2016-10-25 19:55:59 +0000654namespace detail {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000655/* Constructors. */
Tim Shen85de51d2016-10-25 19:55:59 +0000656void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000657 unsigned int count;
658
659 semantics = ourSemantics;
660 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000661 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000662 significand.parts = new integerPart[count];
663}
664
Tim Shen85de51d2016-10-25 19:55:59 +0000665void IEEEFloat::freeSignificand() {
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000666 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000667 delete [] significand.parts;
668}
669
Tim Shen85de51d2016-10-25 19:55:59 +0000670void IEEEFloat::assign(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000671 assert(semantics == rhs.semantics);
672
673 sign = rhs.sign;
674 category = rhs.category;
675 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000676 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000677 copySignificand(rhs);
678}
679
Tim Shen85de51d2016-10-25 19:55:59 +0000680void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
Michael Gottesman8136c382013-06-26 23:17:28 +0000681 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000682 assert(rhs.partCount() >= partCount());
683
684 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000685 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000686}
687
Neil Booth5fe658b2007-10-14 10:39:51 +0000688/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000689 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000690 which may not be ideal. If float, this is QNaN(0). */
Tim Shen85de51d2016-10-25 19:55:59 +0000691void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
Neil Booth5fe658b2007-10-14 10:39:51 +0000692 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000693 sign = Negative;
694
John McCallc12b1332010-02-28 12:49:50 +0000695 integerPart *significand = significandParts();
696 unsigned numParts = partCount();
697
John McCalldcb9a7a2010-02-28 02:51:25 +0000698 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000699 if (!fill || fill->getNumWords() < numParts)
700 APInt::tcSet(significand, 0, numParts);
701 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000702 APInt::tcAssign(significand, fill->getRawData(),
703 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000704
705 // Zero out the excess bits of the significand.
706 unsigned bitsToPreserve = semantics->precision - 1;
707 unsigned part = bitsToPreserve / 64;
708 bitsToPreserve %= 64;
709 significand[part] &= ((1ULL << bitsToPreserve) - 1);
710 for (part++; part != numParts; ++part)
711 significand[part] = 0;
712 }
713
714 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000715
716 if (SNaN) {
717 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000718 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000719
720 // If there are no bits set in the payload, we have to set
721 // *something* to make it a NaN instead of an infinity;
722 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000723 if (APInt::tcIsZero(significand, numParts))
724 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000725 } else {
726 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000727 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000728 }
John McCallc12b1332010-02-28 12:49:50 +0000729
730 // For x87 extended precision, we want to make a NaN, not a
731 // pseudo-NaN. Maybe we should expose the ability to make
732 // pseudo-NaNs?
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000733 if (semantics == &semX87DoubleExtended)
John McCallc12b1332010-02-28 12:49:50 +0000734 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000735}
736
Tim Shen85de51d2016-10-25 19:55:59 +0000737IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000738 if (this != &rhs) {
739 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000740 freeSignificand();
741 initialize(rhs.semantics);
742 }
743 assign(rhs);
744 }
745
746 return *this;
747}
748
Tim Shen85de51d2016-10-25 19:55:59 +0000749IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000750 freeSignificand();
751
752 semantics = rhs.semantics;
753 significand = rhs.significand;
754 exponent = rhs.exponent;
755 category = rhs.category;
756 sign = rhs.sign;
757
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000758 rhs.semantics = &semBogus;
Benjamin Kramer06f47782014-03-04 20:26:51 +0000759 return *this;
760}
761
Tim Shen85de51d2016-10-25 19:55:59 +0000762bool IEEEFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000763 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Simon Pilgrima2849592017-03-20 13:53:59 +0000764 (APInt::tcExtractBit(significandParts(),
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000765 semantics->precision - 1) == 0);
766}
767
Tim Shen85de51d2016-10-25 19:55:59 +0000768bool IEEEFloat::isSmallest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000769 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000770 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000771 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000772 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000773 significandMSB() == 0;
774}
775
Tim Shen85de51d2016-10-25 19:55:59 +0000776bool IEEEFloat::isSignificandAllOnes() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000777 // Test if the significand excluding the integral bit is all ones. This allows
778 // us to test for binade boundaries.
779 const integerPart *Parts = significandParts();
780 const unsigned PartCount = partCount();
781 for (unsigned i = 0; i < PartCount - 1; i++)
782 if (~Parts[i])
783 return false;
784
785 // Set the unused high bits to all ones when we compare.
786 const unsigned NumHighBits =
787 PartCount*integerPartWidth - semantics->precision + 1;
788 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
789 "fill than integerPartWidth");
790 const integerPart HighBitFill =
791 ~integerPart(0) << (integerPartWidth - NumHighBits);
792 if (~(Parts[PartCount - 1] | HighBitFill))
793 return false;
794
795 return true;
796}
797
Tim Shen85de51d2016-10-25 19:55:59 +0000798bool IEEEFloat::isSignificandAllZeros() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000799 // Test if the significand excluding the integral bit is all zeros. This
800 // allows us to test for binade boundaries.
801 const integerPart *Parts = significandParts();
802 const unsigned PartCount = partCount();
803
804 for (unsigned i = 0; i < PartCount - 1; i++)
805 if (Parts[i])
806 return false;
807
808 const unsigned NumHighBits =
809 PartCount*integerPartWidth - semantics->precision + 1;
810 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
811 "clear than integerPartWidth");
812 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
813
814 if (Parts[PartCount - 1] & HighBitMask)
815 return false;
816
817 return true;
818}
819
Tim Shen85de51d2016-10-25 19:55:59 +0000820bool IEEEFloat::isLargest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000821 // The largest number by magnitude in our format will be the floating point
822 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000823 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000824 && isSignificandAllOnes();
825}
826
Tim Shen85de51d2016-10-25 19:55:59 +0000827bool IEEEFloat::isInteger() const {
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000828 // This could be made more efficient; I'm going for obviously correct.
829 if (!isFinite()) return false;
Tim Shen85de51d2016-10-25 19:55:59 +0000830 IEEEFloat truncated = *this;
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000831 truncated.roundToIntegral(rmTowardZero);
832 return compare(truncated) == cmpEqual;
833}
834
Tim Shen85de51d2016-10-25 19:55:59 +0000835bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000836 if (this == &rhs)
837 return true;
838 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000839 category != rhs.category ||
840 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000841 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000842 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000843 return true;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000844
845 if (isFiniteNonZero() && exponent != rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000846 return false;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000847
848 return std::equal(significandParts(), significandParts() + partCount(),
849 rhs.significandParts());
Dale Johannesena719a602007-08-24 00:56:33 +0000850}
851
Tim Shen85de51d2016-10-25 19:55:59 +0000852IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000853 initialize(&ourSemantics);
854 sign = 0;
Michael Gottesman30a90eb2013-07-27 21:49:21 +0000855 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000856 zeroSignificand();
857 exponent = ourSemantics.precision - 1;
858 significandParts()[0] = value;
859 normalize(rmNearestTiesToEven, lfExactlyZero);
860}
861
Tim Shen85de51d2016-10-25 19:55:59 +0000862IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000863 initialize(&ourSemantics);
864 category = fcZero;
865 sign = false;
866}
867
Tim Shenb49915482016-10-28 22:45:33 +0000868// Delegate to the previous constructor, because later copy constructor may
869// actually inspects category, which can't be garbage.
870IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
Tim Shen1bab9cf2016-10-29 00:51:41 +0000871 : IEEEFloat(ourSemantics) {}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000872
Tim Shen85de51d2016-10-25 19:55:59 +0000873IEEEFloat::IEEEFloat(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000874 initialize(rhs.semantics);
875 assign(rhs);
876}
877
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000878IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000879 *this = std::move(rhs);
880}
881
Tim Shen85de51d2016-10-25 19:55:59 +0000882IEEEFloat::~IEEEFloat() { freeSignificand(); }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000883
Tim Shen85de51d2016-10-25 19:55:59 +0000884unsigned int IEEEFloat::partCount() const {
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000885 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000886}
887
Craig Topperc85be522017-06-18 18:15:41 +0000888const IEEEFloat::integerPart *IEEEFloat::significandParts() const {
Tim Shen85de51d2016-10-25 19:55:59 +0000889 return const_cast<IEEEFloat *>(this)->significandParts();
JF Bastiena1d3c242015-08-26 02:32:45 +0000890}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000891
Craig Topperc85be522017-06-18 18:15:41 +0000892IEEEFloat::integerPart *IEEEFloat::significandParts() {
Evan Cheng67c90212009-10-27 21:35:42 +0000893 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000894 return significand.parts;
895 else
896 return &significand.part;
897}
898
Tim Shen85de51d2016-10-25 19:55:59 +0000899void IEEEFloat::zeroSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000900 APInt::tcSet(significandParts(), 0, partCount());
901}
902
903/* Increment an fcNormal floating point number's significand. */
Tim Shen85de51d2016-10-25 19:55:59 +0000904void IEEEFloat::incrementSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000905 integerPart carry;
906
907 carry = APInt::tcIncrement(significandParts(), partCount());
908
909 /* Our callers should never cause us to overflow. */
910 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000911 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000912}
913
914/* Add the significand of the RHS. Returns the carry flag. */
Craig Topperc85be522017-06-18 18:15:41 +0000915IEEEFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000916 integerPart *parts;
917
918 parts = significandParts();
919
920 assert(semantics == rhs.semantics);
921 assert(exponent == rhs.exponent);
922
923 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
924}
925
926/* Subtract the significand of the RHS with a borrow flag. Returns
927 the borrow flag. */
Craig Topperc85be522017-06-18 18:15:41 +0000928IEEEFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
929 integerPart borrow) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000930 integerPart *parts;
931
932 parts = significandParts();
933
934 assert(semantics == rhs.semantics);
935 assert(exponent == rhs.exponent);
936
937 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000938 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000939}
940
941/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
942 on to the full-precision result of the multiplication. Returns the
943 lost fraction. */
Tim Shen85de51d2016-10-25 19:55:59 +0000944lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
945 const IEEEFloat *addend) {
Neil Booth9acbf5a2007-09-26 21:33:42 +0000946 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000947 unsigned int partsCount, newPartsCount, precision;
948 integerPart *lhsSignificand;
949 integerPart scratch[4];
950 integerPart *fullSignificand;
951 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000952 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000953
954 assert(semantics == rhs.semantics);
955
956 precision = semantics->precision;
Lang Hames56c0eb22014-11-19 19:15:41 +0000957
958 // Allocate space for twice as many bits as the original significand, plus one
959 // extra bit for the addition to overflow into.
960 newPartsCount = partCountForBits(precision * 2 + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000961
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000962 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000963 fullSignificand = new integerPart[newPartsCount];
964 else
965 fullSignificand = scratch;
966
967 lhsSignificand = significandParts();
968 partsCount = partCount();
969
970 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000971 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000972
973 lost_fraction = lfExactlyZero;
974 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
975 exponent += rhs.exponent;
976
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000977 // Assume the operands involved in the multiplication are single-precision
978 // FP, and the two multiplicants are:
979 // *this = a23 . a22 ... a0 * 2^e1
980 // rhs = b23 . b22 ... b0 * 2^e2
981 // the result of multiplication is:
Lang Hames56c0eb22014-11-19 19:15:41 +0000982 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
Simon Pilgrima2849592017-03-20 13:53:59 +0000983 // Note that there are three significant bits at the left-hand side of the
Lang Hames56c0eb22014-11-19 19:15:41 +0000984 // radix point: two for the multiplication, and an overflow bit for the
985 // addition (that will always be zero at this point). Move the radix point
986 // toward left by two bits, and adjust exponent accordingly.
987 exponent += 2;
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000988
Hal Finkel171c2ec2014-10-14 19:23:07 +0000989 if (addend && addend->isNonZero()) {
Simon Pilgrima2849592017-03-20 13:53:59 +0000990 // The intermediate result of the multiplication has "2 * precision"
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000991 // signicant bit; adjust the addend to be consistent with mul result.
992 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000993 Significand savedSignificand = significand;
994 const fltSemantics *savedSemantics = semantics;
995 fltSemantics extendedSemantics;
996 opStatus status;
997 unsigned int extendedPrecision;
998
Lang Hames56c0eb22014-11-19 19:15:41 +0000999 // Normalize our MSB to one below the top bit to allow for overflow.
1000 extendedPrecision = 2 * precision + 1;
1001 if (omsb != extendedPrecision - 1) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001002 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001003 APInt::tcShiftLeft(fullSignificand, newPartsCount,
Lang Hames56c0eb22014-11-19 19:15:41 +00001004 (extendedPrecision - 1) - omsb);
1005 exponent -= (extendedPrecision - 1) - omsb;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001006 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001007
1008 /* Create new semantics. */
1009 extendedSemantics = *semantics;
1010 extendedSemantics.precision = extendedPrecision;
1011
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001012 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001013 significand.part = fullSignificand[0];
1014 else
1015 significand.parts = fullSignificand;
1016 semantics = &extendedSemantics;
1017
Tim Shen85de51d2016-10-25 19:55:59 +00001018 IEEEFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001019 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001020 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001021 (void)status;
Lang Hames56c0eb22014-11-19 19:15:41 +00001022
1023 // Shift the significand of the addend right by one bit. This guarantees
1024 // that the high bit of the significand is zero (same as fullSignificand),
1025 // so the addition will overflow (if it does overflow at all) into the top bit.
1026 lost_fraction = extendedAddend.shiftSignificandRight(1);
1027 assert(lost_fraction == lfExactlyZero &&
1028 "Lost precision while shifting addend for fused-multiply-add.");
1029
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001030 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1031
1032 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001033 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001034 fullSignificand[0] = significand.part;
1035 significand = savedSignificand;
1036 semantics = savedSemantics;
1037
1038 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1039 }
1040
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001041 // Convert the result having "2 * precision" significant-bits back to the one
Simon Pilgrima2849592017-03-20 13:53:59 +00001042 // having "precision" significant-bits. First, move the radix point from
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001043 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1044 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
Lang Hames56c0eb22014-11-19 19:15:41 +00001045 exponent -= precision + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001046
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001047 // In case MSB resides at the left-hand side of radix point, shift the
1048 // mantissa right by some amount to make sure the MSB reside right before
1049 // the radix point (i.e. "MSB . rest-significant-bits").
1050 //
1051 // Note that the result is not normalized when "omsb < precision". So, the
Tim Shen85de51d2016-10-25 19:55:59 +00001052 // caller needs to call IEEEFloat::normalize() if normalized value is
1053 // expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001054 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001055 unsigned int bits, significantParts;
1056 lostFraction lf;
1057
1058 bits = omsb - precision;
1059 significantParts = partCountForBits(omsb);
1060 lf = shiftRight(fullSignificand, significantParts, bits);
1061 lost_fraction = combineLostFractions(lf, lost_fraction);
1062 exponent += bits;
1063 }
1064
1065 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1066
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001067 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001068 delete [] fullSignificand;
1069
1070 return lost_fraction;
1071}
1072
1073/* Multiply the significands of LHS and RHS to DST. */
Tim Shen85de51d2016-10-25 19:55:59 +00001074lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001075 unsigned int bit, i, partsCount;
1076 const integerPart *rhsSignificand;
1077 integerPart *lhsSignificand, *dividend, *divisor;
1078 integerPart scratch[4];
1079 lostFraction lost_fraction;
1080
1081 assert(semantics == rhs.semantics);
1082
1083 lhsSignificand = significandParts();
1084 rhsSignificand = rhs.significandParts();
1085 partsCount = partCount();
1086
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001087 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001088 dividend = new integerPart[partsCount * 2];
1089 else
1090 dividend = scratch;
1091
1092 divisor = dividend + partsCount;
1093
1094 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001095 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001096 dividend[i] = lhsSignificand[i];
1097 divisor[i] = rhsSignificand[i];
1098 lhsSignificand[i] = 0;
1099 }
1100
1101 exponent -= rhs.exponent;
1102
1103 unsigned int precision = semantics->precision;
1104
1105 /* Normalize the divisor. */
1106 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001107 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001108 exponent += bit;
1109 APInt::tcShiftLeft(divisor, partsCount, bit);
1110 }
1111
1112 /* Normalize the dividend. */
1113 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001114 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001115 exponent -= bit;
1116 APInt::tcShiftLeft(dividend, partsCount, bit);
1117 }
1118
Neil Boothb93d90e2007-10-12 16:02:31 +00001119 /* Ensure the dividend >= divisor initially for the loop below.
1120 Incidentally, this means that the division loop below is
1121 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001122 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001123 exponent--;
1124 APInt::tcShiftLeft(dividend, partsCount, 1);
1125 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1126 }
1127
1128 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001129 for (bit = precision; bit; bit -= 1) {
1130 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001131 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1132 APInt::tcSetBit(lhsSignificand, bit - 1);
1133 }
1134
1135 APInt::tcShiftLeft(dividend, partsCount, 1);
1136 }
1137
1138 /* Figure out the lost fraction. */
1139 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1140
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001141 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001142 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001143 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001144 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001145 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001146 lost_fraction = lfExactlyZero;
1147 else
1148 lost_fraction = lfLessThanHalf;
1149
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001150 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001151 delete [] dividend;
1152
1153 return lost_fraction;
1154}
1155
Tim Shen85de51d2016-10-25 19:55:59 +00001156unsigned int IEEEFloat::significandMSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001157 return APInt::tcMSB(significandParts(), partCount());
1158}
1159
Tim Shen85de51d2016-10-25 19:55:59 +00001160unsigned int IEEEFloat::significandLSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001161 return APInt::tcLSB(significandParts(), partCount());
1162}
1163
1164/* Note that a zero result is NOT normalized to fcZero. */
Tim Shen85de51d2016-10-25 19:55:59 +00001165lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001166 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001167 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001168
1169 exponent += bits;
1170
1171 return shiftRight(significandParts(), partCount(), bits);
1172}
1173
1174/* Shift the significand left BITS bits, subtract BITS from its exponent. */
Tim Shen85de51d2016-10-25 19:55:59 +00001175void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001176 assert(bits < semantics->precision);
1177
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001178 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001179 unsigned int partsCount = partCount();
1180
1181 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1182 exponent -= bits;
1183
1184 assert(!APInt::tcIsZero(significandParts(), partsCount));
1185 }
1186}
1187
Tim Shen85de51d2016-10-25 19:55:59 +00001188IEEEFloat::cmpResult
1189IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001190 int compare;
1191
1192 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001193 assert(isFiniteNonZero());
1194 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001195
1196 compare = exponent - rhs.exponent;
1197
1198 /* If exponents are equal, do an unsigned bignum comparison of the
1199 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001200 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001201 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001202 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001203
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001204 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001205 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001206 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001207 return cmpLessThan;
1208 else
1209 return cmpEqual;
1210}
1211
1212/* Handle overflow. Sign is preserved. We either become infinity or
1213 the largest finite number. */
Tim Shen85de51d2016-10-25 19:55:59 +00001214IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001215 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001216 if (rounding_mode == rmNearestTiesToEven ||
1217 rounding_mode == rmNearestTiesToAway ||
1218 (rounding_mode == rmTowardPositive && !sign) ||
1219 (rounding_mode == rmTowardNegative && sign)) {
1220 category = fcInfinity;
1221 return (opStatus) (opOverflow | opInexact);
1222 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001223
1224 /* Otherwise we become the largest finite number. */
1225 category = fcNormal;
1226 exponent = semantics->maxExponent;
1227 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001228 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001229
1230 return opInexact;
1231}
1232
Neil Booth1ca1f802007-10-03 15:16:41 +00001233/* Returns TRUE if, when truncating the current number, with BIT the
1234 new LSB, with the given lost fraction and rounding mode, the result
1235 would need to be rounded away from zero (i.e., by increasing the
1236 signficand). This routine must work for fcZero of both signs, and
1237 fcNormal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001238bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1239 lostFraction lost_fraction,
1240 unsigned int bit) const {
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001241 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001242 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001243
Neil Booth1ca1f802007-10-03 15:16:41 +00001244 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001245 assert(lost_fraction != lfExactlyZero);
1246
Mike Stump889285d2009-05-13 23:23:20 +00001247 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001248 case rmNearestTiesToAway:
1249 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1250
1251 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001252 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001253 return true;
1254
1255 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001256 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001257 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001258
1259 return false;
1260
1261 case rmTowardZero:
1262 return false;
1263
1264 case rmTowardPositive:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001265 return !sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001266
1267 case rmTowardNegative:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001268 return sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001269 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001270 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001271}
1272
Tim Shen85de51d2016-10-25 19:55:59 +00001273IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1274 lostFraction lost_fraction) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001275 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001276 int exponentChange;
1277
Michael Gottesman8136c382013-06-26 23:17:28 +00001278 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001279 return opOK;
1280
1281 /* Before rounding normalize the exponent of fcNormal numbers. */
1282 omsb = significandMSB() + 1;
1283
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001284 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001285 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001286 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001287 the exponent. */
1288 exponentChange = omsb - semantics->precision;
1289
1290 /* If the resulting exponent is too high, overflow according to
1291 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001292 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001293 return handleOverflow(rounding_mode);
1294
1295 /* Subnormal numbers have exponent minExponent, and their MSB
1296 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001297 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001298 exponentChange = semantics->minExponent - exponent;
1299
1300 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001301 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001302 assert(lost_fraction == lfExactlyZero);
1303
1304 shiftSignificandLeft(-exponentChange);
1305
1306 return opOK;
1307 }
1308
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001309 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001310 lostFraction lf;
1311
1312 /* Shift right and capture any new lost fraction. */
1313 lf = shiftSignificandRight(exponentChange);
1314
1315 lost_fraction = combineLostFractions(lf, lost_fraction);
1316
1317 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001318 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001319 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001320 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001321 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001322 }
1323 }
1324
1325 /* Now round the number according to rounding_mode given the lost
1326 fraction. */
1327
1328 /* As specified in IEEE 754, since we do not trap we do not report
1329 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001330 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001331 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001332 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001333 category = fcZero;
1334
1335 return opOK;
1336 }
1337
1338 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001339 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1340 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001341 exponent = semantics->minExponent;
1342
1343 incrementSignificand();
1344 omsb = significandMSB() + 1;
1345
1346 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001347 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001348 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001349 significand right one. However if we already have the
1350 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001351 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001352 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001353
Neil Booth9acbf5a2007-09-26 21:33:42 +00001354 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001355 }
1356
1357 shiftSignificandRight(1);
1358
1359 return opInexact;
1360 }
1361 }
1362
1363 /* The normal case - we were and are not denormal, and any
1364 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001365 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001366 return opInexact;
1367
1368 /* We have a non-zero denormal. */
1369 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001370
1371 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001372 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001373 category = fcZero;
1374
1375 /* The fcZero case is a denormal that underflowed to zero. */
1376 return (opStatus) (opUnderflow | opInexact);
1377}
1378
Tim Shen85de51d2016-10-25 19:55:59 +00001379IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1380 bool subtract) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001381 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001382 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001383 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001384
Michael Gottesman9b877e12013-06-24 09:57:57 +00001385 case PackCategoriesIntoKey(fcNaN, fcZero):
1386 case PackCategoriesIntoKey(fcNaN, fcNormal):
1387 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1388 case PackCategoriesIntoKey(fcNaN, fcNaN):
1389 case PackCategoriesIntoKey(fcNormal, fcZero):
1390 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1391 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001392 return opOK;
1393
Michael Gottesman9b877e12013-06-24 09:57:57 +00001394 case PackCategoriesIntoKey(fcZero, fcNaN):
1395 case PackCategoriesIntoKey(fcNormal, fcNaN):
1396 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Stephen Canond3278282014-06-08 16:53:31 +00001397 // We need to be sure to flip the sign here for subtraction because we
1398 // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1399 sign = rhs.sign ^ subtract;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001400 category = fcNaN;
1401 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001402 return opOK;
1403
Michael Gottesman9b877e12013-06-24 09:57:57 +00001404 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1405 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001406 category = fcInfinity;
1407 sign = rhs.sign ^ subtract;
1408 return opOK;
1409
Michael Gottesman9b877e12013-06-24 09:57:57 +00001410 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001411 assign(rhs);
1412 sign = rhs.sign ^ subtract;
1413 return opOK;
1414
Michael Gottesman9b877e12013-06-24 09:57:57 +00001415 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001416 /* Sign depends on rounding mode; handled by caller. */
1417 return opOK;
1418
Michael Gottesman9b877e12013-06-24 09:57:57 +00001419 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001420 /* Differently signed infinities can only be validly
1421 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001422 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001423 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001424 return opInvalidOp;
1425 }
1426
1427 return opOK;
1428
Michael Gottesman9b877e12013-06-24 09:57:57 +00001429 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001430 return opDivByZero;
1431 }
1432}
1433
1434/* Add or subtract two normal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001435lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1436 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001437 integerPart carry;
1438 lostFraction lost_fraction;
1439 int bits;
1440
1441 /* Determine if the operation on the absolute values is effectively
1442 an addition or subtraction. */
Aaron Ballmand5cc45f2015-03-24 12:47:51 +00001443 subtract ^= static_cast<bool>(sign ^ rhs.sign);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001444
1445 /* Are we bigger exponent-wise than the RHS? */
1446 bits = exponent - rhs.exponent;
1447
1448 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001449 if (subtract) {
Tim Shen85de51d2016-10-25 19:55:59 +00001450 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001451 bool reverse;
1452
Chris Lattner3da18eb2007-08-24 03:02:34 +00001453 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001454 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1455 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001456 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001457 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1458 shiftSignificandLeft(1);
1459 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001460 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001461 lost_fraction = shiftSignificandRight(-bits - 1);
1462 temp_rhs.shiftSignificandLeft(1);
1463 reverse = true;
1464 }
1465
Chris Lattner3da18eb2007-08-24 03:02:34 +00001466 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001467 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001468 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001469 copySignificand(temp_rhs);
1470 sign = !sign;
1471 } else {
1472 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001473 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001474 }
1475
1476 /* Invert the lost fraction - it was on the RHS and
1477 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001478 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001479 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001480 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001481 lost_fraction = lfLessThanHalf;
1482
1483 /* The code above is intended to ensure that no borrow is
1484 necessary. */
1485 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001486 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001487 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001488 if (bits > 0) {
Tim Shen85de51d2016-10-25 19:55:59 +00001489 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001490
1491 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1492 carry = addSignificand(temp_rhs);
1493 } else {
1494 lost_fraction = shiftSignificandRight(-bits);
1495 carry = addSignificand(rhs);
1496 }
1497
1498 /* We have a guard bit; generating a carry cannot happen. */
1499 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001500 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001501 }
1502
1503 return lost_fraction;
1504}
1505
Tim Shen85de51d2016-10-25 19:55:59 +00001506IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001507 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001508 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001509 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001510
Michael Gottesman9b877e12013-06-24 09:57:57 +00001511 case PackCategoriesIntoKey(fcNaN, fcZero):
1512 case PackCategoriesIntoKey(fcNaN, fcNormal):
1513 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1514 case PackCategoriesIntoKey(fcNaN, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001515 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001516 return opOK;
1517
Michael Gottesman9b877e12013-06-24 09:57:57 +00001518 case PackCategoriesIntoKey(fcZero, fcNaN):
1519 case PackCategoriesIntoKey(fcNormal, fcNaN):
1520 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001521 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001522 category = fcNaN;
1523 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001524 return opOK;
1525
Michael Gottesman9b877e12013-06-24 09:57:57 +00001526 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1527 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1528 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001529 category = fcInfinity;
1530 return opOK;
1531
Michael Gottesman9b877e12013-06-24 09:57:57 +00001532 case PackCategoriesIntoKey(fcZero, fcNormal):
1533 case PackCategoriesIntoKey(fcNormal, fcZero):
1534 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001535 category = fcZero;
1536 return opOK;
1537
Michael Gottesman9b877e12013-06-24 09:57:57 +00001538 case PackCategoriesIntoKey(fcZero, fcInfinity):
1539 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001540 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001541 return opInvalidOp;
1542
Michael Gottesman9b877e12013-06-24 09:57:57 +00001543 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001544 return opOK;
1545 }
1546}
1547
Tim Shen85de51d2016-10-25 19:55:59 +00001548IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001549 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001550 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001551 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001552
Michael Gottesman9b877e12013-06-24 09:57:57 +00001553 case PackCategoriesIntoKey(fcZero, fcNaN):
1554 case PackCategoriesIntoKey(fcNormal, fcNaN):
1555 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001556 category = fcNaN;
1557 copySignificand(rhs);
Galina Kistanova5c4f1a92017-05-30 03:30:34 +00001558 LLVM_FALLTHROUGH;
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001559 case PackCategoriesIntoKey(fcNaN, fcZero):
1560 case PackCategoriesIntoKey(fcNaN, fcNormal):
1561 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1562 case PackCategoriesIntoKey(fcNaN, fcNaN):
1563 sign = false;
Galina Kistanova5c4f1a92017-05-30 03:30:34 +00001564 LLVM_FALLTHROUGH;
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001565 case PackCategoriesIntoKey(fcInfinity, fcZero):
1566 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1567 case PackCategoriesIntoKey(fcZero, fcInfinity):
1568 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001569 return opOK;
1570
Michael Gottesman9b877e12013-06-24 09:57:57 +00001571 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001572 category = fcZero;
1573 return opOK;
1574
Michael Gottesman9b877e12013-06-24 09:57:57 +00001575 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001576 category = fcInfinity;
1577 return opDivByZero;
1578
Michael Gottesman9b877e12013-06-24 09:57:57 +00001579 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1580 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001581 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001582 return opInvalidOp;
1583
Michael Gottesman9b877e12013-06-24 09:57:57 +00001584 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001585 return opOK;
1586 }
1587}
1588
Tim Shen85de51d2016-10-25 19:55:59 +00001589IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001590 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001591 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001592 llvm_unreachable(nullptr);
Dale Johannesenb5721632009-01-21 00:35:19 +00001593
Michael Gottesman9b877e12013-06-24 09:57:57 +00001594 case PackCategoriesIntoKey(fcNaN, fcZero):
1595 case PackCategoriesIntoKey(fcNaN, fcNormal):
1596 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1597 case PackCategoriesIntoKey(fcNaN, fcNaN):
1598 case PackCategoriesIntoKey(fcZero, fcInfinity):
1599 case PackCategoriesIntoKey(fcZero, fcNormal):
1600 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001601 return opOK;
1602
Michael Gottesman9b877e12013-06-24 09:57:57 +00001603 case PackCategoriesIntoKey(fcZero, fcNaN):
1604 case PackCategoriesIntoKey(fcNormal, fcNaN):
1605 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001606 sign = false;
Dale Johannesenb5721632009-01-21 00:35:19 +00001607 category = fcNaN;
1608 copySignificand(rhs);
1609 return opOK;
1610
Michael Gottesman9b877e12013-06-24 09:57:57 +00001611 case PackCategoriesIntoKey(fcNormal, fcZero):
1612 case PackCategoriesIntoKey(fcInfinity, fcZero):
1613 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1614 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1615 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001616 makeNaN();
1617 return opInvalidOp;
1618
Michael Gottesman9b877e12013-06-24 09:57:57 +00001619 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001620 return opOK;
1621 }
1622}
1623
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001624/* Change sign. */
Tim Shen85de51d2016-10-25 19:55:59 +00001625void IEEEFloat::changeSign() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001626 /* Look mummy, this one's easy. */
1627 sign = !sign;
1628}
1629
1630/* Normalized addition or subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001631IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
1632 roundingMode rounding_mode,
1633 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001634 opStatus fs;
1635
1636 fs = addOrSubtractSpecials(rhs, subtract);
1637
1638 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001639 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001640 lostFraction lost_fraction;
1641
1642 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1643 fs = normalize(rounding_mode, lost_fraction);
1644
1645 /* Can only be zero if we lost no fraction. */
1646 assert(category != fcZero || lost_fraction == lfExactlyZero);
1647 }
1648
1649 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1650 positive zero unless rounding to minus infinity, except that
1651 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001652 if (category == fcZero) {
1653 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001654 sign = (rounding_mode == rmTowardNegative);
1655 }
1656
1657 return fs;
1658}
1659
1660/* Normalized addition. */
Tim Shen85de51d2016-10-25 19:55:59 +00001661IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs,
1662 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001663 return addOrSubtract(rhs, rounding_mode, false);
1664}
1665
1666/* Normalized subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001667IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs,
1668 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001669 return addOrSubtract(rhs, rounding_mode, true);
1670}
1671
1672/* Normalized multiply. */
Tim Shen85de51d2016-10-25 19:55:59 +00001673IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs,
1674 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001675 opStatus fs;
1676
1677 sign ^= rhs.sign;
1678 fs = multiplySpecials(rhs);
1679
Michael Gottesman8136c382013-06-26 23:17:28 +00001680 if (isFiniteNonZero()) {
Craig Topperc10719f2014-04-07 04:17:22 +00001681 lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001682 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001683 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001684 fs = (opStatus) (fs | opInexact);
1685 }
1686
1687 return fs;
1688}
1689
1690/* Normalized divide. */
Tim Shen85de51d2016-10-25 19:55:59 +00001691IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs,
1692 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001693 opStatus fs;
1694
1695 sign ^= rhs.sign;
1696 fs = divideSpecials(rhs);
1697
Michael Gottesman8136c382013-06-26 23:17:28 +00001698 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001699 lostFraction lost_fraction = divideSignificand(rhs);
1700 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001701 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001702 fs = (opStatus) (fs | opInexact);
1703 }
1704
1705 return fs;
1706}
1707
Dale Johannesenfe750172009-01-20 18:35:05 +00001708/* Normalized remainder. This is not currently correct in all cases. */
Tim Shen85de51d2016-10-25 19:55:59 +00001709IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) {
Dale Johannesenfe750172009-01-20 18:35:05 +00001710 opStatus fs;
Tim Shen85de51d2016-10-25 19:55:59 +00001711 IEEEFloat V = *this;
Dale Johannesenfe750172009-01-20 18:35:05 +00001712 unsigned int origSign = sign;
1713
Dale Johannesenfe750172009-01-20 18:35:05 +00001714 fs = V.divide(rhs, rmNearestTiesToEven);
1715 if (fs == opDivByZero)
1716 return fs;
1717
1718 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001719 integerPart *x = new integerPart[parts];
Dale Johannesenfe750172009-01-20 18:35:05 +00001720 bool ignored;
Simon Pilgrim00b34992017-03-20 14:40:12 +00001721 fs = V.convertToInteger(makeMutableArrayRef(x, parts),
1722 parts * integerPartWidth, true, rmNearestTiesToEven,
1723 &ignored);
1724 if (fs == opInvalidOp) {
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001725 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001726 return fs;
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001727 }
Dale Johannesenfe750172009-01-20 18:35:05 +00001728
1729 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1730 rmNearestTiesToEven);
1731 assert(fs==opOK); // should always work
1732
1733 fs = V.multiply(rhs, rmNearestTiesToEven);
1734 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1735
1736 fs = subtract(V, rmNearestTiesToEven);
1737 assert(fs==opOK || fs==opInexact); // likewise
1738
1739 if (isZero())
1740 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001741 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001742 return fs;
1743}
1744
Stephen Canon157c8692017-03-31 20:31:33 +00001745/* Normalized llvm frem (C fmod). */
Tim Shen85de51d2016-10-25 19:55:59 +00001746IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) {
Dale Johannesen689d17d2007-08-31 23:35:31 +00001747 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001748 fs = modSpecials(rhs);
Serguei Katkovf2c28512017-11-01 07:56:55 +00001749 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001750
Stephen Canon157c8692017-03-31 20:31:33 +00001751 while (isFiniteNonZero() && rhs.isFiniteNonZero() &&
1752 compareAbsoluteValue(rhs) != cmpLessThan) {
1753 IEEEFloat V = scalbn(rhs, ilogb(*this) - ilogb(rhs), rmNearestTiesToEven);
1754 if (compareAbsoluteValue(V) == cmpLessThan)
1755 V = scalbn(V, -1, rmNearestTiesToEven);
1756 V.sign = sign;
Fangrui Songf78650a2018-07-30 19:41:25 +00001757
Stephen Canonb12db0e2015-09-21 19:29:25 +00001758 fs = subtract(V, rmNearestTiesToEven);
Stephen Canon157c8692017-03-31 20:31:33 +00001759 assert(fs==opOK);
Dale Johannesenb5721632009-01-21 00:35:19 +00001760 }
Serguei Katkovf2c28512017-11-01 07:56:55 +00001761 if (isZero())
1762 sign = origSign; // fmod requires this
Dale Johannesen689d17d2007-08-31 23:35:31 +00001763 return fs;
1764}
1765
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001766/* Normalized fused-multiply-add. */
Tim Shen85de51d2016-10-25 19:55:59 +00001767IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand,
1768 const IEEEFloat &addend,
1769 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001770 opStatus fs;
1771
1772 /* Post-multiplication sign, before addition. */
1773 sign ^= multiplicand.sign;
1774
1775 /* If and only if all arguments are normal do we need to do an
1776 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001777 if (isFiniteNonZero() &&
1778 multiplicand.isFiniteNonZero() &&
Hal Finkel171c2ec2014-10-14 19:23:07 +00001779 addend.isFinite()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001780 lostFraction lost_fraction;
1781
1782 lost_fraction = multiplySignificand(multiplicand, &addend);
1783 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001784 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001785 fs = (opStatus) (fs | opInexact);
1786
1787 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1788 positive zero unless rounding to minus infinity, except that
1789 adding two like-signed zeroes gives that zero. */
Lang Hames12b12e82015-01-04 01:20:55 +00001790 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001791 sign = (rounding_mode == rmTowardNegative);
1792 } else {
1793 fs = multiplySpecials(multiplicand);
1794
1795 /* FS can only be opOK or opInvalidOp. There is no more work
1796 to do in the latter case. The IEEE-754R standard says it is
1797 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001798 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001799
1800 If we need to do the addition we can do so with normal
1801 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001802 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001803 fs = addOrSubtract(addend, rounding_mode, false);
1804 }
1805
1806 return fs;
1807}
1808
Owen Andersona40319b2012-08-13 23:32:49 +00001809/* Rounding-mode corrrect round to integral value. */
Tim Shen85de51d2016-10-25 19:55:59 +00001810IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) {
Owen Andersona40319b2012-08-13 23:32:49 +00001811 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001812
Owen Anderson352dfff2012-08-15 18:28:45 +00001813 // If the exponent is large enough, we know that this value is already
1814 // integral, and the arithmetic below would potentially cause it to saturate
1815 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001816 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001817 return opOK;
1818
Owen Andersona40319b2012-08-13 23:32:49 +00001819 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1820 // precision of our format, and then subtract it back off again. The choice
1821 // of rounding modes for the addition/subtraction determines the rounding mode
1822 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001823 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001824 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001825 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1826 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Tim Shen85de51d2016-10-25 19:55:59 +00001827 IEEEFloat MagicConstant(*semantics);
Owen Andersona40319b2012-08-13 23:32:49 +00001828 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1829 rmNearestTiesToEven);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00001830 MagicConstant.sign = sign;
Owen Anderson1ff74b02012-08-15 05:39:46 +00001831
Owen Andersona40319b2012-08-13 23:32:49 +00001832 if (fs != opOK)
1833 return fs;
1834
Owen Anderson1ff74b02012-08-15 05:39:46 +00001835 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1836 bool inputSign = isNegative();
1837
Owen Andersona40319b2012-08-13 23:32:49 +00001838 fs = add(MagicConstant, rounding_mode);
1839 if (fs != opOK && fs != opInexact)
1840 return fs;
1841
1842 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001843
1844 // Restore the input sign.
1845 if (inputSign != isNegative())
1846 changeSign();
1847
Owen Andersona40319b2012-08-13 23:32:49 +00001848 return fs;
1849}
1850
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001851
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001852/* Comparison requires normalized numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001853IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001854 cmpResult result;
1855
1856 assert(semantics == rhs.semantics);
1857
Michael Gottesman9b877e12013-06-24 09:57:57 +00001858 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001859 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001860 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001861
Michael Gottesman9b877e12013-06-24 09:57:57 +00001862 case PackCategoriesIntoKey(fcNaN, fcZero):
1863 case PackCategoriesIntoKey(fcNaN, fcNormal):
1864 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1865 case PackCategoriesIntoKey(fcNaN, fcNaN):
1866 case PackCategoriesIntoKey(fcZero, fcNaN):
1867 case PackCategoriesIntoKey(fcNormal, fcNaN):
1868 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001869 return cmpUnordered;
1870
Michael Gottesman9b877e12013-06-24 09:57:57 +00001871 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1872 case PackCategoriesIntoKey(fcInfinity, fcZero):
1873 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001874 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001875 return cmpLessThan;
1876 else
1877 return cmpGreaterThan;
1878
Michael Gottesman9b877e12013-06-24 09:57:57 +00001879 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1880 case PackCategoriesIntoKey(fcZero, fcInfinity):
1881 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001882 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001883 return cmpGreaterThan;
1884 else
1885 return cmpLessThan;
1886
Michael Gottesman9b877e12013-06-24 09:57:57 +00001887 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001888 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001889 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001890 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001891 return cmpLessThan;
1892 else
1893 return cmpGreaterThan;
1894
Michael Gottesman9b877e12013-06-24 09:57:57 +00001895 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001896 return cmpEqual;
1897
Michael Gottesman9b877e12013-06-24 09:57:57 +00001898 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001899 break;
1900 }
1901
1902 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001903 if (sign != rhs.sign) {
1904 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001905 result = cmpLessThan;
1906 else
1907 result = cmpGreaterThan;
1908 } else {
1909 /* Compare absolute values; invert result if negative. */
1910 result = compareAbsoluteValue(rhs);
1911
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001912 if (sign) {
1913 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001914 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001915 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001916 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001917 }
1918 }
1919
1920 return result;
1921}
1922
Tim Shen85de51d2016-10-25 19:55:59 +00001923/// IEEEFloat::convert - convert a value of one floating point type to another.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001924/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1925/// records whether the transformation lost information, i.e. whether
1926/// converting the result back to the original type will produce the
1927/// original value (this is almost the same as return value==fsOK, but there
1928/// are edge cases where this is not so).
1929
Tim Shen85de51d2016-10-25 19:55:59 +00001930IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics,
1931 roundingMode rounding_mode,
1932 bool *losesInfo) {
Neil Bootha8d72692007-09-22 02:56:19 +00001933 lostFraction lostFraction;
1934 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001935 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001936 int shift;
1937 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001938
Neil Bootha8d72692007-09-22 02:56:19 +00001939 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001940 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001941 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001942 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001943
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001944 bool X86SpecialNan = false;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001945 if (&fromSemantics == &semX87DoubleExtended &&
1946 &toSemantics != &semX87DoubleExtended && category == fcNaN &&
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001947 (!(*significandParts() & 0x8000000000000000ULL) ||
1948 !(*significandParts() & 0x4000000000000000ULL))) {
1949 // x86 has some unusual NaNs which cannot be represented in any other
1950 // format; note them here.
1951 X86SpecialNan = true;
1952 }
1953
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00001954 // If this is a truncation of a denormal number, and the target semantics
1955 // has larger exponent range than the source semantics (this can happen
1956 // when truncating from PowerPC double-double to double format), the
1957 // right shift could lose result mantissa bits. Adjust exponent instead
1958 // of performing excessive shift.
1959 if (shift < 0 && isFiniteNonZero()) {
1960 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1961 if (exponent + exponentChange < toSemantics.minExponent)
1962 exponentChange = toSemantics.minExponent - exponent;
1963 if (exponentChange < shift)
1964 exponentChange = shift;
1965 if (exponentChange < 0) {
1966 shift -= exponentChange;
1967 exponent += exponentChange;
1968 }
1969 }
1970
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001971 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00001972 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001973 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1974
1975 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00001976 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001977 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001978 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001979 newParts = new integerPart[newPartCount];
1980 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00001981 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001982 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001983 freeSignificand();
1984 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001985 } else if (newPartCount == 1 && oldPartCount != 1) {
1986 // Switch to built-in storage for a single part.
1987 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00001988 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001989 newPart = significandParts()[0];
1990 freeSignificand();
1991 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001992 }
1993
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001994 // Now that we have the right storage, switch the semantics.
1995 semantics = &toSemantics;
1996
1997 // If this is an extension, perform the shift now that the storage is
1998 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00001999 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002000 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2001
Michael Gottesman8136c382013-06-26 23:17:28 +00002002 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00002003 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002004 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002005 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002006 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002007
2008 // For x87 extended precision, we want to make a NaN, not a special NaN if
2009 // the input wasn't special either.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002010 if (!X86SpecialNan && semantics == &semX87DoubleExtended)
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002011 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2012
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002013 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2014 // does not give you back the same bits. This is dubious, and we
2015 // don't currently do it. You're really supposed to get
2016 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002017 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002018 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002019 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002020 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002021 }
2022
2023 return fs;
2024}
2025
2026/* Convert a floating point number to an integer according to the
2027 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002028 returns an invalid operation exception and the contents of the
2029 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002030 range but the floating point number is not the exact integer, the C
2031 standard doesn't require an inexact exception to be raised. IEEE
2032 854 does require it so we do that.
2033
2034 Note that for conversions to integer type the C standard requires
2035 round-to-zero to always be used. */
Tim Shen85de51d2016-10-25 19:55:59 +00002036IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
Simon Pilgrim00b34992017-03-20 14:40:12 +00002037 MutableArrayRef<integerPart> parts, unsigned int width, bool isSigned,
Tim Shen85de51d2016-10-25 19:55:59 +00002038 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002039 lostFraction lost_fraction;
2040 const integerPart *src;
2041 unsigned int dstPartsCount, truncatedBits;
2042
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002043 *isExact = false;
2044
Neil Booth618d0fc2007-11-01 22:43:37 +00002045 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002046 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002047 return opInvalidOp;
2048
2049 dstPartsCount = partCountForBits(width);
Simon Pilgrim00b34992017-03-20 14:40:12 +00002050 assert(dstPartsCount <= parts.size() && "Integer too big");
Neil Booth618d0fc2007-11-01 22:43:37 +00002051
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002052 if (category == fcZero) {
Simon Pilgrim00b34992017-03-20 14:40:12 +00002053 APInt::tcSet(parts.data(), 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002054 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002055 *isExact = !sign;
2056 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002057 }
2058
2059 src = significandParts();
2060
2061 /* Step 1: place our absolute value, with any fraction truncated, in
2062 the destination. */
2063 if (exponent < 0) {
2064 /* Our absolute value is less than one; truncate everything. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002065 APInt::tcSet(parts.data(), 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002066 /* For exponent -1 the integer bit represents .5, look at that.
2067 For smaller exponents leftmost truncated bit is 0. */
2068 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002069 } else {
2070 /* We want the most significant (exponent + 1) bits; the rest are
2071 truncated. */
2072 unsigned int bits = exponent + 1U;
2073
2074 /* Hopelessly large in magnitude? */
2075 if (bits > width)
2076 return opInvalidOp;
2077
2078 if (bits < semantics->precision) {
2079 /* We truncate (semantics->precision - bits) bits. */
2080 truncatedBits = semantics->precision - bits;
Simon Pilgrim00b34992017-03-20 14:40:12 +00002081 APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits);
Neil Booth618d0fc2007-11-01 22:43:37 +00002082 } else {
2083 /* We want at least as many bits as are available. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002084 APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision,
2085 0);
2086 APInt::tcShiftLeft(parts.data(), dstPartsCount,
2087 bits - semantics->precision);
Neil Booth618d0fc2007-11-01 22:43:37 +00002088 truncatedBits = 0;
2089 }
2090 }
2091
2092 /* Step 2: work out any lost fraction, and increment the absolute
2093 value if we would round away from zero. */
2094 if (truncatedBits) {
2095 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2096 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002097 if (lost_fraction != lfExactlyZero &&
2098 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Simon Pilgrim00b34992017-03-20 14:40:12 +00002099 if (APInt::tcIncrement(parts.data(), dstPartsCount))
Neil Booth618d0fc2007-11-01 22:43:37 +00002100 return opInvalidOp; /* Overflow. */
2101 }
2102 } else {
2103 lost_fraction = lfExactlyZero;
2104 }
2105
2106 /* Step 3: check if we fit in the destination. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002107 unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1;
Neil Booth618d0fc2007-11-01 22:43:37 +00002108
2109 if (sign) {
2110 if (!isSigned) {
2111 /* Negative numbers cannot be represented as unsigned. */
2112 if (omsb != 0)
2113 return opInvalidOp;
2114 } else {
2115 /* It takes omsb bits to represent the unsigned integer value.
2116 We lose a bit for the sign, but care is needed as the
2117 maximally negative integer is a special case. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002118 if (omsb == width &&
2119 APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb)
Neil Booth618d0fc2007-11-01 22:43:37 +00002120 return opInvalidOp;
2121
2122 /* This case can happen because of rounding. */
2123 if (omsb > width)
2124 return opInvalidOp;
2125 }
2126
Simon Pilgrim00b34992017-03-20 14:40:12 +00002127 APInt::tcNegate (parts.data(), dstPartsCount);
Neil Booth618d0fc2007-11-01 22:43:37 +00002128 } else {
2129 if (omsb >= width + !isSigned)
2130 return opInvalidOp;
2131 }
2132
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002133 if (lost_fraction == lfExactlyZero) {
2134 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002135 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002136 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002137 return opInexact;
2138}
2139
2140/* Same as convertToSignExtendedInteger, except we provide
2141 deterministic values in case of an invalid operation exception,
2142 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002143 for underflow or overflow.
2144 The *isExact output tells whether the result is exact, in the sense
2145 that converting it back to the original floating point type produces
2146 the original value. This is almost equivalent to result==opOK,
2147 except for negative zeroes.
2148*/
Simon Pilgrim00b34992017-03-20 14:40:12 +00002149IEEEFloat::opStatus
2150IEEEFloat::convertToInteger(MutableArrayRef<integerPart> parts,
2151 unsigned int width, bool isSigned,
2152 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002153 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002154
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002155 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002156 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002157
Neil Booth618d0fc2007-11-01 22:43:37 +00002158 if (fs == opInvalidOp) {
2159 unsigned int bits, dstPartsCount;
2160
2161 dstPartsCount = partCountForBits(width);
Simon Pilgrim00b34992017-03-20 14:40:12 +00002162 assert(dstPartsCount <= parts.size() && "Integer too big");
Neil Booth618d0fc2007-11-01 22:43:37 +00002163
2164 if (category == fcNaN)
2165 bits = 0;
2166 else if (sign)
2167 bits = isSigned;
2168 else
2169 bits = width - isSigned;
2170
Simon Pilgrim00b34992017-03-20 14:40:12 +00002171 APInt::tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits);
Neil Booth618d0fc2007-11-01 22:43:37 +00002172 if (sign && isSigned)
Simon Pilgrim00b34992017-03-20 14:40:12 +00002173 APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002174 }
2175
Neil Booth618d0fc2007-11-01 22:43:37 +00002176 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002177}
2178
Neil Booth6c1c8582007-10-07 12:07:53 +00002179/* Convert an unsigned integer SRC to a floating point number,
2180 rounding according to ROUNDING_MODE. The sign of the floating
2181 point number is not modified. */
Tim Shen85de51d2016-10-25 19:55:59 +00002182IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2183 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
Neil Booth49c6aab2007-10-08 14:39:42 +00002184 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002185 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002186 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002187
2188 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002189 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002190 dst = significandParts();
2191 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002192 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002193
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002194 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002195 be that many; extract what we can. */
2196 if (precision <= omsb) {
2197 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002198 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002199 omsb - precision);
2200 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2201 } else {
2202 exponent = precision - 1;
2203 lost_fraction = lfExactlyZero;
2204 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002205 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002206
2207 return normalize(rounding_mode, lost_fraction);
2208}
2209
Tim Shen85de51d2016-10-25 19:55:59 +00002210IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned,
2211 roundingMode rounding_mode) {
Dan Gohman35723eb2008-02-29 01:26:11 +00002212 unsigned int partCount = Val.getNumWords();
2213 APInt api = Val;
2214
2215 sign = false;
2216 if (isSigned && api.isNegative()) {
2217 sign = true;
2218 api = -api;
2219 }
2220
2221 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2222}
2223
Neil Booth03f58ab2007-10-07 12:15:41 +00002224/* Convert a two's complement integer SRC to a floating point number,
2225 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2226 integer is signed, in which case it must be sign-extended. */
Tim Shen85de51d2016-10-25 19:55:59 +00002227IEEEFloat::opStatus
2228IEEEFloat::convertFromSignExtendedInteger(const integerPart *src,
2229 unsigned int srcCount, bool isSigned,
2230 roundingMode rounding_mode) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002231 opStatus status;
2232
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002233 if (isSigned &&
2234 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002235 integerPart *copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002236
2237 /* If we're signed and negative negate a copy. */
2238 sign = true;
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002239 copy = new integerPart[srcCount];
Neil Booth03f58ab2007-10-07 12:15:41 +00002240 APInt::tcAssign(copy, src, srcCount);
2241 APInt::tcNegate(copy, srcCount);
2242 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002243 delete [] copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002244 } else {
2245 sign = false;
2246 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2247 }
2248
2249 return status;
2250}
2251
Neil Booth5f009732007-10-07 11:45:55 +00002252/* FIXME: should this just take a const APInt reference? */
Tim Shen85de51d2016-10-25 19:55:59 +00002253IEEEFloat::opStatus
2254IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2255 unsigned int width, bool isSigned,
2256 roundingMode rounding_mode) {
Dale Johannesen42305122007-09-21 22:09:37 +00002257 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002258 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002259
2260 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002261 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002262 sign = true;
2263 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002264 }
2265
Neil Boothba205222007-10-07 12:10:57 +00002266 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002267}
2268
Tim Shen85de51d2016-10-25 19:55:59 +00002269IEEEFloat::opStatus
2270IEEEFloat::convertFromHexadecimalString(StringRef s,
2271 roundingMode rounding_mode) {
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002272 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002273
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002274 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002275 zeroSignificand();
2276 exponent = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002277
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002278 integerPart *significand = significandParts();
2279 unsigned partsCount = partCount();
2280 unsigned bitPos = partsCount * integerPartWidth;
2281 bool computedTrailingFraction = false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002282
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002283 // Skip leading zeroes and any (hexa)decimal point.
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002284 StringRef::iterator begin = s.begin();
2285 StringRef::iterator end = s.end();
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002286 StringRef::iterator dot;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002287 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002288 StringRef::iterator firstSignificantDigit = p;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002289
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002290 while (p != end) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002291 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002292
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002293 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002294 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002295 dot = p++;
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002296 continue;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002297 }
2298
2299 hex_value = hexDigitValue(*p);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002300 if (hex_value == -1U)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002301 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002302
2303 p++;
2304
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002305 // Store the number while we have space.
2306 if (bitPos) {
2307 bitPos -= 4;
2308 hex_value <<= bitPos % integerPartWidth;
2309 significand[bitPos / integerPartWidth] |= hex_value;
2310 } else if (!computedTrailingFraction) {
2311 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2312 computedTrailingFraction = true;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002313 }
2314 }
2315
2316 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002317 assert(p != end && "Hex strings require an exponent");
2318 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2319 assert(p != begin && "Significand has no digits");
2320 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002321
2322 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002323 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002324 int expAdjustment;
2325
2326 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002327 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002328 dot = p;
2329
2330 /* Calculate the exponent adjustment implicit in the number of
2331 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002332 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002333 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002334 expAdjustment++;
2335 expAdjustment = expAdjustment * 4 - 1;
2336
2337 /* Adjust for writing the significand starting at the most
2338 significant nibble. */
2339 expAdjustment += semantics->precision;
2340 expAdjustment -= partsCount * integerPartWidth;
2341
2342 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002343 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002344 }
2345
2346 return normalize(rounding_mode, lost_fraction);
2347}
2348
Tim Shen85de51d2016-10-25 19:55:59 +00002349IEEEFloat::opStatus
2350IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2351 unsigned sigPartCount, int exp,
2352 roundingMode rounding_mode) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002353 unsigned int parts, pow5PartCount;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00002354 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002355 integerPart pow5Parts[maxPowerOfFiveParts];
2356 bool isNearest;
2357
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002358 isNearest = (rounding_mode == rmNearestTiesToEven ||
2359 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002360
2361 parts = partCountForBits(semantics->precision + 11);
2362
2363 /* Calculate pow(5, abs(exp)). */
2364 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2365
2366 for (;; parts *= 2) {
2367 opStatus sigStatus, powStatus;
2368 unsigned int excessPrecision, truncatedBits;
2369
2370 calcSemantics.precision = parts * integerPartWidth - 1;
2371 excessPrecision = calcSemantics.precision - semantics->precision;
2372 truncatedBits = excessPrecision;
2373
Tim Shen139a58f2016-10-27 22:52:40 +00002374 IEEEFloat decSig(calcSemantics, uninitialized);
2375 decSig.makeZero(sign);
Tim Shen85de51d2016-10-25 19:55:59 +00002376 IEEEFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002377
2378 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2379 rmNearestTiesToEven);
2380 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2381 rmNearestTiesToEven);
2382 /* Add exp, as 10^n = 5^n * 2^n. */
2383 decSig.exponent += exp;
2384
2385 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002386 integerPart HUerr, HUdistance;
2387 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002388
2389 if (exp >= 0) {
2390 /* multiplySignificand leaves the precision-th bit set to 1. */
Craig Topperc10719f2014-04-07 04:17:22 +00002391 calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
Neil Boothb93d90e2007-10-12 16:02:31 +00002392 powHUerr = powStatus != opOK;
2393 } else {
2394 calcLostFraction = decSig.divideSignificand(pow5);
2395 /* Denormal numbers have less precision. */
2396 if (decSig.exponent < semantics->minExponent) {
2397 excessPrecision += (semantics->minExponent - decSig.exponent);
2398 truncatedBits = excessPrecision;
2399 if (excessPrecision > calcSemantics.precision)
2400 excessPrecision = calcSemantics.precision;
2401 }
2402 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002403 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002404 }
2405
2406 /* Both multiplySignificand and divideSignificand return the
2407 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002408 assert(APInt::tcExtractBit
2409 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002410
2411 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2412 powHUerr);
2413 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2414 excessPrecision, isNearest);
2415
2416 /* Are we guaranteed to round correctly if we truncate? */
2417 if (HUdistance >= HUerr) {
2418 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2419 calcSemantics.precision - excessPrecision,
2420 excessPrecision);
2421 /* Take the exponent of decSig. If we tcExtract-ed less bits
2422 above we must adjust our exponent to compensate for the
2423 implicit right shift. */
2424 exponent = (decSig.exponent + semantics->precision
2425 - (calcSemantics.precision - excessPrecision));
2426 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2427 decSig.partCount(),
2428 truncatedBits);
2429 return normalize(rounding_mode, calcLostFraction);
2430 }
2431 }
2432}
2433
Tim Shen85de51d2016-10-25 19:55:59 +00002434IEEEFloat::opStatus
2435IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
Neil Booth4ed401b2007-10-14 10:16:12 +00002436 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002437 opStatus fs;
2438
Neil Booth4ed401b2007-10-14 10:16:12 +00002439 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002440 StringRef::iterator p = str.begin();
2441 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002442
Neil Booth91305512007-10-15 15:00:55 +00002443 /* Handle the quick cases. First the case of no significant digits,
2444 i.e. zero, and then exponents that are obviously too large or too
2445 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2446 definitely overflows if
2447
2448 (exp - 1) * L >= maxExponent
2449
2450 and definitely underflows to zero where
2451
2452 (exp + 1) * L <= minExponent - precision
2453
2454 With integer arithmetic the tightest bounds for L are
2455
2456 93/28 < L < 196/59 [ numerator <= 256 ]
2457 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2458 */
2459
Michael Gottesman228156c2013-07-01 23:54:08 +00002460 // Test if we have a zero number allowing for strings with no null terminators
2461 // and zero decimals with non-zero exponents.
Simon Pilgrima2849592017-03-20 13:53:59 +00002462 //
Michael Gottesman228156c2013-07-01 23:54:08 +00002463 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2464 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2465 // be at most one dot. On the other hand, if we have a zero with a non-zero
2466 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002467 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002468 category = fcZero;
2469 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002470
2471 /* Check whether the normalized exponent is high enough to overflow
2472 max during the log-rebasing in the max-exponent check below. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002473 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
John McCallb42cc682010-02-26 22:20:41 +00002474 fs = handleOverflow(rounding_mode);
2475
2476 /* If it wasn't, then it also wasn't high enough to overflow max
2477 during the log-rebasing in the min-exponent check. Check that it
2478 won't overflow min in either check, then perform the min-exponent
2479 check. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002480 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
John McCallb42cc682010-02-26 22:20:41 +00002481 (D.normalizedExponent + 1) * 28738 <=
2482 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002483 /* Underflow to zero and round. */
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002484 category = fcNormal;
Neil Booth91305512007-10-15 15:00:55 +00002485 zeroSignificand();
2486 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002487
2488 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002489 } else if ((D.normalizedExponent - 1) * 42039
2490 >= 12655 * semantics->maxExponent) {
2491 /* Overflow and round. */
2492 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002493 } else {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002494 integerPart *decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002495 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002496
Neil Booth4ed401b2007-10-14 10:16:12 +00002497 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002498 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002499 to hold the full significand, and an extra part required by
2500 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002501 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002502 partCount = partCountForBits(1 + 196 * partCount / 59);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002503 decSignificand = new integerPart[partCount + 1];
Neil Booth4ed401b2007-10-14 10:16:12 +00002504 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002505
Neil Booth4ed401b2007-10-14 10:16:12 +00002506 /* Convert to binary efficiently - we do almost all multiplication
2507 in an integerPart. When this would overflow do we do a single
2508 bignum multiplication, and then revert again to multiplication
2509 in an integerPart. */
2510 do {
2511 integerPart decValue, val, multiplier;
2512
2513 val = 0;
2514 multiplier = 1;
2515
2516 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002517 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002518 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002519 if (p == str.end()) {
2520 break;
2521 }
2522 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002523 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002524 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002525 multiplier *= 10;
2526 val = val * 10 + decValue;
2527 /* The maximum number that can be multiplied by ten with any
2528 digit added without overflowing an integerPart. */
2529 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2530
2531 /* Multiply out the current part. */
2532 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2533 partCount, partCount + 1, false);
2534
2535 /* If we used another part (likely but not guaranteed), increase
2536 the count. */
2537 if (decSignificand[partCount])
2538 partCount++;
2539 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002540
Neil Boothae077d22007-11-01 22:51:07 +00002541 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002542 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002543 D.exponent, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002544
2545 delete [] decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002546 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002547
2548 return fs;
2549}
2550
Tim Shen85de51d2016-10-25 19:55:59 +00002551bool IEEEFloat::convertFromStringSpecials(StringRef str) {
Serguei Katkov768d6dd2017-12-19 04:27:39 +00002552 if (str.equals("inf") || str.equals("INFINITY") || str.equals("+Inf")) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002553 makeInf(false);
2554 return true;
2555 }
2556
Serguei Katkov768d6dd2017-12-19 04:27:39 +00002557 if (str.equals("-inf") || str.equals("-INFINITY") || str.equals("-Inf")) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002558 makeInf(true);
2559 return true;
2560 }
2561
2562 if (str.equals("nan") || str.equals("NaN")) {
2563 makeNaN(false, false);
2564 return true;
2565 }
2566
2567 if (str.equals("-nan") || str.equals("-NaN")) {
2568 makeNaN(false, true);
2569 return true;
2570 }
2571
2572 return false;
2573}
2574
Tim Shen85de51d2016-10-25 19:55:59 +00002575IEEEFloat::opStatus IEEEFloat::convertFromString(StringRef str,
2576 roundingMode rounding_mode) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002577 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002578
Michael Gottesman40e8a182013-06-24 09:58:05 +00002579 // Handle special cases.
2580 if (convertFromStringSpecials(str))
2581 return opOK;
2582
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002583 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002584 StringRef::iterator p = str.begin();
2585 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002586 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002587 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002588 p++;
2589 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002590 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002591 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002592
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002593 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002594 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002595 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002596 rounding_mode);
2597 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002598
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002599 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002600}
Dale Johannesena719a602007-08-24 00:56:33 +00002601
Neil Booth8f1946f2007-10-03 22:26:02 +00002602/* Write out a hexadecimal representation of the floating point value
2603 to DST, which must be of sufficient size, in the C99 form
2604 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2605 excluding the terminating NUL.
2606
2607 If UPPERCASE, the output is in upper case, otherwise in lower case.
2608
2609 HEXDIGITS digits appear altogether, rounding the value if
2610 necessary. If HEXDIGITS is 0, the minimal precision to display the
2611 number precisely is used instead. If nothing would appear after
2612 the decimal point it is suppressed.
2613
2614 The decimal exponent is always printed and has at least one digit.
2615 Zero values display an exponent of zero. Infinities and NaNs
2616 appear as "infinity" or "nan" respectively.
2617
2618 The above rules are as specified by C99. There is ambiguity about
2619 what the leading hexadecimal digit should be. This implementation
2620 uses whatever is necessary so that the exponent is displayed as
2621 stored. This implies the exponent will fall within the IEEE format
2622 range, and the leading hexadecimal digit will be 0 (for denormals),
2623 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2624 any other digits zero).
2625*/
Tim Shen85de51d2016-10-25 19:55:59 +00002626unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
2627 bool upperCase,
2628 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002629 char *p;
2630
2631 p = dst;
2632 if (sign)
2633 *dst++ = '-';
2634
2635 switch (category) {
2636 case fcInfinity:
2637 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2638 dst += sizeof infinityL - 1;
2639 break;
2640
2641 case fcNaN:
2642 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2643 dst += sizeof NaNU - 1;
2644 break;
2645
2646 case fcZero:
2647 *dst++ = '0';
2648 *dst++ = upperCase ? 'X': 'x';
2649 *dst++ = '0';
2650 if (hexDigits > 1) {
2651 *dst++ = '.';
2652 memset (dst, '0', hexDigits - 1);
2653 dst += hexDigits - 1;
2654 }
2655 *dst++ = upperCase ? 'P': 'p';
2656 *dst++ = '0';
2657 break;
2658
2659 case fcNormal:
2660 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2661 break;
2662 }
2663
2664 *dst = 0;
2665
Evan Cheng82b9e962008-05-02 21:15:08 +00002666 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002667}
2668
2669/* Does the hard work of outputting the correctly rounded hexadecimal
2670 form of a normal floating point number with the specified number of
2671 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2672 digits necessary to print the value precisely is output. */
Tim Shen85de51d2016-10-25 19:55:59 +00002673char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2674 bool upperCase,
2675 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002676 unsigned int count, valueBits, shift, partsCount, outputDigits;
2677 const char *hexDigitChars;
2678 const integerPart *significand;
2679 char *p;
2680 bool roundUp;
2681
2682 *dst++ = '0';
2683 *dst++ = upperCase ? 'X': 'x';
2684
2685 roundUp = false;
2686 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2687
2688 significand = significandParts();
2689 partsCount = partCount();
2690
2691 /* +3 because the first digit only uses the single integer bit, so
2692 we have 3 virtual zero most-significant-bits. */
2693 valueBits = semantics->precision + 3;
2694 shift = integerPartWidth - valueBits % integerPartWidth;
2695
2696 /* The natural number of digits required ignoring trailing
2697 insignificant zeroes. */
2698 outputDigits = (valueBits - significandLSB () + 3) / 4;
2699
2700 /* hexDigits of zero means use the required number for the
2701 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002702 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002703 if (hexDigits) {
2704 if (hexDigits < outputDigits) {
2705 /* We are dropping non-zero bits, so need to check how to round.
2706 "bits" is the number of dropped bits. */
2707 unsigned int bits;
2708 lostFraction fraction;
2709
2710 bits = valueBits - hexDigits * 4;
2711 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2712 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2713 }
2714 outputDigits = hexDigits;
2715 }
2716
2717 /* Write the digits consecutively, and start writing in the location
2718 of the hexadecimal point. We move the most significant digit
2719 left and add the hexadecimal point later. */
2720 p = ++dst;
2721
2722 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2723
2724 while (outputDigits && count) {
2725 integerPart part;
2726
2727 /* Put the most significant integerPartWidth bits in "part". */
2728 if (--count == partsCount)
2729 part = 0; /* An imaginary higher zero part. */
2730 else
2731 part = significand[count] << shift;
2732
2733 if (count && shift)
2734 part |= significand[count - 1] >> (integerPartWidth - shift);
2735
2736 /* Convert as much of "part" to hexdigits as we can. */
2737 unsigned int curDigits = integerPartWidth / 4;
2738
2739 if (curDigits > outputDigits)
2740 curDigits = outputDigits;
2741 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2742 outputDigits -= curDigits;
2743 }
2744
2745 if (roundUp) {
2746 char *q = dst;
2747
2748 /* Note that hexDigitChars has a trailing '0'. */
2749 do {
2750 q--;
2751 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002752 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002753 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002754 } else {
2755 /* Add trailing zeroes. */
2756 memset (dst, '0', outputDigits);
2757 dst += outputDigits;
2758 }
2759
2760 /* Move the most significant digit to before the point, and if there
2761 is something after the decimal point add it. This must come
2762 after rounding above. */
2763 p[-1] = p[0];
2764 if (dst -1 == p)
2765 dst--;
2766 else
2767 p[0] = '.';
2768
2769 /* Finally output the exponent. */
2770 *dst++ = upperCase ? 'P': 'p';
2771
Neil Booth32897f52007-10-06 07:29:25 +00002772 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002773}
2774
Tim Shen85de51d2016-10-25 19:55:59 +00002775hash_code hash_value(const IEEEFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002776 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002777 return hash_combine((uint8_t)Arg.category,
2778 // NaN has no sign, fix it at zero.
2779 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2780 Arg.semantics->precision);
2781
2782 // Normal floats need their exponent and significand hashed.
2783 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2784 Arg.semantics->precision, Arg.exponent,
2785 hash_combine_range(
2786 Arg.significandParts(),
2787 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002788}
2789
2790// Conversion from APFloat to/from host float/double. It may eventually be
2791// possible to eliminate these and have everybody deal with APFloats, but that
2792// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002793// Current implementation requires integerPartWidth==64, which is correct at
2794// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002795
Dale Johannesen728687c2007-09-05 20:39:49 +00002796// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002797// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002798
Tim Shen85de51d2016-10-25 19:55:59 +00002799APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002800 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002801 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002802
2803 uint64_t myexponent, mysignificand;
2804
Michael Gottesman8136c382013-06-26 23:17:28 +00002805 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002806 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002807 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002808 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2809 myexponent = 0; // denormal
2810 } else if (category==fcZero) {
2811 myexponent = 0;
2812 mysignificand = 0;
2813 } else if (category==fcInfinity) {
2814 myexponent = 0x7fff;
2815 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002816 } else {
2817 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002818 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002819 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002820 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002821
2822 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002823 words[0] = mysignificand;
2824 words[1] = ((uint64_t)(sign & 1) << 15) |
2825 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002826 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002827}
2828
Tim Shen85de51d2016-10-25 19:55:59 +00002829APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00002830 assert(semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy);
Evan Cheng67c90212009-10-27 21:35:42 +00002831 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002832
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002833 uint64_t words[2];
2834 opStatus fs;
2835 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002836
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002837 // Convert number to double. To avoid spurious underflows, we re-
2838 // normalize against the "double" minExponent first, and only *then*
2839 // truncate the mantissa. The result of that second conversion
2840 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002841 // Declare fltSemantics before APFloat that uses it (and
2842 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002843 fltSemantics extendedSemantics = *semantics;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002844 extendedSemantics.minExponent = semIEEEdouble.minExponent;
Tim Shen85de51d2016-10-25 19:55:59 +00002845 IEEEFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002846 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2847 assert(fs == opOK && !losesInfo);
2848 (void)fs;
2849
Tim Shen85de51d2016-10-25 19:55:59 +00002850 IEEEFloat u(extended);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002851 fs = u.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002852 assert(fs == opOK || fs == opInexact);
2853 (void)fs;
2854 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2855
2856 // If conversion was exact or resulted in a special case, we're done;
2857 // just set the second double to zero. Otherwise, re-convert back to
2858 // the extended format and compute the difference. This now should
2859 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002860 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002861 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2862 assert(fs == opOK && !losesInfo);
2863 (void)fs;
2864
Tim Shen85de51d2016-10-25 19:55:59 +00002865 IEEEFloat v(extended);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002866 v.subtract(u, rmNearestTiesToEven);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002867 fs = v.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002868 assert(fs == opOK && !losesInfo);
2869 (void)fs;
2870 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002871 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002872 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002873 }
2874
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002875 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002876}
2877
Tim Shen85de51d2016-10-25 19:55:59 +00002878APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002879 assert(semantics == (const llvm::fltSemantics*)&semIEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002880 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002881
2882 uint64_t myexponent, mysignificand, mysignificand2;
2883
Michael Gottesman8136c382013-06-26 23:17:28 +00002884 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002885 myexponent = exponent+16383; //bias
2886 mysignificand = significandParts()[0];
2887 mysignificand2 = significandParts()[1];
2888 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2889 myexponent = 0; // denormal
2890 } else if (category==fcZero) {
2891 myexponent = 0;
2892 mysignificand = mysignificand2 = 0;
2893 } else if (category==fcInfinity) {
2894 myexponent = 0x7fff;
2895 mysignificand = mysignificand2 = 0;
2896 } else {
2897 assert(category == fcNaN && "Unknown category!");
2898 myexponent = 0x7fff;
2899 mysignificand = significandParts()[0];
2900 mysignificand2 = significandParts()[1];
2901 }
2902
2903 uint64_t words[2];
2904 words[0] = mysignificand;
2905 words[1] = ((uint64_t)(sign & 1) << 63) |
2906 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002907 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002908
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002909 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002910}
2911
Tim Shen85de51d2016-10-25 19:55:59 +00002912APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002913 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002914 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002915
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002916 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002917
Michael Gottesman8136c382013-06-26 23:17:28 +00002918 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002919 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002920 mysignificand = *significandParts();
2921 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2922 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002923 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002924 myexponent = 0;
2925 mysignificand = 0;
2926 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002927 myexponent = 0x7ff;
2928 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002929 } else {
2930 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002931 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002932 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002933 }
Dale Johannesena719a602007-08-24 00:56:33 +00002934
Evan Cheng82b9e962008-05-02 21:15:08 +00002935 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002936 ((myexponent & 0x7ff) << 52) |
2937 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002938}
2939
Tim Shen85de51d2016-10-25 19:55:59 +00002940APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002941 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002942 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002943
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002944 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002945
Michael Gottesman8136c382013-06-26 23:17:28 +00002946 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002947 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00002948 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00002949 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00002950 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002951 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002952 myexponent = 0;
2953 mysignificand = 0;
2954 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002955 myexponent = 0xff;
2956 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002957 } else {
2958 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00002959 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00002960 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002961 }
Dale Johannesena719a602007-08-24 00:56:33 +00002962
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002963 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2964 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00002965}
2966
Tim Shen85de51d2016-10-25 19:55:59 +00002967APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002968 assert(semantics == (const llvm::fltSemantics*)&semIEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00002969 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00002970
2971 uint32_t myexponent, mysignificand;
2972
Michael Gottesman8136c382013-06-26 23:17:28 +00002973 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00002974 myexponent = exponent+15; //bias
2975 mysignificand = (uint32_t)*significandParts();
2976 if (myexponent == 1 && !(mysignificand & 0x400))
2977 myexponent = 0; // denormal
2978 } else if (category==fcZero) {
2979 myexponent = 0;
2980 mysignificand = 0;
2981 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00002982 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002983 mysignificand = 0;
2984 } else {
2985 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00002986 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002987 mysignificand = (uint32_t)*significandParts();
2988 }
2989
2990 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2991 (mysignificand & 0x3ff)));
2992}
2993
Dale Johannesen007aa372007-10-11 18:07:22 +00002994// This function creates an APInt that is just a bit map of the floating
2995// point constant as it would appear in memory. It is not a conversion,
2996// and treating the result as a normal integer is unlikely to be useful.
2997
Tim Shen85de51d2016-10-25 19:55:59 +00002998APInt IEEEFloat::bitcastToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002999 if (semantics == (const llvm::fltSemantics*)&semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003000 return convertHalfAPFloatToAPInt();
3001
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003002 if (semantics == (const llvm::fltSemantics*)&semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003003 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003004
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003005 if (semantics == (const llvm::fltSemantics*)&semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003006 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003007
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003008 if (semantics == (const llvm::fltSemantics*)&semIEEEquad)
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003009 return convertQuadrupleAPFloatToAPInt();
3010
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003011 if (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy)
Dale Johannesen007aa372007-10-11 18:07:22 +00003012 return convertPPCDoubleDoubleAPFloatToAPInt();
3013
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003014 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003015 "unknown format!");
3016 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003017}
3018
Tim Shen85de51d2016-10-25 19:55:59 +00003019float IEEEFloat::convertToFloat() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003020 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle &&
Chris Lattner688f9912009-09-24 21:44:20 +00003021 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003022 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003023 return api.bitsToFloat();
3024}
3025
Tim Shen85de51d2016-10-25 19:55:59 +00003026double IEEEFloat::convertToDouble() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003027 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble &&
Chris Lattner688f9912009-09-24 21:44:20 +00003028 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003029 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003030 return api.bitsToDouble();
3031}
3032
Dale Johannesenfff29952008-10-06 18:22:29 +00003033/// Integer bit is explicit in this format. Intel hardware (387 and later)
3034/// does not support these bit patterns:
3035/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3036/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
Dale Johannesenfff29952008-10-06 18:22:29 +00003037/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003038/// exponent = 0, integer bit 1 ("pseudodenormal")
3039/// At the moment, the first three are treated as NaNs, the last one as Normal.
Tim Shen85de51d2016-10-25 19:55:59 +00003040void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003041 assert(api.getBitWidth()==80);
3042 uint64_t i1 = api.getRawData()[0];
3043 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003044 uint64_t myexponent = (i2 & 0x7fff);
3045 uint64_t mysignificand = i1;
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003046 uint8_t myintegerbit = mysignificand >> 63;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003047
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003048 initialize(&semX87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003049 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003050
Dale Johannesen93eefa02009-03-23 21:16:53 +00003051 sign = static_cast<unsigned int>(i2>>15);
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003052 if (myexponent == 0 && mysignificand == 0) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003053 // exponent, significand meaningless
3054 category = fcZero;
3055 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3056 // exponent, significand meaningless
3057 category = fcInfinity;
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003058 } else if ((myexponent == 0x7fff && mysignificand != 0x8000000000000000ULL) ||
3059 (myexponent != 0x7fff && myexponent != 0 && myintegerbit == 0)) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003060 // exponent meaningless
3061 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003062 significandParts()[0] = mysignificand;
3063 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003064 } else {
3065 category = fcNormal;
3066 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003067 significandParts()[0] = mysignificand;
3068 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003069 if (myexponent==0) // denormal
3070 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003071 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003072}
3073
Tim Shen85de51d2016-10-25 19:55:59 +00003074void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) {
Dale Johannesen007aa372007-10-11 18:07:22 +00003075 assert(api.getBitWidth()==128);
3076 uint64_t i1 = api.getRawData()[0];
3077 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003078 opStatus fs;
3079 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003080
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003081 // Get the first double and convert to our format.
3082 initFromDoubleAPInt(APInt(64, i1));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003083 fs = convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003084 assert(fs == opOK && !losesInfo);
3085 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003086
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003087 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003088 if (isFiniteNonZero()) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003089 IEEEFloat v(semIEEEdouble, APInt(64, i2));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003090 fs = v.convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003091 assert(fs == opOK && !losesInfo);
3092 (void)fs;
3093
3094 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003095 }
3096}
3097
Tim Shen85de51d2016-10-25 19:55:59 +00003098void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003099 assert(api.getBitWidth()==128);
3100 uint64_t i1 = api.getRawData()[0];
3101 uint64_t i2 = api.getRawData()[1];
3102 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3103 uint64_t mysignificand = i1;
3104 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3105
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003106 initialize(&semIEEEquad);
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003107 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003108
3109 sign = static_cast<unsigned int>(i2>>63);
3110 if (myexponent==0 &&
3111 (mysignificand==0 && mysignificand2==0)) {
3112 // exponent, significand meaningless
3113 category = fcZero;
3114 } else if (myexponent==0x7fff &&
3115 (mysignificand==0 && mysignificand2==0)) {
3116 // exponent, significand meaningless
3117 category = fcInfinity;
3118 } else if (myexponent==0x7fff &&
3119 (mysignificand!=0 || mysignificand2 !=0)) {
3120 // exponent meaningless
3121 category = fcNaN;
3122 significandParts()[0] = mysignificand;
3123 significandParts()[1] = mysignificand2;
3124 } else {
3125 category = fcNormal;
3126 exponent = myexponent - 16383;
3127 significandParts()[0] = mysignificand;
3128 significandParts()[1] = mysignificand2;
3129 if (myexponent==0) // denormal
3130 exponent = -16382;
3131 else
3132 significandParts()[1] |= 0x1000000000000LL; // integer bit
3133 }
3134}
3135
Tim Shen85de51d2016-10-25 19:55:59 +00003136void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003137 assert(api.getBitWidth()==64);
3138 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003139 uint64_t myexponent = (i >> 52) & 0x7ff;
3140 uint64_t mysignificand = i & 0xfffffffffffffLL;
3141
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003142 initialize(&semIEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003143 assert(partCount()==1);
3144
Evan Cheng82b9e962008-05-02 21:15:08 +00003145 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003146 if (myexponent==0 && mysignificand==0) {
3147 // exponent, significand meaningless
3148 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003149 } else if (myexponent==0x7ff && mysignificand==0) {
3150 // exponent, significand meaningless
3151 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003152 } else if (myexponent==0x7ff && mysignificand!=0) {
3153 // exponent meaningless
3154 category = fcNaN;
3155 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003156 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003157 category = fcNormal;
3158 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003159 *significandParts() = mysignificand;
3160 if (myexponent==0) // denormal
3161 exponent = -1022;
3162 else
3163 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003164 }
Dale Johannesena719a602007-08-24 00:56:33 +00003165}
3166
Tim Shen85de51d2016-10-25 19:55:59 +00003167void IEEEFloat::initFromFloatAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003168 assert(api.getBitWidth()==32);
3169 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003170 uint32_t myexponent = (i >> 23) & 0xff;
3171 uint32_t mysignificand = i & 0x7fffff;
3172
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003173 initialize(&semIEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003174 assert(partCount()==1);
3175
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003176 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003177 if (myexponent==0 && mysignificand==0) {
3178 // exponent, significand meaningless
3179 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003180 } else if (myexponent==0xff && mysignificand==0) {
3181 // exponent, significand meaningless
3182 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003183 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003184 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003185 category = fcNaN;
3186 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003187 } else {
3188 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003189 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003190 *significandParts() = mysignificand;
3191 if (myexponent==0) // denormal
3192 exponent = -126;
3193 else
3194 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003195 }
3196}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003197
Tim Shen85de51d2016-10-25 19:55:59 +00003198void IEEEFloat::initFromHalfAPInt(const APInt &api) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003199 assert(api.getBitWidth()==16);
3200 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003201 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003202 uint32_t mysignificand = i & 0x3ff;
3203
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003204 initialize(&semIEEEhalf);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003205 assert(partCount()==1);
3206
3207 sign = i >> 15;
3208 if (myexponent==0 && mysignificand==0) {
3209 // exponent, significand meaningless
3210 category = fcZero;
3211 } else if (myexponent==0x1f && mysignificand==0) {
3212 // exponent, significand meaningless
3213 category = fcInfinity;
3214 } else if (myexponent==0x1f && mysignificand!=0) {
3215 // sign, exponent, significand meaningless
3216 category = fcNaN;
3217 *significandParts() = mysignificand;
3218 } else {
3219 category = fcNormal;
3220 exponent = myexponent - 15; //bias
3221 *significandParts() = mysignificand;
3222 if (myexponent==0) // denormal
3223 exponent = -14;
3224 else
3225 *significandParts() |= 0x400; // integer bit
3226 }
3227}
3228
Dale Johannesen245dceb2007-09-11 18:32:33 +00003229/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003230/// we infer the floating point type from the size of the APInt. The
3231/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3232/// when the size is anything else).
Tim Shen85de51d2016-10-25 19:55:59 +00003233void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003234 if (Sem == &semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003235 return initFromHalfAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003236 if (Sem == &semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003237 return initFromFloatAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003238 if (Sem == &semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003239 return initFromDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003240 if (Sem == &semX87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003241 return initFromF80LongDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003242 if (Sem == &semIEEEquad)
Tim Northover29178a32013-01-22 09:46:31 +00003243 return initFromQuadrupleAPInt(api);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003244 if (Sem == &semPPCDoubleDoubleLegacy)
Tim Northover29178a32013-01-22 09:46:31 +00003245 return initFromPPCDoubleDoubleAPInt(api);
3246
Craig Topper2617dcc2014-04-15 06:32:26 +00003247 llvm_unreachable(nullptr);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003248}
3249
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003250/// Make this number the largest magnitude normal number in the given
3251/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003252void IEEEFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003253 // We want (in interchange format):
3254 // sign = {Negative}
3255 // exponent = 1..10
3256 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003257 category = fcNormal;
3258 sign = Negative;
3259 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003260
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003261 // Use memset to set all but the highest integerPart to all ones.
3262 integerPart *significand = significandParts();
3263 unsigned PartCount = partCount();
3264 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003265
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003266 // Set the high integerPart especially setting all unused top bits for
3267 // internal consistency.
3268 const unsigned NumUnusedHighBits =
3269 PartCount*integerPartWidth - semantics->precision;
Alexey Samsonovba1ecbc2014-09-06 00:41:19 +00003270 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3271 ? (~integerPart(0) >> NumUnusedHighBits)
3272 : 0;
John McCall29b5c282009-12-24 08:56:26 +00003273}
3274
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003275/// Make this number the smallest magnitude denormal number in the given
3276/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003277void IEEEFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003278 // We want (in interchange format):
3279 // sign = {Negative}
3280 // exponent = 0..0
3281 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003282 category = fcNormal;
3283 sign = Negative;
3284 exponent = semantics->minExponent;
3285 APInt::tcSet(significandParts(), 1, partCount());
3286}
John McCall29b5c282009-12-24 08:56:26 +00003287
Tim Shen139a58f2016-10-27 22:52:40 +00003288void IEEEFloat::makeSmallestNormalized(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003289 // We want (in interchange format):
3290 // sign = {Negative}
3291 // exponent = 0..0
3292 // significand = 10..0
3293
Tim Shen139a58f2016-10-27 22:52:40 +00003294 category = fcNormal;
3295 zeroSignificand();
3296 sign = Negative;
3297 exponent = semantics->minExponent;
3298 significandParts()[partCountForBits(semantics->precision) - 1] |=
3299 (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003300}
3301
Tim Shen85de51d2016-10-25 19:55:59 +00003302IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
Tim Northover29178a32013-01-22 09:46:31 +00003303 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003304}
3305
Tim Shen85de51d2016-10-25 19:55:59 +00003306IEEEFloat::IEEEFloat(float f) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003307 initFromAPInt(&semIEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003308}
3309
Tim Shen85de51d2016-10-25 19:55:59 +00003310IEEEFloat::IEEEFloat(double d) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003311 initFromAPInt(&semIEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003312}
John McCall29b5c282009-12-24 08:56:26 +00003313
3314namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003315 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3316 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003317 }
3318
John McCalle6212ace2009-12-24 12:16:56 +00003319 /// Removes data from the given significand until it is no more
3320 /// precise than is required for the desired precision.
3321 void AdjustToPrecision(APInt &significand,
3322 int &exp, unsigned FormatPrecision) {
3323 unsigned bits = significand.getActiveBits();
3324
3325 // 196/59 is a very slight overestimate of lg_2(10).
3326 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3327
3328 if (bits <= bitsRequired) return;
3329
3330 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3331 if (!tensRemovable) return;
3332
3333 exp += tensRemovable;
3334
3335 APInt divisor(significand.getBitWidth(), 1);
3336 APInt powten(significand.getBitWidth(), 10);
3337 while (true) {
3338 if (tensRemovable & 1)
3339 divisor *= powten;
3340 tensRemovable >>= 1;
3341 if (!tensRemovable) break;
3342 powten *= powten;
3343 }
3344
3345 significand = significand.udiv(divisor);
3346
Hao Liube99cc32013-03-20 01:46:36 +00003347 // Truncate the significand down to its active bit count.
3348 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003349 }
3350
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003351
John McCall29b5c282009-12-24 08:56:26 +00003352 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3353 int &exp, unsigned FormatPrecision) {
3354 unsigned N = buffer.size();
3355 if (N <= FormatPrecision) return;
3356
3357 // The most significant figures are the last ones in the buffer.
3358 unsigned FirstSignificant = N - FormatPrecision;
3359
3360 // Round.
3361 // FIXME: this probably shouldn't use 'round half up'.
3362
3363 // Rounding down is just a truncation, except we also want to drop
3364 // trailing zeros from the new result.
3365 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003366 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003367 FirstSignificant++;
3368
3369 exp += FirstSignificant;
3370 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3371 return;
3372 }
3373
3374 // Rounding up requires a decimal add-with-carry. If we continue
3375 // the carry, the newly-introduced zeros will just be truncated.
3376 for (unsigned I = FirstSignificant; I != N; ++I) {
3377 if (buffer[I] == '9') {
3378 FirstSignificant++;
3379 } else {
3380 buffer[I]++;
3381 break;
3382 }
3383 }
3384
3385 // If we carried through, we have exactly one digit of precision.
3386 if (FirstSignificant == N) {
3387 exp += FirstSignificant;
3388 buffer.clear();
3389 buffer.push_back('1');
3390 return;
3391 }
3392
3393 exp += FirstSignificant;
3394 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3395 }
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003396}
John McCall29b5c282009-12-24 08:56:26 +00003397
Tim Shen85de51d2016-10-25 19:55:59 +00003398void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003399 unsigned FormatMaxPadding, bool TruncateZero) const {
John McCall29b5c282009-12-24 08:56:26 +00003400 switch (category) {
3401 case fcInfinity:
3402 if (isNegative())
3403 return append(Str, "-Inf");
3404 else
3405 return append(Str, "+Inf");
3406
3407 case fcNaN: return append(Str, "NaN");
3408
3409 case fcZero:
3410 if (isNegative())
3411 Str.push_back('-');
3412
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003413 if (!FormatMaxPadding) {
3414 if (TruncateZero)
3415 append(Str, "0.0E+0");
3416 else {
3417 append(Str, "0.0");
3418 if (FormatPrecision > 1)
3419 Str.append(FormatPrecision - 1, '0');
3420 append(Str, "e+00");
3421 }
3422 } else
John McCall29b5c282009-12-24 08:56:26 +00003423 Str.push_back('0');
3424 return;
3425
3426 case fcNormal:
3427 break;
3428 }
3429
3430 if (isNegative())
3431 Str.push_back('-');
3432
3433 // Decompose the number into an APInt and an exponent.
3434 int exp = exponent - ((int) semantics->precision - 1);
3435 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003436 makeArrayRef(significandParts(),
3437 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003438
John McCalldd5044a2009-12-24 23:18:09 +00003439 // Set FormatPrecision if zero. We want to do this before we
3440 // truncate trailing zeros, as those are part of the precision.
3441 if (!FormatPrecision) {
Eli Friedmane72f1322013-08-29 23:44:34 +00003442 // We use enough digits so the number can be round-tripped back to an
3443 // APFloat. The formula comes from "How to Print Floating-Point Numbers
3444 // Accurately" by Steele and White.
3445 // FIXME: Using a formula based purely on the precision is conservative;
3446 // we can print fewer digits depending on the actual value being printed.
John McCalldd5044a2009-12-24 23:18:09 +00003447
Eli Friedmane72f1322013-08-29 23:44:34 +00003448 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3449 FormatPrecision = 2 + semantics->precision * 59 / 196;
John McCalldd5044a2009-12-24 23:18:09 +00003450 }
3451
John McCall29b5c282009-12-24 08:56:26 +00003452 // Ignore trailing binary zeros.
3453 int trailingZeros = significand.countTrailingZeros();
3454 exp += trailingZeros;
Craig Topperfc947bc2017-04-18 17:14:21 +00003455 significand.lshrInPlace(trailingZeros);
John McCall29b5c282009-12-24 08:56:26 +00003456
3457 // Change the exponent from 2^e to 10^e.
3458 if (exp == 0) {
3459 // Nothing to do.
3460 } else if (exp > 0) {
3461 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003462 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003463 significand <<= exp;
3464 exp = 0;
3465 } else { /* exp < 0 */
3466 int texp = -exp;
3467
3468 // We transform this using the identity:
3469 // (N)(2^-e) == (N)(5^e)(10^-e)
3470 // This means we have to multiply N (the significand) by 5^e.
3471 // To avoid overflow, we have to operate on numbers large
3472 // enough to store N * 5^e:
3473 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003474 // <= semantics->precision + e * 137 / 59
3475 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003476
Eli Friedman19546412011-10-07 23:40:49 +00003477 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003478
3479 // Multiply significand by 5^e.
3480 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003481 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003482 APInt five_to_the_i(precision, 5);
3483 while (true) {
3484 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003485
John McCall29b5c282009-12-24 08:56:26 +00003486 texp >>= 1;
3487 if (!texp) break;
3488 five_to_the_i *= five_to_the_i;
3489 }
3490 }
3491
John McCalle6212ace2009-12-24 12:16:56 +00003492 AdjustToPrecision(significand, exp, FormatPrecision);
3493
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003494 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003495
3496 // Fill the buffer.
3497 unsigned precision = significand.getBitWidth();
3498 APInt ten(precision, 10);
3499 APInt digit(precision, 0);
3500
3501 bool inTrail = true;
3502 while (significand != 0) {
3503 // digit <- significand % 10
3504 // significand <- significand / 10
3505 APInt::udivrem(significand, ten, significand, digit);
3506
3507 unsigned d = digit.getZExtValue();
3508
3509 // Drop trailing zeros.
3510 if (inTrail && !d) exp++;
3511 else {
3512 buffer.push_back((char) ('0' + d));
3513 inTrail = false;
3514 }
3515 }
3516
3517 assert(!buffer.empty() && "no characters in buffer!");
3518
3519 // Drop down to FormatPrecision.
3520 // TODO: don't do more precise calculations above than are required.
3521 AdjustToPrecision(buffer, exp, FormatPrecision);
3522
3523 unsigned NDigits = buffer.size();
3524
John McCalldd5044a2009-12-24 23:18:09 +00003525 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003526 bool FormatScientific;
3527 if (!FormatMaxPadding)
3528 FormatScientific = true;
3529 else {
John McCall29b5c282009-12-24 08:56:26 +00003530 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003531 // 765e3 --> 765000
3532 // ^^^
3533 // But we shouldn't make the number look more precise than it is.
3534 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3535 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003536 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003537 // Power of the most significant digit.
3538 int MSD = exp + (int) (NDigits - 1);
3539 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003540 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003541 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003542 } else {
3543 // 765e-5 == 0.00765
3544 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003545 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003546 }
3547 }
John McCall29b5c282009-12-24 08:56:26 +00003548 }
3549
3550 // Scientific formatting is pretty straightforward.
3551 if (FormatScientific) {
3552 exp += (NDigits - 1);
3553
3554 Str.push_back(buffer[NDigits-1]);
3555 Str.push_back('.');
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003556 if (NDigits == 1 && TruncateZero)
John McCall29b5c282009-12-24 08:56:26 +00003557 Str.push_back('0');
3558 else
3559 for (unsigned I = 1; I != NDigits; ++I)
3560 Str.push_back(buffer[NDigits-1-I]);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003561 // Fill with zeros up to FormatPrecision.
3562 if (!TruncateZero && FormatPrecision > NDigits - 1)
3563 Str.append(FormatPrecision - NDigits + 1, '0');
3564 // For !TruncateZero we use lower 'e'.
3565 Str.push_back(TruncateZero ? 'E' : 'e');
John McCall29b5c282009-12-24 08:56:26 +00003566
3567 Str.push_back(exp >= 0 ? '+' : '-');
3568 if (exp < 0) exp = -exp;
3569 SmallVector<char, 6> expbuf;
3570 do {
3571 expbuf.push_back((char) ('0' + (exp % 10)));
3572 exp /= 10;
3573 } while (exp);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003574 // Exponent always at least two digits if we do not truncate zeros.
3575 if (!TruncateZero && expbuf.size() < 2)
3576 expbuf.push_back('0');
John McCall29b5c282009-12-24 08:56:26 +00003577 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3578 Str.push_back(expbuf[E-1-I]);
3579 return;
3580 }
3581
3582 // Non-scientific, positive exponents.
3583 if (exp >= 0) {
3584 for (unsigned I = 0; I != NDigits; ++I)
3585 Str.push_back(buffer[NDigits-1-I]);
3586 for (unsigned I = 0; I != (unsigned) exp; ++I)
3587 Str.push_back('0');
3588 return;
3589 }
3590
3591 // Non-scientific, negative exponents.
3592
3593 // The number of digits to the left of the decimal point.
3594 int NWholeDigits = exp + (int) NDigits;
3595
3596 unsigned I = 0;
3597 if (NWholeDigits > 0) {
3598 for (; I != (unsigned) NWholeDigits; ++I)
3599 Str.push_back(buffer[NDigits-I-1]);
3600 Str.push_back('.');
3601 } else {
3602 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3603
3604 Str.push_back('0');
3605 Str.push_back('.');
3606 for (unsigned Z = 1; Z != NZeros; ++Z)
3607 Str.push_back('0');
3608 }
3609
3610 for (; I != NDigits; ++I)
3611 Str.push_back(buffer[NDigits-I-1]);
3612}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003613
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003614bool IEEEFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003615 // Special floats and denormals have no exact inverse.
Michael Gottesman8136c382013-06-26 23:17:28 +00003616 if (!isFiniteNonZero())
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003617 return false;
3618
3619 // Check that the number is a power of two by making sure that only the
3620 // integer bit is set in the significand.
3621 if (significandLSB() != semantics->precision - 1)
3622 return false;
3623
3624 // Get the inverse.
Tim Shen85de51d2016-10-25 19:55:59 +00003625 IEEEFloat reciprocal(*semantics, 1ULL);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003626 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3627 return false;
3628
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003629 // Avoid multiplication with a denormal, it is not safe on all platforms and
3630 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003631 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003632 return false;
3633
Michael Gottesman8136c382013-06-26 23:17:28 +00003634 assert(reciprocal.isFiniteNonZero() &&
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003635 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3636
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003637 if (inv)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003638 *inv = APFloat(reciprocal, *semantics);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003639
3640 return true;
3641}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003642
Tim Shen85de51d2016-10-25 19:55:59 +00003643bool IEEEFloat::isSignaling() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003644 if (!isNaN())
3645 return false;
3646
3647 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3648 // first bit of the trailing significand being 0.
3649 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3650}
3651
3652/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3653///
3654/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3655/// appropriate sign switching before/after the computation.
Tim Shen85de51d2016-10-25 19:55:59 +00003656IEEEFloat::opStatus IEEEFloat::next(bool nextDown) {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003657 // If we are performing nextDown, swap sign so we have -x.
3658 if (nextDown)
3659 changeSign();
3660
3661 // Compute nextUp(x)
3662 opStatus result = opOK;
3663
3664 // Handle each float category separately.
3665 switch (category) {
3666 case fcInfinity:
3667 // nextUp(+inf) = +inf
3668 if (!isNegative())
3669 break;
3670 // nextUp(-inf) = -getLargest()
3671 makeLargest(true);
3672 break;
3673 case fcNaN:
3674 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3675 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3676 // change the payload.
3677 if (isSignaling()) {
3678 result = opInvalidOp;
Alp Tokercb402912014-01-24 17:20:08 +00003679 // For consistency, propagate the sign of the sNaN to the qNaN.
Craig Topperc10719f2014-04-07 04:17:22 +00003680 makeNaN(false, isNegative(), nullptr);
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003681 }
3682 break;
3683 case fcZero:
3684 // nextUp(pm 0) = +getSmallest()
3685 makeSmallest(false);
3686 break;
3687 case fcNormal:
3688 // nextUp(-getSmallest()) = -0
3689 if (isSmallest() && isNegative()) {
3690 APInt::tcSet(significandParts(), 0, partCount());
3691 category = fcZero;
3692 exponent = 0;
3693 break;
3694 }
3695
3696 // nextUp(getLargest()) == INFINITY
3697 if (isLargest() && !isNegative()) {
3698 APInt::tcSet(significandParts(), 0, partCount());
3699 category = fcInfinity;
3700 exponent = semantics->maxExponent + 1;
3701 break;
3702 }
3703
3704 // nextUp(normal) == normal + inc.
3705 if (isNegative()) {
3706 // If we are negative, we need to decrement the significand.
3707
3708 // We only cross a binade boundary that requires adjusting the exponent
3709 // if:
3710 // 1. exponent != semantics->minExponent. This implies we are not in the
3711 // smallest binade or are dealing with denormals.
3712 // 2. Our significand excluding the integral bit is all zeros.
3713 bool WillCrossBinadeBoundary =
3714 exponent != semantics->minExponent && isSignificandAllZeros();
3715
3716 // Decrement the significand.
3717 //
3718 // We always do this since:
Alp Tokerf907b892013-12-05 05:44:44 +00003719 // 1. If we are dealing with a non-binade decrement, by definition we
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003720 // just decrement the significand.
3721 // 2. If we are dealing with a normal -> normal binade decrement, since
3722 // we have an explicit integral bit the fact that all bits but the
3723 // integral bit are zero implies that subtracting one will yield a
3724 // significand with 0 integral bit and 1 in all other spots. Thus we
3725 // must just adjust the exponent and set the integral bit to 1.
3726 // 3. If we are dealing with a normal -> denormal binade decrement,
3727 // since we set the integral bit to 0 when we represent denormals, we
3728 // just decrement the significand.
3729 integerPart *Parts = significandParts();
3730 APInt::tcDecrement(Parts, partCount());
3731
3732 if (WillCrossBinadeBoundary) {
3733 // Our result is a normal number. Do the following:
3734 // 1. Set the integral bit to 1.
3735 // 2. Decrement the exponent.
3736 APInt::tcSetBit(Parts, semantics->precision - 1);
3737 exponent--;
3738 }
3739 } else {
3740 // If we are positive, we need to increment the significand.
3741
3742 // We only cross a binade boundary that requires adjusting the exponent if
3743 // the input is not a denormal and all of said input's significand bits
3744 // are set. If all of said conditions are true: clear the significand, set
3745 // the integral bit to 1, and increment the exponent. If we have a
3746 // denormal always increment since moving denormals and the numbers in the
3747 // smallest normal binade have the same exponent in our representation.
3748 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3749
3750 if (WillCrossBinadeBoundary) {
3751 integerPart *Parts = significandParts();
3752 APInt::tcSet(Parts, 0, partCount());
3753 APInt::tcSetBit(Parts, semantics->precision - 1);
3754 assert(exponent != semantics->maxExponent &&
3755 "We can not increment an exponent beyond the maxExponent allowed"
3756 " by the given floating point semantics.");
3757 exponent++;
3758 } else {
3759 incrementSignificand();
3760 }
3761 }
3762 break;
3763 }
3764
3765 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3766 if (nextDown)
3767 changeSign();
3768
3769 return result;
3770}
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003771
Tim Shen85de51d2016-10-25 19:55:59 +00003772void IEEEFloat::makeInf(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003773 category = fcInfinity;
3774 sign = Negative;
3775 exponent = semantics->maxExponent + 1;
3776 APInt::tcSet(significandParts(), 0, partCount());
3777}
3778
Tim Shen85de51d2016-10-25 19:55:59 +00003779void IEEEFloat::makeZero(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003780 category = fcZero;
3781 sign = Negative;
3782 exponent = semantics->minExponent-1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003783 APInt::tcSet(significandParts(), 0, partCount());
3784}
3785
Tim Shen85de51d2016-10-25 19:55:59 +00003786void IEEEFloat::makeQuiet() {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003787 assert(isNaN());
3788 APInt::tcSetBit(significandParts(), semantics->precision - 2);
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003789}
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003790
Tim Shen85de51d2016-10-25 19:55:59 +00003791int ilogb(const IEEEFloat &Arg) {
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003792 if (Arg.isNaN())
Tim Shen85de51d2016-10-25 19:55:59 +00003793 return IEEEFloat::IEK_NaN;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003794 if (Arg.isZero())
Tim Shen85de51d2016-10-25 19:55:59 +00003795 return IEEEFloat::IEK_Zero;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003796 if (Arg.isInfinity())
Tim Shen85de51d2016-10-25 19:55:59 +00003797 return IEEEFloat::IEK_Inf;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003798 if (!Arg.isDenormal())
3799 return Arg.exponent;
3800
Tim Shen85de51d2016-10-25 19:55:59 +00003801 IEEEFloat Normalized(Arg);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003802 int SignificandBits = Arg.getSemantics().precision - 1;
3803
3804 Normalized.exponent += SignificandBits;
Tim Shen85de51d2016-10-25 19:55:59 +00003805 Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003806 return Normalized.exponent - SignificandBits;
3807}
3808
Tim Shen85de51d2016-10-25 19:55:59 +00003809IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) {
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003810 auto MaxExp = X.getSemantics().maxExponent;
3811 auto MinExp = X.getSemantics().minExponent;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003812
Matt Arsenaultafa31cf2016-03-13 05:11:51 +00003813 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
3814 // overflow; clamp it to a safe range before adding, but ensure that the range
3815 // is large enough that the clamp does not change the result. The range we
3816 // need to support is the difference between the largest possible exponent and
3817 // the normalized exponent of half the smallest denormal.
3818
3819 int SignificandBits = X.getSemantics().precision - 1;
3820 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
3821
3822 // Clamp to one past the range ends to let normalize handle overlflow.
3823 X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement);
3824 X.normalize(RoundingMode, lfExactlyZero);
Matt Arsenaultea00b492016-03-23 23:51:45 +00003825 if (X.isNaN())
3826 X.makeQuiet();
Richard Trieu6ae37962015-04-30 23:07:00 +00003827 return X;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003828}
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003829
Tim Shen85de51d2016-10-25 19:55:59 +00003830IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003831 Exp = ilogb(Val);
3832
3833 // Quiet signalling nans.
Tim Shen85de51d2016-10-25 19:55:59 +00003834 if (Exp == IEEEFloat::IEK_NaN) {
3835 IEEEFloat Quiet(Val);
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003836 Quiet.makeQuiet();
3837 return Quiet;
3838 }
3839
Tim Shen85de51d2016-10-25 19:55:59 +00003840 if (Exp == IEEEFloat::IEK_Inf)
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003841 return Val;
3842
3843 // 1 is added because frexp is defined to return a normalized fraction in
3844 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
Tim Shen85de51d2016-10-25 19:55:59 +00003845 Exp = Exp == IEEEFloat::IEK_Zero ? 0 : Exp + 1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003846 return scalbn(Val, -Exp, RM);
3847}
Tim Shen85de51d2016-10-25 19:55:59 +00003848
Tim Shen139a58f2016-10-27 22:52:40 +00003849DoubleAPFloat::DoubleAPFloat(const fltSemantics &S)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003850 : Semantics(&S),
3851 Floats(new APFloat[2]{APFloat(semIEEEdouble), APFloat(semIEEEdouble)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003852 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003853}
3854
3855DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag)
3856 : Semantics(&S),
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003857 Floats(new APFloat[2]{APFloat(semIEEEdouble, uninitialized),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003858 APFloat(semIEEEdouble, uninitialized)}) {
3859 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003860}
3861
3862DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003863 : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble, I),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003864 APFloat(semIEEEdouble)}) {
3865 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003866}
3867
3868DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003869 : Semantics(&S),
3870 Floats(new APFloat[2]{
3871 APFloat(semIEEEdouble, APInt(64, I.getRawData()[0])),
3872 APFloat(semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003873 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003874}
3875
3876DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First,
3877 APFloat &&Second)
3878 : Semantics(&S),
3879 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003880 assert(Semantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003881 assert(&Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003882 assert(&Floats[1].getSemantics() == &semIEEEdouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003883}
3884
3885DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS)
3886 : Semantics(RHS.Semantics),
Tim Shenb49915482016-10-28 22:45:33 +00003887 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
3888 APFloat(RHS.Floats[1])}
3889 : nullptr) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003890 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003891}
3892
3893DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS)
3894 : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003895 RHS.Semantics = &semBogus;
3896 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003897}
3898
3899DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) {
Tim Shenb49915482016-10-28 22:45:33 +00003900 if (Semantics == RHS.Semantics && RHS.Floats) {
Tim Shen139a58f2016-10-27 22:52:40 +00003901 Floats[0] = RHS.Floats[0];
3902 Floats[1] = RHS.Floats[1];
3903 } else if (this != &RHS) {
3904 this->~DoubleAPFloat();
3905 new (this) DoubleAPFloat(RHS);
3906 }
3907 return *this;
3908}
3909
Tim Shen7f127622017-01-24 00:19:45 +00003910// Implement addition, subtraction, multiplication and division based on:
Tim Shen44bde892016-12-12 21:59:30 +00003911// "Software for Doubled-Precision Floating-Point Computations",
3912// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
3913APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
3914 const APFloat &c, const APFloat &cc,
3915 roundingMode RM) {
3916 int Status = opOK;
3917 APFloat z = a;
3918 Status |= z.add(c, RM);
3919 if (!z.isFinite()) {
3920 if (!z.isInfinity()) {
3921 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003922 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003923 return (opStatus)Status;
3924 }
3925 Status = opOK;
3926 auto AComparedToC = a.compareAbsoluteValue(c);
3927 z = cc;
3928 Status |= z.add(aa, RM);
3929 if (AComparedToC == APFloat::cmpGreaterThan) {
3930 // z = cc + aa + c + a;
3931 Status |= z.add(c, RM);
3932 Status |= z.add(a, RM);
3933 } else {
3934 // z = cc + aa + a + c;
3935 Status |= z.add(a, RM);
3936 Status |= z.add(c, RM);
3937 }
3938 if (!z.isFinite()) {
3939 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003940 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003941 return (opStatus)Status;
3942 }
3943 Floats[0] = z;
3944 APFloat zz = aa;
3945 Status |= zz.add(cc, RM);
3946 if (AComparedToC == APFloat::cmpGreaterThan) {
3947 // Floats[1] = a - z + c + zz;
3948 Floats[1] = a;
3949 Status |= Floats[1].subtract(z, RM);
3950 Status |= Floats[1].add(c, RM);
3951 Status |= Floats[1].add(zz, RM);
3952 } else {
3953 // Floats[1] = c - z + a + zz;
3954 Floats[1] = c;
3955 Status |= Floats[1].subtract(z, RM);
3956 Status |= Floats[1].add(a, RM);
3957 Status |= Floats[1].add(zz, RM);
3958 }
3959 } else {
3960 // q = a - z;
3961 APFloat q = a;
3962 Status |= q.subtract(z, RM);
3963
3964 // zz = q + c + (a - (q + z)) + aa + cc;
3965 // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
3966 auto zz = q;
3967 Status |= zz.add(c, RM);
3968 Status |= q.add(z, RM);
3969 Status |= q.subtract(a, RM);
3970 q.changeSign();
3971 Status |= zz.add(q, RM);
3972 Status |= zz.add(aa, RM);
3973 Status |= zz.add(cc, RM);
3974 if (zz.isZero() && !zz.isNegative()) {
3975 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003976 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003977 return opOK;
3978 }
3979 Floats[0] = z;
3980 Status |= Floats[0].add(zz, RM);
3981 if (!Floats[0].isFinite()) {
Tim Shen7117e692017-01-26 00:11:07 +00003982 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003983 return (opStatus)Status;
3984 }
3985 Floats[1] = std::move(z);
3986 Status |= Floats[1].subtract(Floats[0], RM);
3987 Status |= Floats[1].add(zz, RM);
3988 }
3989 return (opStatus)Status;
3990}
3991
3992APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
3993 const DoubleAPFloat &RHS,
3994 DoubleAPFloat &Out,
3995 roundingMode RM) {
3996 if (LHS.getCategory() == fcNaN) {
3997 Out = LHS;
3998 return opOK;
3999 }
4000 if (RHS.getCategory() == fcNaN) {
4001 Out = RHS;
4002 return opOK;
4003 }
4004 if (LHS.getCategory() == fcZero) {
4005 Out = RHS;
4006 return opOK;
4007 }
4008 if (RHS.getCategory() == fcZero) {
4009 Out = LHS;
4010 return opOK;
4011 }
4012 if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity &&
4013 LHS.isNegative() != RHS.isNegative()) {
4014 Out.makeNaN(false, Out.isNegative(), nullptr);
4015 return opInvalidOp;
4016 }
4017 if (LHS.getCategory() == fcInfinity) {
4018 Out = LHS;
4019 return opOK;
4020 }
4021 if (RHS.getCategory() == fcInfinity) {
4022 Out = RHS;
4023 return opOK;
4024 }
4025 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
4026
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004027 APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
Tim Shen44bde892016-12-12 21:59:30 +00004028 CC(RHS.Floats[1]);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004029 assert(&A.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004030 assert(&AA.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004031 assert(&C.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004032 assert(&CC.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004033 assert(&Out.Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004034 assert(&Out.Floats[1].getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004035 return Out.addImpl(A, AA, C, CC, RM);
Tim Shen44bde892016-12-12 21:59:30 +00004036}
4037
4038APFloat::opStatus DoubleAPFloat::add(const DoubleAPFloat &RHS,
4039 roundingMode RM) {
4040 return addWithSpecial(*this, RHS, *this, RM);
4041}
4042
4043APFloat::opStatus DoubleAPFloat::subtract(const DoubleAPFloat &RHS,
4044 roundingMode RM) {
4045 changeSign();
4046 auto Ret = add(RHS, RM);
4047 changeSign();
4048 return Ret;
4049}
4050
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004051APFloat::opStatus DoubleAPFloat::multiply(const DoubleAPFloat &RHS,
4052 APFloat::roundingMode RM) {
Tim Shen7f127622017-01-24 00:19:45 +00004053 const auto &LHS = *this;
4054 auto &Out = *this;
4055 /* Interesting observation: For special categories, finding the lowest
4056 common ancestor of the following layered graph gives the correct
4057 return category:
4058
4059 NaN
4060 / \
4061 Zero Inf
4062 \ /
4063 Normal
4064
4065 e.g. NaN * NaN = NaN
4066 Zero * Inf = NaN
4067 Normal * Zero = Zero
4068 Normal * Inf = Inf
4069 */
4070 if (LHS.getCategory() == fcNaN) {
4071 Out = LHS;
4072 return opOK;
4073 }
4074 if (RHS.getCategory() == fcNaN) {
4075 Out = RHS;
4076 return opOK;
4077 }
4078 if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) ||
4079 (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) {
4080 Out.makeNaN(false, false, nullptr);
4081 return opOK;
4082 }
4083 if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) {
4084 Out = LHS;
4085 return opOK;
4086 }
4087 if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) {
4088 Out = RHS;
4089 return opOK;
4090 }
4091 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
4092 "Special cases not handled exhaustively");
4093
4094 int Status = opOK;
4095 APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
4096 // t = a * c
4097 APFloat T = A;
4098 Status |= T.multiply(C, RM);
4099 if (!T.isFiniteNonZero()) {
4100 Floats[0] = T;
Tim Shen7117e692017-01-26 00:11:07 +00004101 Floats[1].makeZero(/* Neg = */ false);
Tim Shen7f127622017-01-24 00:19:45 +00004102 return (opStatus)Status;
4103 }
4104
4105 // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
4106 APFloat Tau = A;
4107 T.changeSign();
4108 Status |= Tau.fusedMultiplyAdd(C, T, RM);
4109 T.changeSign();
4110 {
4111 // v = a * d
4112 APFloat V = A;
4113 Status |= V.multiply(D, RM);
4114 // w = b * c
4115 APFloat W = B;
4116 Status |= W.multiply(C, RM);
4117 Status |= V.add(W, RM);
4118 // tau += v + w
4119 Status |= Tau.add(V, RM);
4120 }
4121 // u = t + tau
4122 APFloat U = T;
4123 Status |= U.add(Tau, RM);
4124
4125 Floats[0] = U;
4126 if (!U.isFinite()) {
Tim Shen7117e692017-01-26 00:11:07 +00004127 Floats[1].makeZero(/* Neg = */ false);
Tim Shen7f127622017-01-24 00:19:45 +00004128 } else {
4129 // Floats[1] = (t - u) + tau
4130 Status |= T.subtract(U, RM);
4131 Status |= T.add(Tau, RM);
4132 Floats[1] = T;
4133 }
4134 return (opStatus)Status;
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004135}
4136
4137APFloat::opStatus DoubleAPFloat::divide(const DoubleAPFloat &RHS,
4138 APFloat::roundingMode RM) {
4139 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4140 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4141 auto Ret =
4142 Tmp.divide(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
4143 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4144 return Ret;
4145}
4146
4147APFloat::opStatus DoubleAPFloat::remainder(const DoubleAPFloat &RHS) {
4148 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4149 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4150 auto Ret =
4151 Tmp.remainder(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4152 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4153 return Ret;
4154}
4155
4156APFloat::opStatus DoubleAPFloat::mod(const DoubleAPFloat &RHS) {
4157 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4158 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4159 auto Ret = Tmp.mod(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4160 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4161 return Ret;
4162}
4163
4164APFloat::opStatus
4165DoubleAPFloat::fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
4166 const DoubleAPFloat &Addend,
4167 APFloat::roundingMode RM) {
4168 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4169 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4170 auto Ret = Tmp.fusedMultiplyAdd(
4171 APFloat(semPPCDoubleDoubleLegacy, Multiplicand.bitcastToAPInt()),
4172 APFloat(semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()), RM);
4173 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4174 return Ret;
4175}
4176
4177APFloat::opStatus DoubleAPFloat::roundToIntegral(APFloat::roundingMode RM) {
4178 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4179 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4180 auto Ret = Tmp.roundToIntegral(RM);
4181 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4182 return Ret;
4183}
4184
Tim Shen44bde892016-12-12 21:59:30 +00004185void DoubleAPFloat::changeSign() {
4186 Floats[0].changeSign();
4187 Floats[1].changeSign();
4188}
4189
4190APFloat::cmpResult
4191DoubleAPFloat::compareAbsoluteValue(const DoubleAPFloat &RHS) const {
4192 auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
4193 if (Result != cmpEqual)
4194 return Result;
4195 Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
4196 if (Result == cmpLessThan || Result == cmpGreaterThan) {
4197 auto Against = Floats[0].isNegative() ^ Floats[1].isNegative();
4198 auto RHSAgainst = RHS.Floats[0].isNegative() ^ RHS.Floats[1].isNegative();
4199 if (Against && !RHSAgainst)
4200 return cmpLessThan;
4201 if (!Against && RHSAgainst)
4202 return cmpGreaterThan;
4203 if (!Against && !RHSAgainst)
4204 return Result;
4205 if (Against && RHSAgainst)
4206 return (cmpResult)(cmpLessThan + cmpGreaterThan - Result);
4207 }
4208 return Result;
4209}
4210
4211APFloat::fltCategory DoubleAPFloat::getCategory() const {
4212 return Floats[0].getCategory();
4213}
4214
4215bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
4216
4217void DoubleAPFloat::makeInf(bool Neg) {
4218 Floats[0].makeInf(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004219 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004220}
4221
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004222void DoubleAPFloat::makeZero(bool Neg) {
4223 Floats[0].makeZero(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004224 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004225}
4226
4227void DoubleAPFloat::makeLargest(bool Neg) {
4228 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4229 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
4230 Floats[1] = APFloat(semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
4231 if (Neg)
4232 changeSign();
4233}
4234
4235void DoubleAPFloat::makeSmallest(bool Neg) {
4236 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4237 Floats[0].makeSmallest(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004238 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004239}
4240
4241void DoubleAPFloat::makeSmallestNormalized(bool Neg) {
4242 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4243 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x0360000000000000ull));
4244 if (Neg)
4245 Floats[0].changeSign();
Tim Shen7117e692017-01-26 00:11:07 +00004246 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004247}
4248
Tim Shen44bde892016-12-12 21:59:30 +00004249void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
4250 Floats[0].makeNaN(SNaN, Neg, fill);
Tim Shen7117e692017-01-26 00:11:07 +00004251 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004252}
4253
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004254APFloat::cmpResult DoubleAPFloat::compare(const DoubleAPFloat &RHS) const {
4255 auto Result = Floats[0].compare(RHS.Floats[0]);
Tim Shen7117e692017-01-26 00:11:07 +00004256 // |Float[0]| > |Float[1]|
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004257 if (Result == APFloat::cmpEqual)
4258 return Floats[1].compare(RHS.Floats[1]);
4259 return Result;
4260}
4261
4262bool DoubleAPFloat::bitwiseIsEqual(const DoubleAPFloat &RHS) const {
4263 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
4264 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
4265}
4266
4267hash_code hash_value(const DoubleAPFloat &Arg) {
4268 if (Arg.Floats)
4269 return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
4270 return hash_combine(Arg.Semantics);
4271}
4272
4273APInt DoubleAPFloat::bitcastToAPInt() const {
4274 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4275 uint64_t Data[] = {
4276 Floats[0].bitcastToAPInt().getRawData()[0],
4277 Floats[1].bitcastToAPInt().getRawData()[0],
4278 };
4279 return APInt(128, 2, Data);
4280}
4281
4282APFloat::opStatus DoubleAPFloat::convertFromString(StringRef S,
4283 roundingMode RM) {
4284 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4285 APFloat Tmp(semPPCDoubleDoubleLegacy);
4286 auto Ret = Tmp.convertFromString(S, RM);
4287 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4288 return Ret;
4289}
4290
4291APFloat::opStatus DoubleAPFloat::next(bool nextDown) {
4292 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4293 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4294 auto Ret = Tmp.next(nextDown);
4295 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4296 return Ret;
4297}
4298
Simon Pilgrim00b34992017-03-20 14:40:12 +00004299APFloat::opStatus
4300DoubleAPFloat::convertToInteger(MutableArrayRef<integerPart> Input,
4301 unsigned int Width, bool IsSigned,
4302 roundingMode RM, bool *IsExact) const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004303 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4304 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4305 .convertToInteger(Input, Width, IsSigned, RM, IsExact);
4306}
4307
4308APFloat::opStatus DoubleAPFloat::convertFromAPInt(const APInt &Input,
4309 bool IsSigned,
4310 roundingMode RM) {
4311 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4312 APFloat Tmp(semPPCDoubleDoubleLegacy);
4313 auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM);
4314 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4315 return Ret;
4316}
4317
4318APFloat::opStatus
4319DoubleAPFloat::convertFromSignExtendedInteger(const integerPart *Input,
4320 unsigned int InputSize,
4321 bool IsSigned, roundingMode RM) {
4322 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4323 APFloat Tmp(semPPCDoubleDoubleLegacy);
4324 auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM);
4325 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4326 return Ret;
4327}
4328
4329APFloat::opStatus
4330DoubleAPFloat::convertFromZeroExtendedInteger(const integerPart *Input,
4331 unsigned int InputSize,
4332 bool IsSigned, roundingMode RM) {
4333 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4334 APFloat Tmp(semPPCDoubleDoubleLegacy);
4335 auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM);
4336 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4337 return Ret;
4338}
4339
4340unsigned int DoubleAPFloat::convertToHexString(char *DST,
4341 unsigned int HexDigits,
4342 bool UpperCase,
4343 roundingMode RM) const {
4344 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4345 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4346 .convertToHexString(DST, HexDigits, UpperCase, RM);
4347}
4348
4349bool DoubleAPFloat::isDenormal() const {
4350 return getCategory() == fcNormal &&
4351 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
Tim Shen7117e692017-01-26 00:11:07 +00004352 // (double)(Hi + Lo) == Hi defines a normal number.
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004353 Floats[0].compare(Floats[0] + Floats[1]) != cmpEqual);
4354}
4355
4356bool DoubleAPFloat::isSmallest() const {
4357 if (getCategory() != fcNormal)
4358 return false;
4359 DoubleAPFloat Tmp(*this);
4360 Tmp.makeSmallest(this->isNegative());
4361 return Tmp.compare(*this) == cmpEqual;
4362}
4363
4364bool DoubleAPFloat::isLargest() const {
4365 if (getCategory() != fcNormal)
4366 return false;
4367 DoubleAPFloat Tmp(*this);
4368 Tmp.makeLargest(this->isNegative());
4369 return Tmp.compare(*this) == cmpEqual;
4370}
4371
4372bool DoubleAPFloat::isInteger() const {
4373 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
Davide Italiano5a2530d2017-08-21 16:51:54 +00004374 return Floats[0].isInteger() && Floats[1].isInteger();
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004375}
4376
4377void DoubleAPFloat::toString(SmallVectorImpl<char> &Str,
4378 unsigned FormatPrecision,
Serguei Katkov3a46eb42017-04-21 02:52:17 +00004379 unsigned FormatMaxPadding,
4380 bool TruncateZero) const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004381 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4382 APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
Serguei Katkov3a46eb42017-04-21 02:52:17 +00004383 .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004384}
4385
4386bool DoubleAPFloat::getExactInverse(APFloat *inv) const {
4387 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4388 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4389 if (!inv)
4390 return Tmp.getExactInverse(nullptr);
4391 APFloat Inv(semPPCDoubleDoubleLegacy);
4392 auto Ret = Tmp.getExactInverse(&Inv);
4393 *inv = APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt());
4394 return Ret;
4395}
4396
4397DoubleAPFloat scalbn(DoubleAPFloat Arg, int Exp, APFloat::roundingMode RM) {
4398 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4399 return DoubleAPFloat(semPPCDoubleDouble, scalbn(Arg.Floats[0], Exp, RM),
4400 scalbn(Arg.Floats[1], Exp, RM));
4401}
4402
4403DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
4404 APFloat::roundingMode RM) {
4405 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4406 APFloat First = frexp(Arg.Floats[0], Exp, RM);
4407 APFloat Second = Arg.Floats[1];
4408 if (Arg.getCategory() == APFloat::fcNormal)
4409 Second = scalbn(Second, -Exp, RM);
4410 return DoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second));
4411}
4412
Tim Shen85de51d2016-10-25 19:55:59 +00004413} // End detail namespace
4414
Tim Shen398f90f2016-11-06 07:38:37 +00004415APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
4416 if (usesLayout<IEEEFloat>(Semantics)) {
4417 new (&IEEE) IEEEFloat(std::move(F));
Tim Shen7b57ac42016-12-21 02:39:21 +00004418 return;
4419 }
4420 if (usesLayout<DoubleAPFloat>(Semantics)) {
Simon Pilgrim2dd6a0c2019-05-15 13:03:10 +00004421 new (&Double)
4422 DoubleAPFloat(Semantics, APFloat(std::move(F), F.getSemantics()),
4423 APFloat(semIEEEdouble));
Tim Shen7b57ac42016-12-21 02:39:21 +00004424 return;
Tim Shen398f90f2016-11-06 07:38:37 +00004425 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004426 llvm_unreachable("Unexpected semantics");
Tim Shen398f90f2016-11-06 07:38:37 +00004427}
4428
Tim Shen85de51d2016-10-25 19:55:59 +00004429APFloat::opStatus APFloat::convertFromString(StringRef Str, roundingMode RM) {
Tim Shen601ba8c2017-01-27 02:11:07 +00004430 APFLOAT_DISPATCH_ON_SEMANTICS(convertFromString(Str, RM));
Tim Shen85de51d2016-10-25 19:55:59 +00004431}
4432
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004433hash_code hash_value(const APFloat &Arg) {
4434 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
4435 return hash_value(Arg.U.IEEE);
4436 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
4437 return hash_value(Arg.U.Double);
4438 llvm_unreachable("Unexpected semantics");
4439}
Tim Shen85de51d2016-10-25 19:55:59 +00004440
4441APFloat::APFloat(const fltSemantics &Semantics, StringRef S)
Tim Shen139a58f2016-10-27 22:52:40 +00004442 : APFloat(Semantics) {
4443 convertFromString(S, rmNearestTiesToEven);
4444}
4445
4446APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics,
4447 roundingMode RM, bool *losesInfo) {
Sven van Haastregt5ad5c3c2018-05-11 09:45:42 +00004448 if (&getSemantics() == &ToSemantics) {
4449 *losesInfo = false;
Tim Shen139a58f2016-10-27 22:52:40 +00004450 return opOK;
Sven van Haastregt5ad5c3c2018-05-11 09:45:42 +00004451 }
Tim Shen139a58f2016-10-27 22:52:40 +00004452 if (usesLayout<IEEEFloat>(getSemantics()) &&
Tim Shen7b57ac42016-12-21 02:39:21 +00004453 usesLayout<IEEEFloat>(ToSemantics))
Tim Shen139a58f2016-10-27 22:52:40 +00004454 return U.IEEE.convert(ToSemantics, RM, losesInfo);
Tim Shen7b57ac42016-12-21 02:39:21 +00004455 if (usesLayout<IEEEFloat>(getSemantics()) &&
4456 usesLayout<DoubleAPFloat>(ToSemantics)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004457 assert(&ToSemantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004458 auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo);
4459 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
Tim Shen139a58f2016-10-27 22:52:40 +00004460 return Ret;
Tim Shen7b57ac42016-12-21 02:39:21 +00004461 }
4462 if (usesLayout<DoubleAPFloat>(getSemantics()) &&
4463 usesLayout<IEEEFloat>(ToSemantics)) {
Tim Shen139a58f2016-10-27 22:52:40 +00004464 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
Tim Shen398f90f2016-11-06 07:38:37 +00004465 *this = APFloat(std::move(getIEEE()), ToSemantics);
Tim Shen139a58f2016-10-27 22:52:40 +00004466 return Ret;
Tim Shen139a58f2016-10-27 22:52:40 +00004467 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004468 llvm_unreachable("Unexpected semantics");
Tim Shen139a58f2016-10-27 22:52:40 +00004469}
Tim Shen85de51d2016-10-25 19:55:59 +00004470
Tim Shen398f90f2016-11-06 07:38:37 +00004471APFloat APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE) {
4472 if (isIEEE) {
4473 switch (BitWidth) {
4474 case 16:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004475 return APFloat(semIEEEhalf, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004476 case 32:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004477 return APFloat(semIEEEsingle, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004478 case 64:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004479 return APFloat(semIEEEdouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004480 case 80:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004481 return APFloat(semX87DoubleExtended, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004482 case 128:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004483 return APFloat(semIEEEquad, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004484 default:
4485 llvm_unreachable("Unknown floating bit width");
4486 }
4487 } else {
4488 assert(BitWidth == 128);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004489 return APFloat(semPPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004490 }
4491}
4492
Tim Shen44bde892016-12-12 21:59:30 +00004493void APFloat::print(raw_ostream &OS) const {
4494 SmallVector<char, 16> Buffer;
4495 toString(Buffer);
4496 OS << Buffer << "\n";
4497}
4498
Aaron Ballman615eb472017-10-15 14:32:27 +00004499#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +00004500LLVM_DUMP_METHOD void APFloat::dump() const { print(dbgs()); }
4501#endif
Tim Shen44bde892016-12-12 21:59:30 +00004502
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004503void APFloat::Profile(FoldingSetNodeID &NID) const {
4504 NID.Add(bitcastToAPInt());
4505}
4506
4507/* Same as convertToInteger(integerPart*, ...), except the result is returned in
4508 an APSInt, whose initial bit-width and signed-ness are used to determine the
4509 precision of the conversion.
4510 */
4511APFloat::opStatus APFloat::convertToInteger(APSInt &result,
4512 roundingMode rounding_mode,
4513 bool *isExact) const {
4514 unsigned bitWidth = result.getBitWidth();
4515 SmallVector<uint64_t, 4> parts(result.getNumWords());
Simon Pilgrim00b34992017-03-20 14:40:12 +00004516 opStatus status = convertToInteger(parts, bitWidth, result.isSigned(),
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004517 rounding_mode, isExact);
4518 // Keeps the original signed-ness.
4519 result = APInt(bitWidth, parts);
4520 return status;
4521}
4522
Tim Shen85de51d2016-10-25 19:55:59 +00004523} // End llvm namespace
Tim Shen601ba8c2017-01-27 02:11:07 +00004524
4525#undef APFLOAT_DISPATCH_ON_SEMANTICS