blob: c45337f1c5221a9bea03198fbf07b89e5489be91 [file] [log] [blame]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision floating
11// point values and provide a variety of arithmetic operations on them.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnere5256752007-12-08 19:00:03 +000015#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +000016#include "llvm/ADT/APSInt.h"
Mehdi Amini47b292d2016-04-16 07:51:28 +000017#include "llvm/ADT/ArrayRef.h"
Ted Kremenek6f30a072008-02-11 17:24:50 +000018#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000019#include "llvm/ADT/Hashing.h"
Jordan Rosee1f76582013-01-18 21:45:30 +000020#include "llvm/ADT/StringExtras.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000021#include "llvm/ADT/StringRef.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
29using namespace llvm;
30
Michael Gottesman9b877e12013-06-24 09:57:57 +000031/// A macro used to combine two fcCategory enums into one key which can be used
32/// in a switch statement to classify how the interaction of two APFloat's
33/// categories affects an operation.
34///
35/// TODO: If clang source code is ever allowed to use constexpr in its own
36/// codebase, change this into a static inline function.
37#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000038
Neil Booth8f1946f2007-10-03 22:26:02 +000039/* Assumed in hexadecimal significand parsing, and conversion to
40 hexadecimal strings. */
Benjamin Kramer7000ca32014-10-12 17:56:40 +000041static_assert(integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000042
43namespace llvm {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000044 /* Represents floating point arithmetic semantics. */
45 struct fltSemantics {
46 /* The largest E such that 2^E is representable; this matches the
47 definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000048 APFloatBase::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000049
50 /* The smallest E such that 2^E is a normalized number; this
51 matches the definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000052 APFloatBase::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000053
54 /* Number of bits in the significand. This includes the integer
55 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000056 unsigned int precision;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000057
58 /* Number of bits actually used in the semantics. */
59 unsigned int sizeInBits;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000060 };
61
Stephan Bergmann17c7f702016-12-14 11:57:17 +000062 static const fltSemantics semIEEEhalf = {15, -14, 11, 16};
63 static const fltSemantics semIEEEsingle = {127, -126, 24, 32};
64 static const fltSemantics semIEEEdouble = {1023, -1022, 53, 64};
65 static const fltSemantics semIEEEquad = {16383, -16382, 113, 128};
66 static const fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80};
67 static const fltSemantics semBogus = {0, 0, 0, 0};
Dale Johannesen007aa372007-10-11 18:07:22 +000068
Ulrich Weigandd9f7e252012-10-29 18:09:01 +000069 /* The PowerPC format consists of two doubles. It does not map cleanly
70 onto the usual format above. It is approximated using twice the
71 mantissa bits. Note that for exponents near the double minimum,
72 we no longer can represent the full 106 mantissa bits, so those
73 will be treated as denormal numbers.
74
75 FIXME: While this approximation is equivalent to what GCC uses for
76 compile-time arithmetic on PPC double-double numbers, it is not able
77 to represent all possible values held by a PPC double-double number,
78 for example: (long double) 1.0 + (long double) 0x1p-106
Michal Gorny21c12042017-01-03 16:33:50 +000079 Should this be replaced by a full emulation of PPC double-double?
80
81 Note: we need to make the value different from semBogus as otherwise
82 an unsafe optimization may collapse both values to a single address,
83 and we heavily rely on them having distinct addresses. */
84 static const fltSemantics semPPCDoubleDouble = {-1, 0, 0, 0};
Tim Shen139a58f2016-10-27 22:52:40 +000085
Tim Shenfd1e5aa2017-01-23 22:39:35 +000086 /* These are legacy semantics for the fallback, inaccrurate implementation of
87 IBM double-double, if the accurate semPPCDoubleDouble doesn't handle the
88 case. It's equivalent to have an IEEE number with consecutive 106 bits of
89 mantissa, and 11 bits of exponent. It's not accurate, becuase the two
90 53-bit mantissa parts don't actually have to be consecutive,
91 e.g. 1 + epsilon.
Tim Shen139a58f2016-10-27 22:52:40 +000092
Tim Shenfd1e5aa2017-01-23 22:39:35 +000093 Currently, these semantics are used in the following way:
94
95 (IEEEdouble, IEEEdouble) -> (64-bit APInt, 64-bit APInt) ->
96 (128-bit APInt) -> semPPCDoubleDoubleLegacy -> IEEE operations
97
98 We use bitcastToAPInt() to get the bit representation (in APInt) of the
99 underlying IEEEdouble, then use the APInt constructor to construct the
100 legacy IEEE float.
101
102 TODO: Implement all operations in semPPCDoubleDouble, and delete these
103 semantics. */
104 static const fltSemantics semPPCDoubleDoubleLegacy = {1023, -1022 + 53,
105 53 + 53, 128};
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000106
107 const fltSemantics &APFloatBase::IEEEhalf() {
108 return semIEEEhalf;
109 }
110 const fltSemantics &APFloatBase::IEEEsingle() {
111 return semIEEEsingle;
112 }
113 const fltSemantics &APFloatBase::IEEEdouble() {
114 return semIEEEdouble;
115 }
116 const fltSemantics &APFloatBase::IEEEquad() {
117 return semIEEEquad;
118 }
119 const fltSemantics &APFloatBase::x87DoubleExtended() {
120 return semX87DoubleExtended;
121 }
122 const fltSemantics &APFloatBase::Bogus() {
123 return semBogus;
124 }
125 const fltSemantics &APFloatBase::PPCDoubleDouble() {
126 return semPPCDoubleDouble;
127 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000128
129 /* A tight upper bound on number of parts required to hold the value
130 pow(5, power) is
131
Neil Booth91305512007-10-15 15:00:55 +0000132 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000133
Neil Boothb93d90e2007-10-12 16:02:31 +0000134 However, whilst the result may require only this many parts,
135 because we are multiplying two values to get it, the
136 multiplication may require an extra part with the excess part
137 being zero (consider the trivial case of 1 * 1, tcFullMultiply
138 requires two parts to hold the single-part result). So we add an
139 extra one to guarantee enough space whilst multiplying. */
140 const unsigned int maxExponent = 16383;
141 const unsigned int maxPrecision = 113;
142 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth91305512007-10-15 15:00:55 +0000143 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
144 / (351 * integerPartWidth));
Tim Shen85de51d2016-10-25 19:55:59 +0000145
146 unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
147 return semantics.precision;
148 }
149 APFloatBase::ExponentType
150 APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) {
151 return semantics.maxExponent;
152 }
153 APFloatBase::ExponentType
154 APFloatBase::semanticsMinExponent(const fltSemantics &semantics) {
155 return semantics.minExponent;
156 }
157 unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
158 return semantics.sizeInBits;
159 }
160
161 unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) {
162 return Sem.sizeInBits;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000163}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000164
Chris Lattner91702092009-03-12 23:59:55 +0000165/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000166
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000167static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000168partCountForBits(unsigned int bits)
169{
170 return ((bits) + integerPartWidth - 1) / integerPartWidth;
171}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000172
Chris Lattner91702092009-03-12 23:59:55 +0000173/* Returns 0U-9U. Return values >= 10U are not digits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000174static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000175decDigitValue(unsigned int c)
176{
177 return c - '0';
178}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000179
Chris Lattner91702092009-03-12 23:59:55 +0000180/* Return the value of a decimal exponent of the form
181 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000182
Chris Lattner91702092009-03-12 23:59:55 +0000183 If the exponent overflows, returns a large exponent with the
184 appropriate sign. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000185static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000186readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000187{
188 bool isNegative;
189 unsigned int absExponent;
190 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000191 StringRef::iterator p = begin;
192
193 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000194
Chris Lattner91702092009-03-12 23:59:55 +0000195 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000196 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000197 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000198 assert(p != end && "Exponent has no digits");
199 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000200
Chris Lattner91702092009-03-12 23:59:55 +0000201 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000202 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000203
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000204 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000205 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000206
Chris Lattner91702092009-03-12 23:59:55 +0000207 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000208 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000209
Chris Lattner91702092009-03-12 23:59:55 +0000210 value += absExponent * 10;
211 if (absExponent >= overlargeExponent) {
212 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000213 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000214 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000215 }
Chris Lattner91702092009-03-12 23:59:55 +0000216 absExponent = value;
217 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000218
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000219 assert(p == end && "Invalid exponent in exponent");
220
Chris Lattner91702092009-03-12 23:59:55 +0000221 if (isNegative)
222 return -(int) absExponent;
223 else
224 return (int) absExponent;
225}
226
227/* This is ugly and needs cleaning up, but I don't immediately see
228 how whilst remaining safe. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000229static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000230totalExponent(StringRef::iterator p, StringRef::iterator end,
231 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000232{
233 int unsignedExponent;
234 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000235 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000236
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000237 assert(p != end && "Exponent has no digits");
238
Chris Lattner91702092009-03-12 23:59:55 +0000239 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000240 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000241 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000242 assert(p != end && "Exponent has no digits");
243 }
Chris Lattner91702092009-03-12 23:59:55 +0000244
245 unsignedExponent = 0;
246 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000247 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000248 unsigned int value;
249
250 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000251 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000252
Chris Lattner91702092009-03-12 23:59:55 +0000253 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000254 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000255 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000256 break;
257 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000258 }
259
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000260 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000261 overflow = true;
262
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000263 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000264 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000265 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000266 exponent = -exponent;
267 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000268 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000269 overflow = true;
270 }
271
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000272 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000273 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000274
275 return exponent;
276}
277
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000278static StringRef::iterator
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000279skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
280 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000281{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000282 StringRef::iterator p = begin;
283 *dot = end;
Nick Lewycky095b92e2014-09-06 01:16:42 +0000284 while (p != end && *p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000285 p++;
286
Nick Lewycky095b92e2014-09-06 01:16:42 +0000287 if (p != end && *p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000288 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000289
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000290 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000291
Nick Lewycky095b92e2014-09-06 01:16:42 +0000292 while (p != end && *p == '0')
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000293 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000294 }
295
Chris Lattner91702092009-03-12 23:59:55 +0000296 return p;
297}
Neil Booth4ed401b2007-10-14 10:16:12 +0000298
Chris Lattner91702092009-03-12 23:59:55 +0000299/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000300
Chris Lattner91702092009-03-12 23:59:55 +0000301 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000302
Chris Lattner91702092009-03-12 23:59:55 +0000303 where the decimal point and exponent are optional, fill out the
304 structure D. Exponent is appropriate if the significand is
305 treated as an integer, and normalizedExponent if the significand
306 is taken to have the decimal point after a single leading
307 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000308
Chris Lattner91702092009-03-12 23:59:55 +0000309 If the value is zero, V->firstSigDigit points to a non-digit, and
310 the return exponent is zero.
311*/
312struct decimalInfo {
313 const char *firstSigDigit;
314 const char *lastSigDigit;
315 int exponent;
316 int normalizedExponent;
317};
Neil Booth4ed401b2007-10-14 10:16:12 +0000318
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000319static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000320interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
321 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000322{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000323 StringRef::iterator dot = end;
324 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000325
Chris Lattner91702092009-03-12 23:59:55 +0000326 D->firstSigDigit = p;
327 D->exponent = 0;
328 D->normalizedExponent = 0;
329
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000330 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000331 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000332 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000333 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000334 if (p == end)
335 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000336 }
Chris Lattner91702092009-03-12 23:59:55 +0000337 if (decDigitValue(*p) >= 10U)
338 break;
Chris Lattner91702092009-03-12 23:59:55 +0000339 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000340
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000341 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000342 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
343 assert(p != begin && "Significand has no digits");
344 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000345
346 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000347 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000348
Chris Lattner91702092009-03-12 23:59:55 +0000349 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000350 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000351 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000352 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000353
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000354 /* If number is all zeroes accept any exponent. */
355 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000356 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000357 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000358 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000359 do
360 p--;
361 while (p != begin && *p == '0');
362 while (p != begin && *p == '.');
363 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000364
Chris Lattner91702092009-03-12 23:59:55 +0000365 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000366 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000367 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000368 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000369 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000370 }
371
Chris Lattner91702092009-03-12 23:59:55 +0000372 D->lastSigDigit = p;
373}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000374
Chris Lattner91702092009-03-12 23:59:55 +0000375/* Return the trailing fraction of a hexadecimal number.
376 DIGITVALUE is the first hex digit of the fraction, P points to
377 the next digit. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000378static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000379trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
380 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000381{
382 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000383
Chris Lattner91702092009-03-12 23:59:55 +0000384 /* If the first trailing digit isn't 0 or 8 we can work out the
385 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000386 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000387 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000388 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000389 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000390
Eli Friedmand2eb07a2013-07-17 22:17:29 +0000391 // Otherwise we need to find the first non-zero digit.
392 while (p != end && (*p == '0' || *p == '.'))
Chris Lattner91702092009-03-12 23:59:55 +0000393 p++;
394
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000395 assert(p != end && "Invalid trailing hexadecimal fraction!");
396
Chris Lattner91702092009-03-12 23:59:55 +0000397 hexDigit = hexDigitValue(*p);
398
399 /* If we ran off the end it is exactly zero or one-half, otherwise
400 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000401 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000402 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
403 else
404 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
405}
406
407/* Return the fraction lost were a bignum truncated losing the least
408 significant BITS bits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000409static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000410lostFractionThroughTruncation(const integerPart *parts,
411 unsigned int partCount,
412 unsigned int bits)
413{
414 unsigned int lsb;
415
416 lsb = APInt::tcLSB(parts, partCount);
417
418 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000419 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000420 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000421 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000422 return lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000423 if (bits <= partCount * integerPartWidth &&
424 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000425 return lfMoreThanHalf;
426
427 return lfLessThanHalf;
428}
429
430/* Shift DST right BITS bits noting lost fraction. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000431static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000432shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
433{
434 lostFraction lost_fraction;
435
436 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
437
438 APInt::tcShiftRight(dst, parts, bits);
439
440 return lost_fraction;
441}
442
443/* Combine the effect of two lost fractions. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000444static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000445combineLostFractions(lostFraction moreSignificant,
446 lostFraction lessSignificant)
447{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000448 if (lessSignificant != lfExactlyZero) {
449 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000450 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000451 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000452 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000453 }
454
Chris Lattner91702092009-03-12 23:59:55 +0000455 return moreSignificant;
456}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000457
Chris Lattner91702092009-03-12 23:59:55 +0000458/* The error from the true value, in half-ulps, on multiplying two
459 floating point numbers, which differ from the value they
460 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
461 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000462
Chris Lattner91702092009-03-12 23:59:55 +0000463 See "How to Read Floating Point Numbers Accurately" by William D
464 Clinger. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000465static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000466HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
467{
468 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000469
Chris Lattner91702092009-03-12 23:59:55 +0000470 if (HUerr1 + HUerr2 == 0)
471 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
472 else
473 return inexactMultiply + 2 * (HUerr1 + HUerr2);
474}
Neil Booth8f1946f2007-10-03 22:26:02 +0000475
Chris Lattner91702092009-03-12 23:59:55 +0000476/* The number of ulps from the boundary (zero, or half if ISNEAREST)
477 when the least significant BITS are truncated. BITS cannot be
478 zero. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000479static integerPart
Chris Lattner91702092009-03-12 23:59:55 +0000480ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
481{
482 unsigned int count, partBits;
483 integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000484
Evan Cheng67c90212009-10-27 21:35:42 +0000485 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000486
Chris Lattner91702092009-03-12 23:59:55 +0000487 bits--;
488 count = bits / integerPartWidth;
489 partBits = bits % integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000490
Chris Lattner91702092009-03-12 23:59:55 +0000491 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000492
Chris Lattner91702092009-03-12 23:59:55 +0000493 if (isNearest)
494 boundary = (integerPart) 1 << (partBits - 1);
495 else
496 boundary = 0;
497
498 if (count == 0) {
499 if (part - boundary <= boundary - part)
500 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000501 else
Chris Lattner91702092009-03-12 23:59:55 +0000502 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000503 }
504
Chris Lattner91702092009-03-12 23:59:55 +0000505 if (part == boundary) {
506 while (--count)
507 if (parts[count])
508 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000509
Chris Lattner91702092009-03-12 23:59:55 +0000510 return parts[0];
511 } else if (part == boundary - 1) {
512 while (--count)
513 if (~parts[count])
514 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000515
Chris Lattner91702092009-03-12 23:59:55 +0000516 return -parts[0];
517 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000518
Chris Lattner91702092009-03-12 23:59:55 +0000519 return ~(integerPart) 0; /* A lot. */
520}
Neil Boothb93d90e2007-10-12 16:02:31 +0000521
Chris Lattner91702092009-03-12 23:59:55 +0000522/* Place pow(5, power) in DST, and return the number of parts used.
523 DST must be at least one part larger than size of the answer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000524static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000525powerOf5(integerPart *dst, unsigned int power)
526{
527 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
528 15625, 78125 };
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000529 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
530 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000531
Chris Lattner0bf18692009-03-13 00:03:51 +0000532 unsigned int partsCount[16] = { 1 };
Chris Lattner91702092009-03-12 23:59:55 +0000533 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
534 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000535 assert(power <= maxExponent);
536
537 p1 = dst;
538 p2 = scratch;
539
540 *p1 = firstEightPowers[power & 7];
541 power >>= 3;
542
543 result = 1;
544 pow5 = pow5s;
545
546 for (unsigned int n = 0; power; power >>= 1, n++) {
547 unsigned int pc;
548
549 pc = partsCount[n];
550
551 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
552 if (pc == 0) {
553 pc = partsCount[n - 1];
554 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
555 pc *= 2;
556 if (pow5[pc - 1] == 0)
557 pc--;
558 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000559 }
560
Chris Lattner91702092009-03-12 23:59:55 +0000561 if (power & 1) {
562 integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000563
Chris Lattner91702092009-03-12 23:59:55 +0000564 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
565 result += pc;
566 if (p2[result - 1] == 0)
567 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000568
Chris Lattner91702092009-03-12 23:59:55 +0000569 /* Now result is in p1 with partsCount parts and p2 is scratch
570 space. */
Richard Trieu7a083812016-02-18 22:09:30 +0000571 tmp = p1;
572 p1 = p2;
573 p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000574 }
575
Chris Lattner91702092009-03-12 23:59:55 +0000576 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000577 }
578
Chris Lattner91702092009-03-12 23:59:55 +0000579 if (p1 != dst)
580 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000581
Chris Lattner91702092009-03-12 23:59:55 +0000582 return result;
583}
Neil Boothb93d90e2007-10-12 16:02:31 +0000584
Chris Lattner91702092009-03-12 23:59:55 +0000585/* Zero at the end to avoid modular arithmetic when adding one; used
586 when rounding up during hexadecimal output. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000587static const char hexDigitsLower[] = "0123456789abcdef0";
588static const char hexDigitsUpper[] = "0123456789ABCDEF0";
589static const char infinityL[] = "infinity";
590static const char infinityU[] = "INFINITY";
591static const char NaNL[] = "nan";
592static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000593
Chris Lattner91702092009-03-12 23:59:55 +0000594/* Write out an integerPart in hexadecimal, starting with the most
595 significant nibble. Write out exactly COUNT hexdigits, return
596 COUNT. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000597static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000598partAsHex (char *dst, integerPart part, unsigned int count,
599 const char *hexDigitChars)
600{
601 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000602
Evan Cheng67c90212009-10-27 21:35:42 +0000603 assert(count != 0 && count <= integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000604
Chris Lattner91702092009-03-12 23:59:55 +0000605 part >>= (integerPartWidth - 4 * count);
606 while (count--) {
607 dst[count] = hexDigitChars[part & 0xf];
608 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000609 }
610
Chris Lattner91702092009-03-12 23:59:55 +0000611 return result;
612}
Neil Booth8f1946f2007-10-03 22:26:02 +0000613
Chris Lattner91702092009-03-12 23:59:55 +0000614/* Write out an unsigned decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000615static char *
Chris Lattner91702092009-03-12 23:59:55 +0000616writeUnsignedDecimal (char *dst, unsigned int n)
617{
618 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000619
Chris Lattner91702092009-03-12 23:59:55 +0000620 p = buff;
621 do
622 *p++ = '0' + n % 10;
623 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000624
Chris Lattner91702092009-03-12 23:59:55 +0000625 do
626 *dst++ = *--p;
627 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000628
Chris Lattner91702092009-03-12 23:59:55 +0000629 return dst;
630}
Neil Booth8f1946f2007-10-03 22:26:02 +0000631
Chris Lattner91702092009-03-12 23:59:55 +0000632/* Write out a signed decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000633static char *
Chris Lattner91702092009-03-12 23:59:55 +0000634writeSignedDecimal (char *dst, int value)
635{
636 if (value < 0) {
637 *dst++ = '-';
638 dst = writeUnsignedDecimal(dst, -(unsigned) value);
639 } else
640 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000641
Chris Lattner91702092009-03-12 23:59:55 +0000642 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000643}
644
Tim Shen85de51d2016-10-25 19:55:59 +0000645namespace detail {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000646/* Constructors. */
Tim Shen85de51d2016-10-25 19:55:59 +0000647void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000648 unsigned int count;
649
650 semantics = ourSemantics;
651 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000652 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000653 significand.parts = new integerPart[count];
654}
655
Tim Shen85de51d2016-10-25 19:55:59 +0000656void IEEEFloat::freeSignificand() {
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000657 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000658 delete [] significand.parts;
659}
660
Tim Shen85de51d2016-10-25 19:55:59 +0000661void IEEEFloat::assign(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000662 assert(semantics == rhs.semantics);
663
664 sign = rhs.sign;
665 category = rhs.category;
666 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000667 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000668 copySignificand(rhs);
669}
670
Tim Shen85de51d2016-10-25 19:55:59 +0000671void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
Michael Gottesman8136c382013-06-26 23:17:28 +0000672 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000673 assert(rhs.partCount() >= partCount());
674
675 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000676 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000677}
678
Neil Booth5fe658b2007-10-14 10:39:51 +0000679/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000680 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000681 which may not be ideal. If float, this is QNaN(0). */
Tim Shen85de51d2016-10-25 19:55:59 +0000682void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
Neil Booth5fe658b2007-10-14 10:39:51 +0000683 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000684 sign = Negative;
685
John McCallc12b1332010-02-28 12:49:50 +0000686 integerPart *significand = significandParts();
687 unsigned numParts = partCount();
688
John McCalldcb9a7a2010-02-28 02:51:25 +0000689 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000690 if (!fill || fill->getNumWords() < numParts)
691 APInt::tcSet(significand, 0, numParts);
692 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000693 APInt::tcAssign(significand, fill->getRawData(),
694 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000695
696 // Zero out the excess bits of the significand.
697 unsigned bitsToPreserve = semantics->precision - 1;
698 unsigned part = bitsToPreserve / 64;
699 bitsToPreserve %= 64;
700 significand[part] &= ((1ULL << bitsToPreserve) - 1);
701 for (part++; part != numParts; ++part)
702 significand[part] = 0;
703 }
704
705 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000706
707 if (SNaN) {
708 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000709 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000710
711 // If there are no bits set in the payload, we have to set
712 // *something* to make it a NaN instead of an infinity;
713 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000714 if (APInt::tcIsZero(significand, numParts))
715 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000716 } else {
717 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000718 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000719 }
John McCallc12b1332010-02-28 12:49:50 +0000720
721 // For x87 extended precision, we want to make a NaN, not a
722 // pseudo-NaN. Maybe we should expose the ability to make
723 // pseudo-NaNs?
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000724 if (semantics == &semX87DoubleExtended)
John McCallc12b1332010-02-28 12:49:50 +0000725 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000726}
727
Tim Shen85de51d2016-10-25 19:55:59 +0000728IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000729 if (this != &rhs) {
730 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000731 freeSignificand();
732 initialize(rhs.semantics);
733 }
734 assign(rhs);
735 }
736
737 return *this;
738}
739
Tim Shen85de51d2016-10-25 19:55:59 +0000740IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000741 freeSignificand();
742
743 semantics = rhs.semantics;
744 significand = rhs.significand;
745 exponent = rhs.exponent;
746 category = rhs.category;
747 sign = rhs.sign;
748
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000749 rhs.semantics = &semBogus;
Benjamin Kramer06f47782014-03-04 20:26:51 +0000750 return *this;
751}
752
Tim Shen85de51d2016-10-25 19:55:59 +0000753bool IEEEFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000754 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000755 (APInt::tcExtractBit(significandParts(),
756 semantics->precision - 1) == 0);
757}
758
Tim Shen85de51d2016-10-25 19:55:59 +0000759bool IEEEFloat::isSmallest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000760 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000761 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000762 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000763 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000764 significandMSB() == 0;
765}
766
Tim Shen85de51d2016-10-25 19:55:59 +0000767bool IEEEFloat::isSignificandAllOnes() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000768 // Test if the significand excluding the integral bit is all ones. This allows
769 // us to test for binade boundaries.
770 const integerPart *Parts = significandParts();
771 const unsigned PartCount = partCount();
772 for (unsigned i = 0; i < PartCount - 1; i++)
773 if (~Parts[i])
774 return false;
775
776 // Set the unused high bits to all ones when we compare.
777 const unsigned NumHighBits =
778 PartCount*integerPartWidth - semantics->precision + 1;
779 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
780 "fill than integerPartWidth");
781 const integerPart HighBitFill =
782 ~integerPart(0) << (integerPartWidth - NumHighBits);
783 if (~(Parts[PartCount - 1] | HighBitFill))
784 return false;
785
786 return true;
787}
788
Tim Shen85de51d2016-10-25 19:55:59 +0000789bool IEEEFloat::isSignificandAllZeros() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000790 // Test if the significand excluding the integral bit is all zeros. This
791 // allows us to test for binade boundaries.
792 const integerPart *Parts = significandParts();
793 const unsigned PartCount = partCount();
794
795 for (unsigned i = 0; i < PartCount - 1; i++)
796 if (Parts[i])
797 return false;
798
799 const unsigned NumHighBits =
800 PartCount*integerPartWidth - semantics->precision + 1;
801 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
802 "clear than integerPartWidth");
803 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
804
805 if (Parts[PartCount - 1] & HighBitMask)
806 return false;
807
808 return true;
809}
810
Tim Shen85de51d2016-10-25 19:55:59 +0000811bool IEEEFloat::isLargest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000812 // The largest number by magnitude in our format will be the floating point
813 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000814 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000815 && isSignificandAllOnes();
816}
817
Tim Shen85de51d2016-10-25 19:55:59 +0000818bool IEEEFloat::isInteger() const {
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000819 // This could be made more efficient; I'm going for obviously correct.
820 if (!isFinite()) return false;
Tim Shen85de51d2016-10-25 19:55:59 +0000821 IEEEFloat truncated = *this;
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000822 truncated.roundToIntegral(rmTowardZero);
823 return compare(truncated) == cmpEqual;
824}
825
Tim Shen85de51d2016-10-25 19:55:59 +0000826bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000827 if (this == &rhs)
828 return true;
829 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000830 category != rhs.category ||
831 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000832 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000833 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000834 return true;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000835
836 if (isFiniteNonZero() && exponent != rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000837 return false;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000838
839 return std::equal(significandParts(), significandParts() + partCount(),
840 rhs.significandParts());
Dale Johannesena719a602007-08-24 00:56:33 +0000841}
842
Tim Shen85de51d2016-10-25 19:55:59 +0000843IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000844 initialize(&ourSemantics);
845 sign = 0;
Michael Gottesman30a90eb2013-07-27 21:49:21 +0000846 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000847 zeroSignificand();
848 exponent = ourSemantics.precision - 1;
849 significandParts()[0] = value;
850 normalize(rmNearestTiesToEven, lfExactlyZero);
851}
852
Tim Shen85de51d2016-10-25 19:55:59 +0000853IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000854 initialize(&ourSemantics);
855 category = fcZero;
856 sign = false;
857}
858
Tim Shenb49915482016-10-28 22:45:33 +0000859// Delegate to the previous constructor, because later copy constructor may
860// actually inspects category, which can't be garbage.
861IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
Tim Shen1bab9cf2016-10-29 00:51:41 +0000862 : IEEEFloat(ourSemantics) {}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000863
Tim Shen85de51d2016-10-25 19:55:59 +0000864IEEEFloat::IEEEFloat(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000865 initialize(rhs.semantics);
866 assign(rhs);
867}
868
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000869IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000870 *this = std::move(rhs);
871}
872
Tim Shen85de51d2016-10-25 19:55:59 +0000873IEEEFloat::~IEEEFloat() { freeSignificand(); }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000874
Tim Shen85de51d2016-10-25 19:55:59 +0000875unsigned int IEEEFloat::partCount() const {
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000876 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000877}
878
Tim Shen85de51d2016-10-25 19:55:59 +0000879const integerPart *IEEEFloat::significandParts() const {
880 return const_cast<IEEEFloat *>(this)->significandParts();
JF Bastiena1d3c242015-08-26 02:32:45 +0000881}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000882
Tim Shen85de51d2016-10-25 19:55:59 +0000883integerPart *IEEEFloat::significandParts() {
Evan Cheng67c90212009-10-27 21:35:42 +0000884 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000885 return significand.parts;
886 else
887 return &significand.part;
888}
889
Tim Shen85de51d2016-10-25 19:55:59 +0000890void IEEEFloat::zeroSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000891 APInt::tcSet(significandParts(), 0, partCount());
892}
893
894/* Increment an fcNormal floating point number's significand. */
Tim Shen85de51d2016-10-25 19:55:59 +0000895void IEEEFloat::incrementSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000896 integerPart carry;
897
898 carry = APInt::tcIncrement(significandParts(), partCount());
899
900 /* Our callers should never cause us to overflow. */
901 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000902 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000903}
904
905/* Add the significand of the RHS. Returns the carry flag. */
Tim Shen85de51d2016-10-25 19:55:59 +0000906integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000907 integerPart *parts;
908
909 parts = significandParts();
910
911 assert(semantics == rhs.semantics);
912 assert(exponent == rhs.exponent);
913
914 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
915}
916
917/* Subtract the significand of the RHS with a borrow flag. Returns
918 the borrow flag. */
Tim Shen85de51d2016-10-25 19:55:59 +0000919integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
920 integerPart borrow) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000921 integerPart *parts;
922
923 parts = significandParts();
924
925 assert(semantics == rhs.semantics);
926 assert(exponent == rhs.exponent);
927
928 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000929 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000930}
931
932/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
933 on to the full-precision result of the multiplication. Returns the
934 lost fraction. */
Tim Shen85de51d2016-10-25 19:55:59 +0000935lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
936 const IEEEFloat *addend) {
Neil Booth9acbf5a2007-09-26 21:33:42 +0000937 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000938 unsigned int partsCount, newPartsCount, precision;
939 integerPart *lhsSignificand;
940 integerPart scratch[4];
941 integerPart *fullSignificand;
942 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000943 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000944
945 assert(semantics == rhs.semantics);
946
947 precision = semantics->precision;
Lang Hames56c0eb22014-11-19 19:15:41 +0000948
949 // Allocate space for twice as many bits as the original significand, plus one
950 // extra bit for the addition to overflow into.
951 newPartsCount = partCountForBits(precision * 2 + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000952
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000953 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000954 fullSignificand = new integerPart[newPartsCount];
955 else
956 fullSignificand = scratch;
957
958 lhsSignificand = significandParts();
959 partsCount = partCount();
960
961 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000962 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000963
964 lost_fraction = lfExactlyZero;
965 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
966 exponent += rhs.exponent;
967
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000968 // Assume the operands involved in the multiplication are single-precision
969 // FP, and the two multiplicants are:
970 // *this = a23 . a22 ... a0 * 2^e1
971 // rhs = b23 . b22 ... b0 * 2^e2
972 // the result of multiplication is:
Lang Hames56c0eb22014-11-19 19:15:41 +0000973 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
974 // Note that there are three significant bits at the left-hand side of the
975 // radix point: two for the multiplication, and an overflow bit for the
976 // addition (that will always be zero at this point). Move the radix point
977 // toward left by two bits, and adjust exponent accordingly.
978 exponent += 2;
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000979
Hal Finkel171c2ec2014-10-14 19:23:07 +0000980 if (addend && addend->isNonZero()) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000981 // The intermediate result of the multiplication has "2 * precision"
982 // signicant bit; adjust the addend to be consistent with mul result.
983 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000984 Significand savedSignificand = significand;
985 const fltSemantics *savedSemantics = semantics;
986 fltSemantics extendedSemantics;
987 opStatus status;
988 unsigned int extendedPrecision;
989
Lang Hames56c0eb22014-11-19 19:15:41 +0000990 // Normalize our MSB to one below the top bit to allow for overflow.
991 extendedPrecision = 2 * precision + 1;
992 if (omsb != extendedPrecision - 1) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000993 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000994 APInt::tcShiftLeft(fullSignificand, newPartsCount,
Lang Hames56c0eb22014-11-19 19:15:41 +0000995 (extendedPrecision - 1) - omsb);
996 exponent -= (extendedPrecision - 1) - omsb;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000997 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000998
999 /* Create new semantics. */
1000 extendedSemantics = *semantics;
1001 extendedSemantics.precision = extendedPrecision;
1002
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001003 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001004 significand.part = fullSignificand[0];
1005 else
1006 significand.parts = fullSignificand;
1007 semantics = &extendedSemantics;
1008
Tim Shen85de51d2016-10-25 19:55:59 +00001009 IEEEFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001010 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001011 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001012 (void)status;
Lang Hames56c0eb22014-11-19 19:15:41 +00001013
1014 // Shift the significand of the addend right by one bit. This guarantees
1015 // that the high bit of the significand is zero (same as fullSignificand),
1016 // so the addition will overflow (if it does overflow at all) into the top bit.
1017 lost_fraction = extendedAddend.shiftSignificandRight(1);
1018 assert(lost_fraction == lfExactlyZero &&
1019 "Lost precision while shifting addend for fused-multiply-add.");
1020
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001021 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1022
1023 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001024 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001025 fullSignificand[0] = significand.part;
1026 significand = savedSignificand;
1027 semantics = savedSemantics;
1028
1029 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1030 }
1031
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001032 // Convert the result having "2 * precision" significant-bits back to the one
1033 // having "precision" significant-bits. First, move the radix point from
1034 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1035 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
Lang Hames56c0eb22014-11-19 19:15:41 +00001036 exponent -= precision + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001037
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001038 // In case MSB resides at the left-hand side of radix point, shift the
1039 // mantissa right by some amount to make sure the MSB reside right before
1040 // the radix point (i.e. "MSB . rest-significant-bits").
1041 //
1042 // Note that the result is not normalized when "omsb < precision". So, the
Tim Shen85de51d2016-10-25 19:55:59 +00001043 // caller needs to call IEEEFloat::normalize() if normalized value is
1044 // expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001045 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001046 unsigned int bits, significantParts;
1047 lostFraction lf;
1048
1049 bits = omsb - precision;
1050 significantParts = partCountForBits(omsb);
1051 lf = shiftRight(fullSignificand, significantParts, bits);
1052 lost_fraction = combineLostFractions(lf, lost_fraction);
1053 exponent += bits;
1054 }
1055
1056 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1057
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001058 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001059 delete [] fullSignificand;
1060
1061 return lost_fraction;
1062}
1063
1064/* Multiply the significands of LHS and RHS to DST. */
Tim Shen85de51d2016-10-25 19:55:59 +00001065lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001066 unsigned int bit, i, partsCount;
1067 const integerPart *rhsSignificand;
1068 integerPart *lhsSignificand, *dividend, *divisor;
1069 integerPart scratch[4];
1070 lostFraction lost_fraction;
1071
1072 assert(semantics == rhs.semantics);
1073
1074 lhsSignificand = significandParts();
1075 rhsSignificand = rhs.significandParts();
1076 partsCount = partCount();
1077
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001078 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001079 dividend = new integerPart[partsCount * 2];
1080 else
1081 dividend = scratch;
1082
1083 divisor = dividend + partsCount;
1084
1085 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001086 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001087 dividend[i] = lhsSignificand[i];
1088 divisor[i] = rhsSignificand[i];
1089 lhsSignificand[i] = 0;
1090 }
1091
1092 exponent -= rhs.exponent;
1093
1094 unsigned int precision = semantics->precision;
1095
1096 /* Normalize the divisor. */
1097 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001098 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001099 exponent += bit;
1100 APInt::tcShiftLeft(divisor, partsCount, bit);
1101 }
1102
1103 /* Normalize the dividend. */
1104 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001105 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001106 exponent -= bit;
1107 APInt::tcShiftLeft(dividend, partsCount, bit);
1108 }
1109
Neil Boothb93d90e2007-10-12 16:02:31 +00001110 /* Ensure the dividend >= divisor initially for the loop below.
1111 Incidentally, this means that the division loop below is
1112 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001113 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001114 exponent--;
1115 APInt::tcShiftLeft(dividend, partsCount, 1);
1116 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1117 }
1118
1119 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001120 for (bit = precision; bit; bit -= 1) {
1121 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001122 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1123 APInt::tcSetBit(lhsSignificand, bit - 1);
1124 }
1125
1126 APInt::tcShiftLeft(dividend, partsCount, 1);
1127 }
1128
1129 /* Figure out the lost fraction. */
1130 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1131
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001132 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001133 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001134 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001135 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001136 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001137 lost_fraction = lfExactlyZero;
1138 else
1139 lost_fraction = lfLessThanHalf;
1140
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001141 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001142 delete [] dividend;
1143
1144 return lost_fraction;
1145}
1146
Tim Shen85de51d2016-10-25 19:55:59 +00001147unsigned int IEEEFloat::significandMSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001148 return APInt::tcMSB(significandParts(), partCount());
1149}
1150
Tim Shen85de51d2016-10-25 19:55:59 +00001151unsigned int IEEEFloat::significandLSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001152 return APInt::tcLSB(significandParts(), partCount());
1153}
1154
1155/* Note that a zero result is NOT normalized to fcZero. */
Tim Shen85de51d2016-10-25 19:55:59 +00001156lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001157 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001158 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001159
1160 exponent += bits;
1161
1162 return shiftRight(significandParts(), partCount(), bits);
1163}
1164
1165/* Shift the significand left BITS bits, subtract BITS from its exponent. */
Tim Shen85de51d2016-10-25 19:55:59 +00001166void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001167 assert(bits < semantics->precision);
1168
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001169 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001170 unsigned int partsCount = partCount();
1171
1172 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1173 exponent -= bits;
1174
1175 assert(!APInt::tcIsZero(significandParts(), partsCount));
1176 }
1177}
1178
Tim Shen85de51d2016-10-25 19:55:59 +00001179IEEEFloat::cmpResult
1180IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001181 int compare;
1182
1183 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001184 assert(isFiniteNonZero());
1185 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001186
1187 compare = exponent - rhs.exponent;
1188
1189 /* If exponents are equal, do an unsigned bignum comparison of the
1190 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001191 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001192 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001193 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001194
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001195 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001196 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001197 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001198 return cmpLessThan;
1199 else
1200 return cmpEqual;
1201}
1202
1203/* Handle overflow. Sign is preserved. We either become infinity or
1204 the largest finite number. */
Tim Shen85de51d2016-10-25 19:55:59 +00001205IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001206 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001207 if (rounding_mode == rmNearestTiesToEven ||
1208 rounding_mode == rmNearestTiesToAway ||
1209 (rounding_mode == rmTowardPositive && !sign) ||
1210 (rounding_mode == rmTowardNegative && sign)) {
1211 category = fcInfinity;
1212 return (opStatus) (opOverflow | opInexact);
1213 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001214
1215 /* Otherwise we become the largest finite number. */
1216 category = fcNormal;
1217 exponent = semantics->maxExponent;
1218 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001219 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001220
1221 return opInexact;
1222}
1223
Neil Booth1ca1f802007-10-03 15:16:41 +00001224/* Returns TRUE if, when truncating the current number, with BIT the
1225 new LSB, with the given lost fraction and rounding mode, the result
1226 would need to be rounded away from zero (i.e., by increasing the
1227 signficand). This routine must work for fcZero of both signs, and
1228 fcNormal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001229bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1230 lostFraction lost_fraction,
1231 unsigned int bit) const {
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001232 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001233 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001234
Neil Booth1ca1f802007-10-03 15:16:41 +00001235 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001236 assert(lost_fraction != lfExactlyZero);
1237
Mike Stump889285d2009-05-13 23:23:20 +00001238 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001239 case rmNearestTiesToAway:
1240 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1241
1242 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001243 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001244 return true;
1245
1246 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001247 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001248 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001249
1250 return false;
1251
1252 case rmTowardZero:
1253 return false;
1254
1255 case rmTowardPositive:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001256 return !sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001257
1258 case rmTowardNegative:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001259 return sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001260 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001261 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001262}
1263
Tim Shen85de51d2016-10-25 19:55:59 +00001264IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1265 lostFraction lost_fraction) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001266 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001267 int exponentChange;
1268
Michael Gottesman8136c382013-06-26 23:17:28 +00001269 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001270 return opOK;
1271
1272 /* Before rounding normalize the exponent of fcNormal numbers. */
1273 omsb = significandMSB() + 1;
1274
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001275 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001276 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001277 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001278 the exponent. */
1279 exponentChange = omsb - semantics->precision;
1280
1281 /* If the resulting exponent is too high, overflow according to
1282 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001283 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001284 return handleOverflow(rounding_mode);
1285
1286 /* Subnormal numbers have exponent minExponent, and their MSB
1287 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001288 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001289 exponentChange = semantics->minExponent - exponent;
1290
1291 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001292 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001293 assert(lost_fraction == lfExactlyZero);
1294
1295 shiftSignificandLeft(-exponentChange);
1296
1297 return opOK;
1298 }
1299
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001300 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001301 lostFraction lf;
1302
1303 /* Shift right and capture any new lost fraction. */
1304 lf = shiftSignificandRight(exponentChange);
1305
1306 lost_fraction = combineLostFractions(lf, lost_fraction);
1307
1308 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001309 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001310 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001311 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001312 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001313 }
1314 }
1315
1316 /* Now round the number according to rounding_mode given the lost
1317 fraction. */
1318
1319 /* As specified in IEEE 754, since we do not trap we do not report
1320 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001321 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001322 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001323 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001324 category = fcZero;
1325
1326 return opOK;
1327 }
1328
1329 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001330 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1331 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001332 exponent = semantics->minExponent;
1333
1334 incrementSignificand();
1335 omsb = significandMSB() + 1;
1336
1337 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001338 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001339 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001340 significand right one. However if we already have the
1341 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001342 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001343 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001344
Neil Booth9acbf5a2007-09-26 21:33:42 +00001345 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001346 }
1347
1348 shiftSignificandRight(1);
1349
1350 return opInexact;
1351 }
1352 }
1353
1354 /* The normal case - we were and are not denormal, and any
1355 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001356 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001357 return opInexact;
1358
1359 /* We have a non-zero denormal. */
1360 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001361
1362 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001363 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001364 category = fcZero;
1365
1366 /* The fcZero case is a denormal that underflowed to zero. */
1367 return (opStatus) (opUnderflow | opInexact);
1368}
1369
Tim Shen85de51d2016-10-25 19:55:59 +00001370IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1371 bool subtract) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001372 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001373 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001374 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001375
Michael Gottesman9b877e12013-06-24 09:57:57 +00001376 case PackCategoriesIntoKey(fcNaN, fcZero):
1377 case PackCategoriesIntoKey(fcNaN, fcNormal):
1378 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1379 case PackCategoriesIntoKey(fcNaN, fcNaN):
1380 case PackCategoriesIntoKey(fcNormal, fcZero):
1381 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1382 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001383 return opOK;
1384
Michael Gottesman9b877e12013-06-24 09:57:57 +00001385 case PackCategoriesIntoKey(fcZero, fcNaN):
1386 case PackCategoriesIntoKey(fcNormal, fcNaN):
1387 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Stephen Canond3278282014-06-08 16:53:31 +00001388 // We need to be sure to flip the sign here for subtraction because we
1389 // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1390 sign = rhs.sign ^ subtract;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001391 category = fcNaN;
1392 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001393 return opOK;
1394
Michael Gottesman9b877e12013-06-24 09:57:57 +00001395 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1396 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001397 category = fcInfinity;
1398 sign = rhs.sign ^ subtract;
1399 return opOK;
1400
Michael Gottesman9b877e12013-06-24 09:57:57 +00001401 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001402 assign(rhs);
1403 sign = rhs.sign ^ subtract;
1404 return opOK;
1405
Michael Gottesman9b877e12013-06-24 09:57:57 +00001406 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001407 /* Sign depends on rounding mode; handled by caller. */
1408 return opOK;
1409
Michael Gottesman9b877e12013-06-24 09:57:57 +00001410 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001411 /* Differently signed infinities can only be validly
1412 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001413 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001414 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001415 return opInvalidOp;
1416 }
1417
1418 return opOK;
1419
Michael Gottesman9b877e12013-06-24 09:57:57 +00001420 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001421 return opDivByZero;
1422 }
1423}
1424
1425/* Add or subtract two normal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001426lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1427 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001428 integerPart carry;
1429 lostFraction lost_fraction;
1430 int bits;
1431
1432 /* Determine if the operation on the absolute values is effectively
1433 an addition or subtraction. */
Aaron Ballmand5cc45f2015-03-24 12:47:51 +00001434 subtract ^= static_cast<bool>(sign ^ rhs.sign);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001435
1436 /* Are we bigger exponent-wise than the RHS? */
1437 bits = exponent - rhs.exponent;
1438
1439 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001440 if (subtract) {
Tim Shen85de51d2016-10-25 19:55:59 +00001441 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001442 bool reverse;
1443
Chris Lattner3da18eb2007-08-24 03:02:34 +00001444 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001445 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1446 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001447 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001448 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1449 shiftSignificandLeft(1);
1450 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001451 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001452 lost_fraction = shiftSignificandRight(-bits - 1);
1453 temp_rhs.shiftSignificandLeft(1);
1454 reverse = true;
1455 }
1456
Chris Lattner3da18eb2007-08-24 03:02:34 +00001457 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001458 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001459 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001460 copySignificand(temp_rhs);
1461 sign = !sign;
1462 } else {
1463 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001464 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001465 }
1466
1467 /* Invert the lost fraction - it was on the RHS and
1468 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001469 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001470 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001471 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001472 lost_fraction = lfLessThanHalf;
1473
1474 /* The code above is intended to ensure that no borrow is
1475 necessary. */
1476 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001477 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001478 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001479 if (bits > 0) {
Tim Shen85de51d2016-10-25 19:55:59 +00001480 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001481
1482 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1483 carry = addSignificand(temp_rhs);
1484 } else {
1485 lost_fraction = shiftSignificandRight(-bits);
1486 carry = addSignificand(rhs);
1487 }
1488
1489 /* We have a guard bit; generating a carry cannot happen. */
1490 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001491 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001492 }
1493
1494 return lost_fraction;
1495}
1496
Tim Shen85de51d2016-10-25 19:55:59 +00001497IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001498 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001499 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001500 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001501
Michael Gottesman9b877e12013-06-24 09:57:57 +00001502 case PackCategoriesIntoKey(fcNaN, fcZero):
1503 case PackCategoriesIntoKey(fcNaN, fcNormal):
1504 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1505 case PackCategoriesIntoKey(fcNaN, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001506 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001507 return opOK;
1508
Michael Gottesman9b877e12013-06-24 09:57:57 +00001509 case PackCategoriesIntoKey(fcZero, fcNaN):
1510 case PackCategoriesIntoKey(fcNormal, fcNaN):
1511 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001512 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001513 category = fcNaN;
1514 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001515 return opOK;
1516
Michael Gottesman9b877e12013-06-24 09:57:57 +00001517 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1518 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1519 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001520 category = fcInfinity;
1521 return opOK;
1522
Michael Gottesman9b877e12013-06-24 09:57:57 +00001523 case PackCategoriesIntoKey(fcZero, fcNormal):
1524 case PackCategoriesIntoKey(fcNormal, fcZero):
1525 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001526 category = fcZero;
1527 return opOK;
1528
Michael Gottesman9b877e12013-06-24 09:57:57 +00001529 case PackCategoriesIntoKey(fcZero, fcInfinity):
1530 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001531 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001532 return opInvalidOp;
1533
Michael Gottesman9b877e12013-06-24 09:57:57 +00001534 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001535 return opOK;
1536 }
1537}
1538
Tim Shen85de51d2016-10-25 19:55:59 +00001539IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001540 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001541 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001542 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001543
Michael Gottesman9b877e12013-06-24 09:57:57 +00001544 case PackCategoriesIntoKey(fcZero, fcNaN):
1545 case PackCategoriesIntoKey(fcNormal, fcNaN):
1546 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001547 category = fcNaN;
1548 copySignificand(rhs);
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001549 case PackCategoriesIntoKey(fcNaN, fcZero):
1550 case PackCategoriesIntoKey(fcNaN, fcNormal):
1551 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1552 case PackCategoriesIntoKey(fcNaN, fcNaN):
1553 sign = false;
1554 case PackCategoriesIntoKey(fcInfinity, fcZero):
1555 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1556 case PackCategoriesIntoKey(fcZero, fcInfinity):
1557 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001558 return opOK;
1559
Michael Gottesman9b877e12013-06-24 09:57:57 +00001560 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001561 category = fcZero;
1562 return opOK;
1563
Michael Gottesman9b877e12013-06-24 09:57:57 +00001564 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001565 category = fcInfinity;
1566 return opDivByZero;
1567
Michael Gottesman9b877e12013-06-24 09:57:57 +00001568 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1569 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001570 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001571 return opInvalidOp;
1572
Michael Gottesman9b877e12013-06-24 09:57:57 +00001573 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001574 return opOK;
1575 }
1576}
1577
Tim Shen85de51d2016-10-25 19:55:59 +00001578IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001579 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001580 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001581 llvm_unreachable(nullptr);
Dale Johannesenb5721632009-01-21 00:35:19 +00001582
Michael Gottesman9b877e12013-06-24 09:57:57 +00001583 case PackCategoriesIntoKey(fcNaN, fcZero):
1584 case PackCategoriesIntoKey(fcNaN, fcNormal):
1585 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1586 case PackCategoriesIntoKey(fcNaN, fcNaN):
1587 case PackCategoriesIntoKey(fcZero, fcInfinity):
1588 case PackCategoriesIntoKey(fcZero, fcNormal):
1589 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001590 return opOK;
1591
Michael Gottesman9b877e12013-06-24 09:57:57 +00001592 case PackCategoriesIntoKey(fcZero, fcNaN):
1593 case PackCategoriesIntoKey(fcNormal, fcNaN):
1594 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001595 sign = false;
Dale Johannesenb5721632009-01-21 00:35:19 +00001596 category = fcNaN;
1597 copySignificand(rhs);
1598 return opOK;
1599
Michael Gottesman9b877e12013-06-24 09:57:57 +00001600 case PackCategoriesIntoKey(fcNormal, fcZero):
1601 case PackCategoriesIntoKey(fcInfinity, fcZero):
1602 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1603 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1604 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001605 makeNaN();
1606 return opInvalidOp;
1607
Michael Gottesman9b877e12013-06-24 09:57:57 +00001608 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001609 return opOK;
1610 }
1611}
1612
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001613/* Change sign. */
Tim Shen85de51d2016-10-25 19:55:59 +00001614void IEEEFloat::changeSign() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001615 /* Look mummy, this one's easy. */
1616 sign = !sign;
1617}
1618
1619/* Normalized addition or subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001620IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
1621 roundingMode rounding_mode,
1622 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001623 opStatus fs;
1624
1625 fs = addOrSubtractSpecials(rhs, subtract);
1626
1627 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001628 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001629 lostFraction lost_fraction;
1630
1631 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1632 fs = normalize(rounding_mode, lost_fraction);
1633
1634 /* Can only be zero if we lost no fraction. */
1635 assert(category != fcZero || lost_fraction == lfExactlyZero);
1636 }
1637
1638 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1639 positive zero unless rounding to minus infinity, except that
1640 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001641 if (category == fcZero) {
1642 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001643 sign = (rounding_mode == rmTowardNegative);
1644 }
1645
1646 return fs;
1647}
1648
1649/* Normalized addition. */
Tim Shen85de51d2016-10-25 19:55:59 +00001650IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs,
1651 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001652 return addOrSubtract(rhs, rounding_mode, false);
1653}
1654
1655/* Normalized subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001656IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs,
1657 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001658 return addOrSubtract(rhs, rounding_mode, true);
1659}
1660
1661/* Normalized multiply. */
Tim Shen85de51d2016-10-25 19:55:59 +00001662IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs,
1663 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001664 opStatus fs;
1665
1666 sign ^= rhs.sign;
1667 fs = multiplySpecials(rhs);
1668
Michael Gottesman8136c382013-06-26 23:17:28 +00001669 if (isFiniteNonZero()) {
Craig Topperc10719f2014-04-07 04:17:22 +00001670 lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001671 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001672 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001673 fs = (opStatus) (fs | opInexact);
1674 }
1675
1676 return fs;
1677}
1678
1679/* Normalized divide. */
Tim Shen85de51d2016-10-25 19:55:59 +00001680IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs,
1681 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001682 opStatus fs;
1683
1684 sign ^= rhs.sign;
1685 fs = divideSpecials(rhs);
1686
Michael Gottesman8136c382013-06-26 23:17:28 +00001687 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001688 lostFraction lost_fraction = divideSignificand(rhs);
1689 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001690 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001691 fs = (opStatus) (fs | opInexact);
1692 }
1693
1694 return fs;
1695}
1696
Dale Johannesenfe750172009-01-20 18:35:05 +00001697/* Normalized remainder. This is not currently correct in all cases. */
Tim Shen85de51d2016-10-25 19:55:59 +00001698IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) {
Dale Johannesenfe750172009-01-20 18:35:05 +00001699 opStatus fs;
Tim Shen85de51d2016-10-25 19:55:59 +00001700 IEEEFloat V = *this;
Dale Johannesenfe750172009-01-20 18:35:05 +00001701 unsigned int origSign = sign;
1702
Dale Johannesenfe750172009-01-20 18:35:05 +00001703 fs = V.divide(rhs, rmNearestTiesToEven);
1704 if (fs == opDivByZero)
1705 return fs;
1706
1707 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001708 integerPart *x = new integerPart[parts];
Dale Johannesenfe750172009-01-20 18:35:05 +00001709 bool ignored;
1710 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1711 rmNearestTiesToEven, &ignored);
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001712 if (fs==opInvalidOp) {
1713 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001714 return fs;
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001715 }
Dale Johannesenfe750172009-01-20 18:35:05 +00001716
1717 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1718 rmNearestTiesToEven);
1719 assert(fs==opOK); // should always work
1720
1721 fs = V.multiply(rhs, rmNearestTiesToEven);
1722 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1723
1724 fs = subtract(V, rmNearestTiesToEven);
1725 assert(fs==opOK || fs==opInexact); // likewise
1726
1727 if (isZero())
1728 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001729 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001730 return fs;
1731}
1732
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001733/* Normalized llvm frem (C fmod).
Dale Johannesenfe750172009-01-20 18:35:05 +00001734 This is not currently correct in all cases. */
Tim Shen85de51d2016-10-25 19:55:59 +00001735IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) {
Dale Johannesen689d17d2007-08-31 23:35:31 +00001736 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001737 fs = modSpecials(rhs);
Dale Johannesen689d17d2007-08-31 23:35:31 +00001738
Michael Gottesman8136c382013-06-26 23:17:28 +00001739 if (isFiniteNonZero() && rhs.isFiniteNonZero()) {
Tim Shen85de51d2016-10-25 19:55:59 +00001740 IEEEFloat V = *this;
Dale Johannesenb5721632009-01-21 00:35:19 +00001741 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001742
Dale Johannesenb5721632009-01-21 00:35:19 +00001743 fs = V.divide(rhs, rmNearestTiesToEven);
1744 if (fs == opDivByZero)
1745 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001746
Dale Johannesenb5721632009-01-21 00:35:19 +00001747 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001748 integerPart *x = new integerPart[parts];
Dale Johannesenb5721632009-01-21 00:35:19 +00001749 bool ignored;
1750 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1751 rmTowardZero, &ignored);
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001752 if (fs==opInvalidOp) {
1753 delete[] x;
Dale Johannesenb5721632009-01-21 00:35:19 +00001754 return fs;
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001755 }
Dale Johannesen728687c2007-09-05 20:39:49 +00001756
Dale Johannesenb5721632009-01-21 00:35:19 +00001757 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1758 rmNearestTiesToEven);
1759 assert(fs==opOK); // should always work
Dale Johannesen728687c2007-09-05 20:39:49 +00001760
Stephen Canonb12db0e2015-09-21 19:29:25 +00001761 fs = V.multiply(rhs, rmNearestTiesToEven);
Dale Johannesenb5721632009-01-21 00:35:19 +00001762 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1763
Stephen Canonb12db0e2015-09-21 19:29:25 +00001764 fs = subtract(V, rmNearestTiesToEven);
Dale Johannesenb5721632009-01-21 00:35:19 +00001765 assert(fs==opOK || fs==opInexact); // likewise
1766
1767 if (isZero())
1768 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001769 delete[] x;
Dale Johannesenb5721632009-01-21 00:35:19 +00001770 }
Dale Johannesen689d17d2007-08-31 23:35:31 +00001771 return fs;
1772}
1773
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001774/* Normalized fused-multiply-add. */
Tim Shen85de51d2016-10-25 19:55:59 +00001775IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand,
1776 const IEEEFloat &addend,
1777 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001778 opStatus fs;
1779
1780 /* Post-multiplication sign, before addition. */
1781 sign ^= multiplicand.sign;
1782
1783 /* If and only if all arguments are normal do we need to do an
1784 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001785 if (isFiniteNonZero() &&
1786 multiplicand.isFiniteNonZero() &&
Hal Finkel171c2ec2014-10-14 19:23:07 +00001787 addend.isFinite()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001788 lostFraction lost_fraction;
1789
1790 lost_fraction = multiplySignificand(multiplicand, &addend);
1791 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001792 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001793 fs = (opStatus) (fs | opInexact);
1794
1795 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1796 positive zero unless rounding to minus infinity, except that
1797 adding two like-signed zeroes gives that zero. */
Lang Hames12b12e82015-01-04 01:20:55 +00001798 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001799 sign = (rounding_mode == rmTowardNegative);
1800 } else {
1801 fs = multiplySpecials(multiplicand);
1802
1803 /* FS can only be opOK or opInvalidOp. There is no more work
1804 to do in the latter case. The IEEE-754R standard says it is
1805 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001806 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001807
1808 If we need to do the addition we can do so with normal
1809 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001810 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001811 fs = addOrSubtract(addend, rounding_mode, false);
1812 }
1813
1814 return fs;
1815}
1816
Owen Andersona40319b2012-08-13 23:32:49 +00001817/* Rounding-mode corrrect round to integral value. */
Tim Shen85de51d2016-10-25 19:55:59 +00001818IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) {
Owen Andersona40319b2012-08-13 23:32:49 +00001819 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001820
Owen Anderson352dfff2012-08-15 18:28:45 +00001821 // If the exponent is large enough, we know that this value is already
1822 // integral, and the arithmetic below would potentially cause it to saturate
1823 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001824 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001825 return opOK;
1826
Owen Andersona40319b2012-08-13 23:32:49 +00001827 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1828 // precision of our format, and then subtract it back off again. The choice
1829 // of rounding modes for the addition/subtraction determines the rounding mode
1830 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001831 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001832 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001833 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1834 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Tim Shen85de51d2016-10-25 19:55:59 +00001835 IEEEFloat MagicConstant(*semantics);
Owen Andersona40319b2012-08-13 23:32:49 +00001836 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1837 rmNearestTiesToEven);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00001838 MagicConstant.sign = sign;
Owen Anderson1ff74b02012-08-15 05:39:46 +00001839
Owen Andersona40319b2012-08-13 23:32:49 +00001840 if (fs != opOK)
1841 return fs;
1842
Owen Anderson1ff74b02012-08-15 05:39:46 +00001843 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1844 bool inputSign = isNegative();
1845
Owen Andersona40319b2012-08-13 23:32:49 +00001846 fs = add(MagicConstant, rounding_mode);
1847 if (fs != opOK && fs != opInexact)
1848 return fs;
1849
1850 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001851
1852 // Restore the input sign.
1853 if (inputSign != isNegative())
1854 changeSign();
1855
Owen Andersona40319b2012-08-13 23:32:49 +00001856 return fs;
1857}
1858
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001859
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001860/* Comparison requires normalized numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001861IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001862 cmpResult result;
1863
1864 assert(semantics == rhs.semantics);
1865
Michael Gottesman9b877e12013-06-24 09:57:57 +00001866 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001867 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001868 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001869
Michael Gottesman9b877e12013-06-24 09:57:57 +00001870 case PackCategoriesIntoKey(fcNaN, fcZero):
1871 case PackCategoriesIntoKey(fcNaN, fcNormal):
1872 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1873 case PackCategoriesIntoKey(fcNaN, fcNaN):
1874 case PackCategoriesIntoKey(fcZero, fcNaN):
1875 case PackCategoriesIntoKey(fcNormal, fcNaN):
1876 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001877 return cmpUnordered;
1878
Michael Gottesman9b877e12013-06-24 09:57:57 +00001879 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1880 case PackCategoriesIntoKey(fcInfinity, fcZero):
1881 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001882 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001883 return cmpLessThan;
1884 else
1885 return cmpGreaterThan;
1886
Michael Gottesman9b877e12013-06-24 09:57:57 +00001887 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1888 case PackCategoriesIntoKey(fcZero, fcInfinity):
1889 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001890 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001891 return cmpGreaterThan;
1892 else
1893 return cmpLessThan;
1894
Michael Gottesman9b877e12013-06-24 09:57:57 +00001895 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001896 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001897 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001898 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001899 return cmpLessThan;
1900 else
1901 return cmpGreaterThan;
1902
Michael Gottesman9b877e12013-06-24 09:57:57 +00001903 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001904 return cmpEqual;
1905
Michael Gottesman9b877e12013-06-24 09:57:57 +00001906 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001907 break;
1908 }
1909
1910 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001911 if (sign != rhs.sign) {
1912 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001913 result = cmpLessThan;
1914 else
1915 result = cmpGreaterThan;
1916 } else {
1917 /* Compare absolute values; invert result if negative. */
1918 result = compareAbsoluteValue(rhs);
1919
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001920 if (sign) {
1921 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001922 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001923 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001924 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001925 }
1926 }
1927
1928 return result;
1929}
1930
Tim Shen85de51d2016-10-25 19:55:59 +00001931/// IEEEFloat::convert - convert a value of one floating point type to another.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001932/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1933/// records whether the transformation lost information, i.e. whether
1934/// converting the result back to the original type will produce the
1935/// original value (this is almost the same as return value==fsOK, but there
1936/// are edge cases where this is not so).
1937
Tim Shen85de51d2016-10-25 19:55:59 +00001938IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics,
1939 roundingMode rounding_mode,
1940 bool *losesInfo) {
Neil Bootha8d72692007-09-22 02:56:19 +00001941 lostFraction lostFraction;
1942 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001943 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001944 int shift;
1945 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001946
Neil Bootha8d72692007-09-22 02:56:19 +00001947 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001948 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001949 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001950 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001951
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001952 bool X86SpecialNan = false;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001953 if (&fromSemantics == &semX87DoubleExtended &&
1954 &toSemantics != &semX87DoubleExtended && category == fcNaN &&
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001955 (!(*significandParts() & 0x8000000000000000ULL) ||
1956 !(*significandParts() & 0x4000000000000000ULL))) {
1957 // x86 has some unusual NaNs which cannot be represented in any other
1958 // format; note them here.
1959 X86SpecialNan = true;
1960 }
1961
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00001962 // If this is a truncation of a denormal number, and the target semantics
1963 // has larger exponent range than the source semantics (this can happen
1964 // when truncating from PowerPC double-double to double format), the
1965 // right shift could lose result mantissa bits. Adjust exponent instead
1966 // of performing excessive shift.
1967 if (shift < 0 && isFiniteNonZero()) {
1968 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1969 if (exponent + exponentChange < toSemantics.minExponent)
1970 exponentChange = toSemantics.minExponent - exponent;
1971 if (exponentChange < shift)
1972 exponentChange = shift;
1973 if (exponentChange < 0) {
1974 shift -= exponentChange;
1975 exponent += exponentChange;
1976 }
1977 }
1978
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001979 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00001980 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001981 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1982
1983 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00001984 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001985 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001986 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001987 newParts = new integerPart[newPartCount];
1988 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00001989 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001990 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001991 freeSignificand();
1992 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001993 } else if (newPartCount == 1 && oldPartCount != 1) {
1994 // Switch to built-in storage for a single part.
1995 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00001996 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001997 newPart = significandParts()[0];
1998 freeSignificand();
1999 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002000 }
2001
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002002 // Now that we have the right storage, switch the semantics.
2003 semantics = &toSemantics;
2004
2005 // If this is an extension, perform the shift now that the storage is
2006 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00002007 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002008 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2009
Michael Gottesman8136c382013-06-26 23:17:28 +00002010 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00002011 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002012 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002013 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002014 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002015
2016 // For x87 extended precision, we want to make a NaN, not a special NaN if
2017 // the input wasn't special either.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002018 if (!X86SpecialNan && semantics == &semX87DoubleExtended)
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002019 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2020
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002021 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2022 // does not give you back the same bits. This is dubious, and we
2023 // don't currently do it. You're really supposed to get
2024 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002025 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002026 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002027 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002028 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002029 }
2030
2031 return fs;
2032}
2033
2034/* Convert a floating point number to an integer according to the
2035 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002036 returns an invalid operation exception and the contents of the
2037 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002038 range but the floating point number is not the exact integer, the C
2039 standard doesn't require an inexact exception to be raised. IEEE
2040 854 does require it so we do that.
2041
2042 Note that for conversions to integer type the C standard requires
2043 round-to-zero to always be used. */
Tim Shen85de51d2016-10-25 19:55:59 +00002044IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
2045 integerPart *parts, unsigned int width, bool isSigned,
2046 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002047 lostFraction lost_fraction;
2048 const integerPart *src;
2049 unsigned int dstPartsCount, truncatedBits;
2050
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002051 *isExact = false;
2052
Neil Booth618d0fc2007-11-01 22:43:37 +00002053 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002054 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002055 return opInvalidOp;
2056
2057 dstPartsCount = partCountForBits(width);
2058
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002059 if (category == fcZero) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002060 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002061 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002062 *isExact = !sign;
2063 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002064 }
2065
2066 src = significandParts();
2067
2068 /* Step 1: place our absolute value, with any fraction truncated, in
2069 the destination. */
2070 if (exponent < 0) {
2071 /* Our absolute value is less than one; truncate everything. */
2072 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002073 /* For exponent -1 the integer bit represents .5, look at that.
2074 For smaller exponents leftmost truncated bit is 0. */
2075 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002076 } else {
2077 /* We want the most significant (exponent + 1) bits; the rest are
2078 truncated. */
2079 unsigned int bits = exponent + 1U;
2080
2081 /* Hopelessly large in magnitude? */
2082 if (bits > width)
2083 return opInvalidOp;
2084
2085 if (bits < semantics->precision) {
2086 /* We truncate (semantics->precision - bits) bits. */
2087 truncatedBits = semantics->precision - bits;
2088 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2089 } else {
2090 /* We want at least as many bits as are available. */
2091 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2092 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2093 truncatedBits = 0;
2094 }
2095 }
2096
2097 /* Step 2: work out any lost fraction, and increment the absolute
2098 value if we would round away from zero. */
2099 if (truncatedBits) {
2100 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2101 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002102 if (lost_fraction != lfExactlyZero &&
2103 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002104 if (APInt::tcIncrement(parts, dstPartsCount))
2105 return opInvalidOp; /* Overflow. */
2106 }
2107 } else {
2108 lost_fraction = lfExactlyZero;
2109 }
2110
2111 /* Step 3: check if we fit in the destination. */
2112 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2113
2114 if (sign) {
2115 if (!isSigned) {
2116 /* Negative numbers cannot be represented as unsigned. */
2117 if (omsb != 0)
2118 return opInvalidOp;
2119 } else {
2120 /* It takes omsb bits to represent the unsigned integer value.
2121 We lose a bit for the sign, but care is needed as the
2122 maximally negative integer is a special case. */
2123 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2124 return opInvalidOp;
2125
2126 /* This case can happen because of rounding. */
2127 if (omsb > width)
2128 return opInvalidOp;
2129 }
2130
2131 APInt::tcNegate (parts, dstPartsCount);
2132 } else {
2133 if (omsb >= width + !isSigned)
2134 return opInvalidOp;
2135 }
2136
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002137 if (lost_fraction == lfExactlyZero) {
2138 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002139 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002140 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002141 return opInexact;
2142}
2143
2144/* Same as convertToSignExtendedInteger, except we provide
2145 deterministic values in case of an invalid operation exception,
2146 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002147 for underflow or overflow.
2148 The *isExact output tells whether the result is exact, in the sense
2149 that converting it back to the original floating point type produces
2150 the original value. This is almost equivalent to result==opOK,
2151 except for negative zeroes.
2152*/
Tim Shen85de51d2016-10-25 19:55:59 +00002153IEEEFloat::opStatus IEEEFloat::convertToInteger(integerPart *parts,
2154 unsigned int width,
2155 bool isSigned,
2156 roundingMode rounding_mode,
2157 bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002158 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002159
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002160 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002161 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002162
Neil Booth618d0fc2007-11-01 22:43:37 +00002163 if (fs == opInvalidOp) {
2164 unsigned int bits, dstPartsCount;
2165
2166 dstPartsCount = partCountForBits(width);
2167
2168 if (category == fcNaN)
2169 bits = 0;
2170 else if (sign)
2171 bits = isSigned;
2172 else
2173 bits = width - isSigned;
2174
2175 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2176 if (sign && isSigned)
2177 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002178 }
2179
Neil Booth618d0fc2007-11-01 22:43:37 +00002180 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002181}
2182
Neil Booth6c1c8582007-10-07 12:07:53 +00002183/* Convert an unsigned integer SRC to a floating point number,
2184 rounding according to ROUNDING_MODE. The sign of the floating
2185 point number is not modified. */
Tim Shen85de51d2016-10-25 19:55:59 +00002186IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2187 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
Neil Booth49c6aab2007-10-08 14:39:42 +00002188 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002189 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002190 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002191
2192 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002193 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002194 dst = significandParts();
2195 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002196 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002197
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002198 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002199 be that many; extract what we can. */
2200 if (precision <= omsb) {
2201 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002202 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002203 omsb - precision);
2204 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2205 } else {
2206 exponent = precision - 1;
2207 lost_fraction = lfExactlyZero;
2208 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002209 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002210
2211 return normalize(rounding_mode, lost_fraction);
2212}
2213
Tim Shen85de51d2016-10-25 19:55:59 +00002214IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned,
2215 roundingMode rounding_mode) {
Dan Gohman35723eb2008-02-29 01:26:11 +00002216 unsigned int partCount = Val.getNumWords();
2217 APInt api = Val;
2218
2219 sign = false;
2220 if (isSigned && api.isNegative()) {
2221 sign = true;
2222 api = -api;
2223 }
2224
2225 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2226}
2227
Neil Booth03f58ab2007-10-07 12:15:41 +00002228/* Convert a two's complement integer SRC to a floating point number,
2229 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2230 integer is signed, in which case it must be sign-extended. */
Tim Shen85de51d2016-10-25 19:55:59 +00002231IEEEFloat::opStatus
2232IEEEFloat::convertFromSignExtendedInteger(const integerPart *src,
2233 unsigned int srcCount, bool isSigned,
2234 roundingMode rounding_mode) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002235 opStatus status;
2236
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002237 if (isSigned &&
2238 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002239 integerPart *copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002240
2241 /* If we're signed and negative negate a copy. */
2242 sign = true;
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002243 copy = new integerPart[srcCount];
Neil Booth03f58ab2007-10-07 12:15:41 +00002244 APInt::tcAssign(copy, src, srcCount);
2245 APInt::tcNegate(copy, srcCount);
2246 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002247 delete [] copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002248 } else {
2249 sign = false;
2250 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2251 }
2252
2253 return status;
2254}
2255
Neil Booth5f009732007-10-07 11:45:55 +00002256/* FIXME: should this just take a const APInt reference? */
Tim Shen85de51d2016-10-25 19:55:59 +00002257IEEEFloat::opStatus
2258IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2259 unsigned int width, bool isSigned,
2260 roundingMode rounding_mode) {
Dale Johannesen42305122007-09-21 22:09:37 +00002261 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002262 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002263
2264 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002265 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002266 sign = true;
2267 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002268 }
2269
Neil Boothba205222007-10-07 12:10:57 +00002270 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002271}
2272
Tim Shen85de51d2016-10-25 19:55:59 +00002273IEEEFloat::opStatus
2274IEEEFloat::convertFromHexadecimalString(StringRef s,
2275 roundingMode rounding_mode) {
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002276 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002277
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002278 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002279 zeroSignificand();
2280 exponent = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002281
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002282 integerPart *significand = significandParts();
2283 unsigned partsCount = partCount();
2284 unsigned bitPos = partsCount * integerPartWidth;
2285 bool computedTrailingFraction = false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002286
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002287 // Skip leading zeroes and any (hexa)decimal point.
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002288 StringRef::iterator begin = s.begin();
2289 StringRef::iterator end = s.end();
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002290 StringRef::iterator dot;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002291 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002292 StringRef::iterator firstSignificantDigit = p;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002293
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002294 while (p != end) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002295 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002296
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002297 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002298 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002299 dot = p++;
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002300 continue;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002301 }
2302
2303 hex_value = hexDigitValue(*p);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002304 if (hex_value == -1U)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002305 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002306
2307 p++;
2308
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002309 // Store the number while we have space.
2310 if (bitPos) {
2311 bitPos -= 4;
2312 hex_value <<= bitPos % integerPartWidth;
2313 significand[bitPos / integerPartWidth] |= hex_value;
2314 } else if (!computedTrailingFraction) {
2315 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2316 computedTrailingFraction = true;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002317 }
2318 }
2319
2320 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002321 assert(p != end && "Hex strings require an exponent");
2322 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2323 assert(p != begin && "Significand has no digits");
2324 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002325
2326 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002327 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002328 int expAdjustment;
2329
2330 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002331 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002332 dot = p;
2333
2334 /* Calculate the exponent adjustment implicit in the number of
2335 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002336 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002337 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002338 expAdjustment++;
2339 expAdjustment = expAdjustment * 4 - 1;
2340
2341 /* Adjust for writing the significand starting at the most
2342 significant nibble. */
2343 expAdjustment += semantics->precision;
2344 expAdjustment -= partsCount * integerPartWidth;
2345
2346 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002347 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002348 }
2349
2350 return normalize(rounding_mode, lost_fraction);
2351}
2352
Tim Shen85de51d2016-10-25 19:55:59 +00002353IEEEFloat::opStatus
2354IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2355 unsigned sigPartCount, int exp,
2356 roundingMode rounding_mode) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002357 unsigned int parts, pow5PartCount;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00002358 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002359 integerPart pow5Parts[maxPowerOfFiveParts];
2360 bool isNearest;
2361
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002362 isNearest = (rounding_mode == rmNearestTiesToEven ||
2363 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002364
2365 parts = partCountForBits(semantics->precision + 11);
2366
2367 /* Calculate pow(5, abs(exp)). */
2368 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2369
2370 for (;; parts *= 2) {
2371 opStatus sigStatus, powStatus;
2372 unsigned int excessPrecision, truncatedBits;
2373
2374 calcSemantics.precision = parts * integerPartWidth - 1;
2375 excessPrecision = calcSemantics.precision - semantics->precision;
2376 truncatedBits = excessPrecision;
2377
Tim Shen139a58f2016-10-27 22:52:40 +00002378 IEEEFloat decSig(calcSemantics, uninitialized);
2379 decSig.makeZero(sign);
Tim Shen85de51d2016-10-25 19:55:59 +00002380 IEEEFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002381
2382 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2383 rmNearestTiesToEven);
2384 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2385 rmNearestTiesToEven);
2386 /* Add exp, as 10^n = 5^n * 2^n. */
2387 decSig.exponent += exp;
2388
2389 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002390 integerPart HUerr, HUdistance;
2391 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002392
2393 if (exp >= 0) {
2394 /* multiplySignificand leaves the precision-th bit set to 1. */
Craig Topperc10719f2014-04-07 04:17:22 +00002395 calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
Neil Boothb93d90e2007-10-12 16:02:31 +00002396 powHUerr = powStatus != opOK;
2397 } else {
2398 calcLostFraction = decSig.divideSignificand(pow5);
2399 /* Denormal numbers have less precision. */
2400 if (decSig.exponent < semantics->minExponent) {
2401 excessPrecision += (semantics->minExponent - decSig.exponent);
2402 truncatedBits = excessPrecision;
2403 if (excessPrecision > calcSemantics.precision)
2404 excessPrecision = calcSemantics.precision;
2405 }
2406 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002407 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002408 }
2409
2410 /* Both multiplySignificand and divideSignificand return the
2411 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002412 assert(APInt::tcExtractBit
2413 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002414
2415 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2416 powHUerr);
2417 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2418 excessPrecision, isNearest);
2419
2420 /* Are we guaranteed to round correctly if we truncate? */
2421 if (HUdistance >= HUerr) {
2422 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2423 calcSemantics.precision - excessPrecision,
2424 excessPrecision);
2425 /* Take the exponent of decSig. If we tcExtract-ed less bits
2426 above we must adjust our exponent to compensate for the
2427 implicit right shift. */
2428 exponent = (decSig.exponent + semantics->precision
2429 - (calcSemantics.precision - excessPrecision));
2430 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2431 decSig.partCount(),
2432 truncatedBits);
2433 return normalize(rounding_mode, calcLostFraction);
2434 }
2435 }
2436}
2437
Tim Shen85de51d2016-10-25 19:55:59 +00002438IEEEFloat::opStatus
2439IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
Neil Booth4ed401b2007-10-14 10:16:12 +00002440 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002441 opStatus fs;
2442
Neil Booth4ed401b2007-10-14 10:16:12 +00002443 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002444 StringRef::iterator p = str.begin();
2445 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002446
Neil Booth91305512007-10-15 15:00:55 +00002447 /* Handle the quick cases. First the case of no significant digits,
2448 i.e. zero, and then exponents that are obviously too large or too
2449 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2450 definitely overflows if
2451
2452 (exp - 1) * L >= maxExponent
2453
2454 and definitely underflows to zero where
2455
2456 (exp + 1) * L <= minExponent - precision
2457
2458 With integer arithmetic the tightest bounds for L are
2459
2460 93/28 < L < 196/59 [ numerator <= 256 ]
2461 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2462 */
2463
Michael Gottesman228156c2013-07-01 23:54:08 +00002464 // Test if we have a zero number allowing for strings with no null terminators
2465 // and zero decimals with non-zero exponents.
2466 //
2467 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2468 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2469 // be at most one dot. On the other hand, if we have a zero with a non-zero
2470 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002471 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002472 category = fcZero;
2473 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002474
2475 /* Check whether the normalized exponent is high enough to overflow
2476 max during the log-rebasing in the max-exponent check below. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002477 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
John McCallb42cc682010-02-26 22:20:41 +00002478 fs = handleOverflow(rounding_mode);
2479
2480 /* If it wasn't, then it also wasn't high enough to overflow max
2481 during the log-rebasing in the min-exponent check. Check that it
2482 won't overflow min in either check, then perform the min-exponent
2483 check. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002484 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
John McCallb42cc682010-02-26 22:20:41 +00002485 (D.normalizedExponent + 1) * 28738 <=
2486 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002487 /* Underflow to zero and round. */
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002488 category = fcNormal;
Neil Booth91305512007-10-15 15:00:55 +00002489 zeroSignificand();
2490 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002491
2492 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002493 } else if ((D.normalizedExponent - 1) * 42039
2494 >= 12655 * semantics->maxExponent) {
2495 /* Overflow and round. */
2496 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002497 } else {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002498 integerPart *decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002499 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002500
Neil Booth4ed401b2007-10-14 10:16:12 +00002501 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002502 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002503 to hold the full significand, and an extra part required by
2504 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002505 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002506 partCount = partCountForBits(1 + 196 * partCount / 59);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002507 decSignificand = new integerPart[partCount + 1];
Neil Booth4ed401b2007-10-14 10:16:12 +00002508 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002509
Neil Booth4ed401b2007-10-14 10:16:12 +00002510 /* Convert to binary efficiently - we do almost all multiplication
2511 in an integerPart. When this would overflow do we do a single
2512 bignum multiplication, and then revert again to multiplication
2513 in an integerPart. */
2514 do {
2515 integerPart decValue, val, multiplier;
2516
2517 val = 0;
2518 multiplier = 1;
2519
2520 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002521 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002522 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002523 if (p == str.end()) {
2524 break;
2525 }
2526 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002527 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002528 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002529 multiplier *= 10;
2530 val = val * 10 + decValue;
2531 /* The maximum number that can be multiplied by ten with any
2532 digit added without overflowing an integerPart. */
2533 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2534
2535 /* Multiply out the current part. */
2536 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2537 partCount, partCount + 1, false);
2538
2539 /* If we used another part (likely but not guaranteed), increase
2540 the count. */
2541 if (decSignificand[partCount])
2542 partCount++;
2543 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002544
Neil Boothae077d22007-11-01 22:51:07 +00002545 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002546 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002547 D.exponent, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002548
2549 delete [] decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002550 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002551
2552 return fs;
2553}
2554
Tim Shen85de51d2016-10-25 19:55:59 +00002555bool IEEEFloat::convertFromStringSpecials(StringRef str) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002556 if (str.equals("inf") || str.equals("INFINITY")) {
2557 makeInf(false);
2558 return true;
2559 }
2560
2561 if (str.equals("-inf") || str.equals("-INFINITY")) {
2562 makeInf(true);
2563 return true;
2564 }
2565
2566 if (str.equals("nan") || str.equals("NaN")) {
2567 makeNaN(false, false);
2568 return true;
2569 }
2570
2571 if (str.equals("-nan") || str.equals("-NaN")) {
2572 makeNaN(false, true);
2573 return true;
2574 }
2575
2576 return false;
2577}
2578
Tim Shen85de51d2016-10-25 19:55:59 +00002579IEEEFloat::opStatus IEEEFloat::convertFromString(StringRef str,
2580 roundingMode rounding_mode) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002581 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002582
Michael Gottesman40e8a182013-06-24 09:58:05 +00002583 // Handle special cases.
2584 if (convertFromStringSpecials(str))
2585 return opOK;
2586
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002587 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002588 StringRef::iterator p = str.begin();
2589 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002590 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002591 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002592 p++;
2593 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002594 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002595 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002596
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002597 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002598 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002599 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002600 rounding_mode);
2601 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002602
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002603 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002604}
Dale Johannesena719a602007-08-24 00:56:33 +00002605
Neil Booth8f1946f2007-10-03 22:26:02 +00002606/* Write out a hexadecimal representation of the floating point value
2607 to DST, which must be of sufficient size, in the C99 form
2608 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2609 excluding the terminating NUL.
2610
2611 If UPPERCASE, the output is in upper case, otherwise in lower case.
2612
2613 HEXDIGITS digits appear altogether, rounding the value if
2614 necessary. If HEXDIGITS is 0, the minimal precision to display the
2615 number precisely is used instead. If nothing would appear after
2616 the decimal point it is suppressed.
2617
2618 The decimal exponent is always printed and has at least one digit.
2619 Zero values display an exponent of zero. Infinities and NaNs
2620 appear as "infinity" or "nan" respectively.
2621
2622 The above rules are as specified by C99. There is ambiguity about
2623 what the leading hexadecimal digit should be. This implementation
2624 uses whatever is necessary so that the exponent is displayed as
2625 stored. This implies the exponent will fall within the IEEE format
2626 range, and the leading hexadecimal digit will be 0 (for denormals),
2627 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2628 any other digits zero).
2629*/
Tim Shen85de51d2016-10-25 19:55:59 +00002630unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
2631 bool upperCase,
2632 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002633 char *p;
2634
2635 p = dst;
2636 if (sign)
2637 *dst++ = '-';
2638
2639 switch (category) {
2640 case fcInfinity:
2641 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2642 dst += sizeof infinityL - 1;
2643 break;
2644
2645 case fcNaN:
2646 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2647 dst += sizeof NaNU - 1;
2648 break;
2649
2650 case fcZero:
2651 *dst++ = '0';
2652 *dst++ = upperCase ? 'X': 'x';
2653 *dst++ = '0';
2654 if (hexDigits > 1) {
2655 *dst++ = '.';
2656 memset (dst, '0', hexDigits - 1);
2657 dst += hexDigits - 1;
2658 }
2659 *dst++ = upperCase ? 'P': 'p';
2660 *dst++ = '0';
2661 break;
2662
2663 case fcNormal:
2664 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2665 break;
2666 }
2667
2668 *dst = 0;
2669
Evan Cheng82b9e962008-05-02 21:15:08 +00002670 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002671}
2672
2673/* Does the hard work of outputting the correctly rounded hexadecimal
2674 form of a normal floating point number with the specified number of
2675 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2676 digits necessary to print the value precisely is output. */
Tim Shen85de51d2016-10-25 19:55:59 +00002677char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2678 bool upperCase,
2679 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002680 unsigned int count, valueBits, shift, partsCount, outputDigits;
2681 const char *hexDigitChars;
2682 const integerPart *significand;
2683 char *p;
2684 bool roundUp;
2685
2686 *dst++ = '0';
2687 *dst++ = upperCase ? 'X': 'x';
2688
2689 roundUp = false;
2690 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2691
2692 significand = significandParts();
2693 partsCount = partCount();
2694
2695 /* +3 because the first digit only uses the single integer bit, so
2696 we have 3 virtual zero most-significant-bits. */
2697 valueBits = semantics->precision + 3;
2698 shift = integerPartWidth - valueBits % integerPartWidth;
2699
2700 /* The natural number of digits required ignoring trailing
2701 insignificant zeroes. */
2702 outputDigits = (valueBits - significandLSB () + 3) / 4;
2703
2704 /* hexDigits of zero means use the required number for the
2705 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002706 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002707 if (hexDigits) {
2708 if (hexDigits < outputDigits) {
2709 /* We are dropping non-zero bits, so need to check how to round.
2710 "bits" is the number of dropped bits. */
2711 unsigned int bits;
2712 lostFraction fraction;
2713
2714 bits = valueBits - hexDigits * 4;
2715 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2716 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2717 }
2718 outputDigits = hexDigits;
2719 }
2720
2721 /* Write the digits consecutively, and start writing in the location
2722 of the hexadecimal point. We move the most significant digit
2723 left and add the hexadecimal point later. */
2724 p = ++dst;
2725
2726 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2727
2728 while (outputDigits && count) {
2729 integerPart part;
2730
2731 /* Put the most significant integerPartWidth bits in "part". */
2732 if (--count == partsCount)
2733 part = 0; /* An imaginary higher zero part. */
2734 else
2735 part = significand[count] << shift;
2736
2737 if (count && shift)
2738 part |= significand[count - 1] >> (integerPartWidth - shift);
2739
2740 /* Convert as much of "part" to hexdigits as we can. */
2741 unsigned int curDigits = integerPartWidth / 4;
2742
2743 if (curDigits > outputDigits)
2744 curDigits = outputDigits;
2745 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2746 outputDigits -= curDigits;
2747 }
2748
2749 if (roundUp) {
2750 char *q = dst;
2751
2752 /* Note that hexDigitChars has a trailing '0'. */
2753 do {
2754 q--;
2755 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002756 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002757 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002758 } else {
2759 /* Add trailing zeroes. */
2760 memset (dst, '0', outputDigits);
2761 dst += outputDigits;
2762 }
2763
2764 /* Move the most significant digit to before the point, and if there
2765 is something after the decimal point add it. This must come
2766 after rounding above. */
2767 p[-1] = p[0];
2768 if (dst -1 == p)
2769 dst--;
2770 else
2771 p[0] = '.';
2772
2773 /* Finally output the exponent. */
2774 *dst++ = upperCase ? 'P': 'p';
2775
Neil Booth32897f52007-10-06 07:29:25 +00002776 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002777}
2778
Tim Shen85de51d2016-10-25 19:55:59 +00002779hash_code hash_value(const IEEEFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002780 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002781 return hash_combine((uint8_t)Arg.category,
2782 // NaN has no sign, fix it at zero.
2783 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2784 Arg.semantics->precision);
2785
2786 // Normal floats need their exponent and significand hashed.
2787 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2788 Arg.semantics->precision, Arg.exponent,
2789 hash_combine_range(
2790 Arg.significandParts(),
2791 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002792}
2793
2794// Conversion from APFloat to/from host float/double. It may eventually be
2795// possible to eliminate these and have everybody deal with APFloats, but that
2796// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002797// Current implementation requires integerPartWidth==64, which is correct at
2798// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002799
Dale Johannesen728687c2007-09-05 20:39:49 +00002800// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002801// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002802
Tim Shen85de51d2016-10-25 19:55:59 +00002803APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002804 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002805 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002806
2807 uint64_t myexponent, mysignificand;
2808
Michael Gottesman8136c382013-06-26 23:17:28 +00002809 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002810 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002811 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002812 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2813 myexponent = 0; // denormal
2814 } else if (category==fcZero) {
2815 myexponent = 0;
2816 mysignificand = 0;
2817 } else if (category==fcInfinity) {
2818 myexponent = 0x7fff;
2819 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002820 } else {
2821 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002822 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002823 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002824 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002825
2826 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002827 words[0] = mysignificand;
2828 words[1] = ((uint64_t)(sign & 1) << 15) |
2829 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002830 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002831}
2832
Tim Shen85de51d2016-10-25 19:55:59 +00002833APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00002834 assert(semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy);
Evan Cheng67c90212009-10-27 21:35:42 +00002835 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002836
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002837 uint64_t words[2];
2838 opStatus fs;
2839 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002840
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002841 // Convert number to double. To avoid spurious underflows, we re-
2842 // normalize against the "double" minExponent first, and only *then*
2843 // truncate the mantissa. The result of that second conversion
2844 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002845 // Declare fltSemantics before APFloat that uses it (and
2846 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002847 fltSemantics extendedSemantics = *semantics;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002848 extendedSemantics.minExponent = semIEEEdouble.minExponent;
Tim Shen85de51d2016-10-25 19:55:59 +00002849 IEEEFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002850 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2851 assert(fs == opOK && !losesInfo);
2852 (void)fs;
2853
Tim Shen85de51d2016-10-25 19:55:59 +00002854 IEEEFloat u(extended);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002855 fs = u.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002856 assert(fs == opOK || fs == opInexact);
2857 (void)fs;
2858 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2859
2860 // If conversion was exact or resulted in a special case, we're done;
2861 // just set the second double to zero. Otherwise, re-convert back to
2862 // the extended format and compute the difference. This now should
2863 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002864 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002865 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2866 assert(fs == opOK && !losesInfo);
2867 (void)fs;
2868
Tim Shen85de51d2016-10-25 19:55:59 +00002869 IEEEFloat v(extended);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002870 v.subtract(u, rmNearestTiesToEven);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002871 fs = v.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002872 assert(fs == opOK && !losesInfo);
2873 (void)fs;
2874 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002875 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002876 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002877 }
2878
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002879 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002880}
2881
Tim Shen85de51d2016-10-25 19:55:59 +00002882APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002883 assert(semantics == (const llvm::fltSemantics*)&semIEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002884 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002885
2886 uint64_t myexponent, mysignificand, mysignificand2;
2887
Michael Gottesman8136c382013-06-26 23:17:28 +00002888 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002889 myexponent = exponent+16383; //bias
2890 mysignificand = significandParts()[0];
2891 mysignificand2 = significandParts()[1];
2892 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2893 myexponent = 0; // denormal
2894 } else if (category==fcZero) {
2895 myexponent = 0;
2896 mysignificand = mysignificand2 = 0;
2897 } else if (category==fcInfinity) {
2898 myexponent = 0x7fff;
2899 mysignificand = mysignificand2 = 0;
2900 } else {
2901 assert(category == fcNaN && "Unknown category!");
2902 myexponent = 0x7fff;
2903 mysignificand = significandParts()[0];
2904 mysignificand2 = significandParts()[1];
2905 }
2906
2907 uint64_t words[2];
2908 words[0] = mysignificand;
2909 words[1] = ((uint64_t)(sign & 1) << 63) |
2910 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002911 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002912
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002913 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002914}
2915
Tim Shen85de51d2016-10-25 19:55:59 +00002916APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002917 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002918 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002919
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002920 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002921
Michael Gottesman8136c382013-06-26 23:17:28 +00002922 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002923 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002924 mysignificand = *significandParts();
2925 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2926 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002927 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002928 myexponent = 0;
2929 mysignificand = 0;
2930 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002931 myexponent = 0x7ff;
2932 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002933 } else {
2934 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002935 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002936 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002937 }
Dale Johannesena719a602007-08-24 00:56:33 +00002938
Evan Cheng82b9e962008-05-02 21:15:08 +00002939 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002940 ((myexponent & 0x7ff) << 52) |
2941 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002942}
2943
Tim Shen85de51d2016-10-25 19:55:59 +00002944APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002945 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002946 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002947
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002948 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002949
Michael Gottesman8136c382013-06-26 23:17:28 +00002950 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002951 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00002952 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00002953 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00002954 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002955 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002956 myexponent = 0;
2957 mysignificand = 0;
2958 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002959 myexponent = 0xff;
2960 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002961 } else {
2962 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00002963 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00002964 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002965 }
Dale Johannesena719a602007-08-24 00:56:33 +00002966
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002967 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2968 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00002969}
2970
Tim Shen85de51d2016-10-25 19:55:59 +00002971APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002972 assert(semantics == (const llvm::fltSemantics*)&semIEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00002973 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00002974
2975 uint32_t myexponent, mysignificand;
2976
Michael Gottesman8136c382013-06-26 23:17:28 +00002977 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00002978 myexponent = exponent+15; //bias
2979 mysignificand = (uint32_t)*significandParts();
2980 if (myexponent == 1 && !(mysignificand & 0x400))
2981 myexponent = 0; // denormal
2982 } else if (category==fcZero) {
2983 myexponent = 0;
2984 mysignificand = 0;
2985 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00002986 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002987 mysignificand = 0;
2988 } else {
2989 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00002990 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002991 mysignificand = (uint32_t)*significandParts();
2992 }
2993
2994 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2995 (mysignificand & 0x3ff)));
2996}
2997
Dale Johannesen007aa372007-10-11 18:07:22 +00002998// This function creates an APInt that is just a bit map of the floating
2999// point constant as it would appear in memory. It is not a conversion,
3000// and treating the result as a normal integer is unlikely to be useful.
3001
Tim Shen85de51d2016-10-25 19:55:59 +00003002APInt IEEEFloat::bitcastToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003003 if (semantics == (const llvm::fltSemantics*)&semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003004 return convertHalfAPFloatToAPInt();
3005
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003006 if (semantics == (const llvm::fltSemantics*)&semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003007 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003008
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003009 if (semantics == (const llvm::fltSemantics*)&semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003010 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003011
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003012 if (semantics == (const llvm::fltSemantics*)&semIEEEquad)
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003013 return convertQuadrupleAPFloatToAPInt();
3014
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003015 if (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy)
Dale Johannesen007aa372007-10-11 18:07:22 +00003016 return convertPPCDoubleDoubleAPFloatToAPInt();
3017
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003018 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003019 "unknown format!");
3020 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003021}
3022
Tim Shen85de51d2016-10-25 19:55:59 +00003023float IEEEFloat::convertToFloat() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003024 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle &&
Chris Lattner688f9912009-09-24 21:44:20 +00003025 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003026 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003027 return api.bitsToFloat();
3028}
3029
Tim Shen85de51d2016-10-25 19:55:59 +00003030double IEEEFloat::convertToDouble() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003031 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble &&
Chris Lattner688f9912009-09-24 21:44:20 +00003032 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003033 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003034 return api.bitsToDouble();
3035}
3036
Dale Johannesenfff29952008-10-06 18:22:29 +00003037/// Integer bit is explicit in this format. Intel hardware (387 and later)
3038/// does not support these bit patterns:
3039/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3040/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3041/// exponent = 0, integer bit 1 ("pseudodenormal")
3042/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3043/// At the moment, the first two are treated as NaNs, the second two as Normal.
Tim Shen85de51d2016-10-25 19:55:59 +00003044void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003045 assert(api.getBitWidth()==80);
3046 uint64_t i1 = api.getRawData()[0];
3047 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003048 uint64_t myexponent = (i2 & 0x7fff);
3049 uint64_t mysignificand = i1;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003050
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003051 initialize(&semX87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003052 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003053
Dale Johannesen93eefa02009-03-23 21:16:53 +00003054 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003055 if (myexponent==0 && mysignificand==0) {
3056 // exponent, significand meaningless
3057 category = fcZero;
3058 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3059 // exponent, significand meaningless
3060 category = fcInfinity;
3061 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3062 // exponent meaningless
3063 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003064 significandParts()[0] = mysignificand;
3065 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003066 } else {
3067 category = fcNormal;
3068 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003069 significandParts()[0] = mysignificand;
3070 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003071 if (myexponent==0) // denormal
3072 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003073 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003074}
3075
Tim Shen85de51d2016-10-25 19:55:59 +00003076void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) {
Dale Johannesen007aa372007-10-11 18:07:22 +00003077 assert(api.getBitWidth()==128);
3078 uint64_t i1 = api.getRawData()[0];
3079 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003080 opStatus fs;
3081 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003082
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003083 // Get the first double and convert to our format.
3084 initFromDoubleAPInt(APInt(64, i1));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003085 fs = convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003086 assert(fs == opOK && !losesInfo);
3087 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003088
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003089 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003090 if (isFiniteNonZero()) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003091 IEEEFloat v(semIEEEdouble, APInt(64, i2));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003092 fs = v.convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003093 assert(fs == opOK && !losesInfo);
3094 (void)fs;
3095
3096 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003097 }
3098}
3099
Tim Shen85de51d2016-10-25 19:55:59 +00003100void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003101 assert(api.getBitWidth()==128);
3102 uint64_t i1 = api.getRawData()[0];
3103 uint64_t i2 = api.getRawData()[1];
3104 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3105 uint64_t mysignificand = i1;
3106 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3107
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003108 initialize(&semIEEEquad);
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003109 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003110
3111 sign = static_cast<unsigned int>(i2>>63);
3112 if (myexponent==0 &&
3113 (mysignificand==0 && mysignificand2==0)) {
3114 // exponent, significand meaningless
3115 category = fcZero;
3116 } else if (myexponent==0x7fff &&
3117 (mysignificand==0 && mysignificand2==0)) {
3118 // exponent, significand meaningless
3119 category = fcInfinity;
3120 } else if (myexponent==0x7fff &&
3121 (mysignificand!=0 || mysignificand2 !=0)) {
3122 // exponent meaningless
3123 category = fcNaN;
3124 significandParts()[0] = mysignificand;
3125 significandParts()[1] = mysignificand2;
3126 } else {
3127 category = fcNormal;
3128 exponent = myexponent - 16383;
3129 significandParts()[0] = mysignificand;
3130 significandParts()[1] = mysignificand2;
3131 if (myexponent==0) // denormal
3132 exponent = -16382;
3133 else
3134 significandParts()[1] |= 0x1000000000000LL; // integer bit
3135 }
3136}
3137
Tim Shen85de51d2016-10-25 19:55:59 +00003138void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003139 assert(api.getBitWidth()==64);
3140 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003141 uint64_t myexponent = (i >> 52) & 0x7ff;
3142 uint64_t mysignificand = i & 0xfffffffffffffLL;
3143
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003144 initialize(&semIEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003145 assert(partCount()==1);
3146
Evan Cheng82b9e962008-05-02 21:15:08 +00003147 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003148 if (myexponent==0 && mysignificand==0) {
3149 // exponent, significand meaningless
3150 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003151 } else if (myexponent==0x7ff && mysignificand==0) {
3152 // exponent, significand meaningless
3153 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003154 } else if (myexponent==0x7ff && mysignificand!=0) {
3155 // exponent meaningless
3156 category = fcNaN;
3157 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003158 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003159 category = fcNormal;
3160 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003161 *significandParts() = mysignificand;
3162 if (myexponent==0) // denormal
3163 exponent = -1022;
3164 else
3165 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003166 }
Dale Johannesena719a602007-08-24 00:56:33 +00003167}
3168
Tim Shen85de51d2016-10-25 19:55:59 +00003169void IEEEFloat::initFromFloatAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003170 assert(api.getBitWidth()==32);
3171 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003172 uint32_t myexponent = (i >> 23) & 0xff;
3173 uint32_t mysignificand = i & 0x7fffff;
3174
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003175 initialize(&semIEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003176 assert(partCount()==1);
3177
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003178 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003179 if (myexponent==0 && mysignificand==0) {
3180 // exponent, significand meaningless
3181 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003182 } else if (myexponent==0xff && mysignificand==0) {
3183 // exponent, significand meaningless
3184 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003185 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003186 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003187 category = fcNaN;
3188 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003189 } else {
3190 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003191 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003192 *significandParts() = mysignificand;
3193 if (myexponent==0) // denormal
3194 exponent = -126;
3195 else
3196 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003197 }
3198}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003199
Tim Shen85de51d2016-10-25 19:55:59 +00003200void IEEEFloat::initFromHalfAPInt(const APInt &api) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003201 assert(api.getBitWidth()==16);
3202 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003203 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003204 uint32_t mysignificand = i & 0x3ff;
3205
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003206 initialize(&semIEEEhalf);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003207 assert(partCount()==1);
3208
3209 sign = i >> 15;
3210 if (myexponent==0 && mysignificand==0) {
3211 // exponent, significand meaningless
3212 category = fcZero;
3213 } else if (myexponent==0x1f && mysignificand==0) {
3214 // exponent, significand meaningless
3215 category = fcInfinity;
3216 } else if (myexponent==0x1f && mysignificand!=0) {
3217 // sign, exponent, significand meaningless
3218 category = fcNaN;
3219 *significandParts() = mysignificand;
3220 } else {
3221 category = fcNormal;
3222 exponent = myexponent - 15; //bias
3223 *significandParts() = mysignificand;
3224 if (myexponent==0) // denormal
3225 exponent = -14;
3226 else
3227 *significandParts() |= 0x400; // integer bit
3228 }
3229}
3230
Dale Johannesen245dceb2007-09-11 18:32:33 +00003231/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003232/// we infer the floating point type from the size of the APInt. The
3233/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3234/// when the size is anything else).
Tim Shen85de51d2016-10-25 19:55:59 +00003235void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003236 if (Sem == &semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003237 return initFromHalfAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003238 if (Sem == &semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003239 return initFromFloatAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003240 if (Sem == &semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003241 return initFromDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003242 if (Sem == &semX87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003243 return initFromF80LongDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003244 if (Sem == &semIEEEquad)
Tim Northover29178a32013-01-22 09:46:31 +00003245 return initFromQuadrupleAPInt(api);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003246 if (Sem == &semPPCDoubleDoubleLegacy)
Tim Northover29178a32013-01-22 09:46:31 +00003247 return initFromPPCDoubleDoubleAPInt(api);
3248
Craig Topper2617dcc2014-04-15 06:32:26 +00003249 llvm_unreachable(nullptr);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003250}
3251
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003252/// Make this number the largest magnitude normal number in the given
3253/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003254void IEEEFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003255 // We want (in interchange format):
3256 // sign = {Negative}
3257 // exponent = 1..10
3258 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003259 category = fcNormal;
3260 sign = Negative;
3261 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003262
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003263 // Use memset to set all but the highest integerPart to all ones.
3264 integerPart *significand = significandParts();
3265 unsigned PartCount = partCount();
3266 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003267
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003268 // Set the high integerPart especially setting all unused top bits for
3269 // internal consistency.
3270 const unsigned NumUnusedHighBits =
3271 PartCount*integerPartWidth - semantics->precision;
Alexey Samsonovba1ecbc2014-09-06 00:41:19 +00003272 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3273 ? (~integerPart(0) >> NumUnusedHighBits)
3274 : 0;
John McCall29b5c282009-12-24 08:56:26 +00003275}
3276
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003277/// Make this number the smallest magnitude denormal number in the given
3278/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003279void IEEEFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003280 // We want (in interchange format):
3281 // sign = {Negative}
3282 // exponent = 0..0
3283 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003284 category = fcNormal;
3285 sign = Negative;
3286 exponent = semantics->minExponent;
3287 APInt::tcSet(significandParts(), 1, partCount());
3288}
John McCall29b5c282009-12-24 08:56:26 +00003289
Tim Shen139a58f2016-10-27 22:52:40 +00003290void IEEEFloat::makeSmallestNormalized(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003291 // We want (in interchange format):
3292 // sign = {Negative}
3293 // exponent = 0..0
3294 // significand = 10..0
3295
Tim Shen139a58f2016-10-27 22:52:40 +00003296 category = fcNormal;
3297 zeroSignificand();
3298 sign = Negative;
3299 exponent = semantics->minExponent;
3300 significandParts()[partCountForBits(semantics->precision) - 1] |=
3301 (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003302}
3303
Tim Shen85de51d2016-10-25 19:55:59 +00003304IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
Tim Northover29178a32013-01-22 09:46:31 +00003305 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003306}
3307
Tim Shen85de51d2016-10-25 19:55:59 +00003308IEEEFloat::IEEEFloat(float f) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003309 initFromAPInt(&semIEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003310}
3311
Tim Shen85de51d2016-10-25 19:55:59 +00003312IEEEFloat::IEEEFloat(double d) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003313 initFromAPInt(&semIEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003314}
John McCall29b5c282009-12-24 08:56:26 +00003315
3316namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003317 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3318 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003319 }
3320
John McCalle6212ace2009-12-24 12:16:56 +00003321 /// Removes data from the given significand until it is no more
3322 /// precise than is required for the desired precision.
3323 void AdjustToPrecision(APInt &significand,
3324 int &exp, unsigned FormatPrecision) {
3325 unsigned bits = significand.getActiveBits();
3326
3327 // 196/59 is a very slight overestimate of lg_2(10).
3328 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3329
3330 if (bits <= bitsRequired) return;
3331
3332 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3333 if (!tensRemovable) return;
3334
3335 exp += tensRemovable;
3336
3337 APInt divisor(significand.getBitWidth(), 1);
3338 APInt powten(significand.getBitWidth(), 10);
3339 while (true) {
3340 if (tensRemovable & 1)
3341 divisor *= powten;
3342 tensRemovable >>= 1;
3343 if (!tensRemovable) break;
3344 powten *= powten;
3345 }
3346
3347 significand = significand.udiv(divisor);
3348
Hao Liube99cc32013-03-20 01:46:36 +00003349 // Truncate the significand down to its active bit count.
3350 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003351 }
3352
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003353
John McCall29b5c282009-12-24 08:56:26 +00003354 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3355 int &exp, unsigned FormatPrecision) {
3356 unsigned N = buffer.size();
3357 if (N <= FormatPrecision) return;
3358
3359 // The most significant figures are the last ones in the buffer.
3360 unsigned FirstSignificant = N - FormatPrecision;
3361
3362 // Round.
3363 // FIXME: this probably shouldn't use 'round half up'.
3364
3365 // Rounding down is just a truncation, except we also want to drop
3366 // trailing zeros from the new result.
3367 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003368 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003369 FirstSignificant++;
3370
3371 exp += FirstSignificant;
3372 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3373 return;
3374 }
3375
3376 // Rounding up requires a decimal add-with-carry. If we continue
3377 // the carry, the newly-introduced zeros will just be truncated.
3378 for (unsigned I = FirstSignificant; I != N; ++I) {
3379 if (buffer[I] == '9') {
3380 FirstSignificant++;
3381 } else {
3382 buffer[I]++;
3383 break;
3384 }
3385 }
3386
3387 // If we carried through, we have exactly one digit of precision.
3388 if (FirstSignificant == N) {
3389 exp += FirstSignificant;
3390 buffer.clear();
3391 buffer.push_back('1');
3392 return;
3393 }
3394
3395 exp += FirstSignificant;
3396 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3397 }
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003398}
John McCall29b5c282009-12-24 08:56:26 +00003399
Tim Shen85de51d2016-10-25 19:55:59 +00003400void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
3401 unsigned FormatMaxPadding) const {
John McCall29b5c282009-12-24 08:56:26 +00003402 switch (category) {
3403 case fcInfinity:
3404 if (isNegative())
3405 return append(Str, "-Inf");
3406 else
3407 return append(Str, "+Inf");
3408
3409 case fcNaN: return append(Str, "NaN");
3410
3411 case fcZero:
3412 if (isNegative())
3413 Str.push_back('-');
3414
3415 if (!FormatMaxPadding)
3416 append(Str, "0.0E+0");
3417 else
3418 Str.push_back('0');
3419 return;
3420
3421 case fcNormal:
3422 break;
3423 }
3424
3425 if (isNegative())
3426 Str.push_back('-');
3427
3428 // Decompose the number into an APInt and an exponent.
3429 int exp = exponent - ((int) semantics->precision - 1);
3430 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003431 makeArrayRef(significandParts(),
3432 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003433
John McCalldd5044a2009-12-24 23:18:09 +00003434 // Set FormatPrecision if zero. We want to do this before we
3435 // truncate trailing zeros, as those are part of the precision.
3436 if (!FormatPrecision) {
Eli Friedmane72f1322013-08-29 23:44:34 +00003437 // We use enough digits so the number can be round-tripped back to an
3438 // APFloat. The formula comes from "How to Print Floating-Point Numbers
3439 // Accurately" by Steele and White.
3440 // FIXME: Using a formula based purely on the precision is conservative;
3441 // we can print fewer digits depending on the actual value being printed.
John McCalldd5044a2009-12-24 23:18:09 +00003442
Eli Friedmane72f1322013-08-29 23:44:34 +00003443 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3444 FormatPrecision = 2 + semantics->precision * 59 / 196;
John McCalldd5044a2009-12-24 23:18:09 +00003445 }
3446
John McCall29b5c282009-12-24 08:56:26 +00003447 // Ignore trailing binary zeros.
3448 int trailingZeros = significand.countTrailingZeros();
3449 exp += trailingZeros;
3450 significand = significand.lshr(trailingZeros);
3451
3452 // Change the exponent from 2^e to 10^e.
3453 if (exp == 0) {
3454 // Nothing to do.
3455 } else if (exp > 0) {
3456 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003457 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003458 significand <<= exp;
3459 exp = 0;
3460 } else { /* exp < 0 */
3461 int texp = -exp;
3462
3463 // We transform this using the identity:
3464 // (N)(2^-e) == (N)(5^e)(10^-e)
3465 // This means we have to multiply N (the significand) by 5^e.
3466 // To avoid overflow, we have to operate on numbers large
3467 // enough to store N * 5^e:
3468 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003469 // <= semantics->precision + e * 137 / 59
3470 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003471
Eli Friedman19546412011-10-07 23:40:49 +00003472 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003473
3474 // Multiply significand by 5^e.
3475 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003476 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003477 APInt five_to_the_i(precision, 5);
3478 while (true) {
3479 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003480
John McCall29b5c282009-12-24 08:56:26 +00003481 texp >>= 1;
3482 if (!texp) break;
3483 five_to_the_i *= five_to_the_i;
3484 }
3485 }
3486
John McCalle6212ace2009-12-24 12:16:56 +00003487 AdjustToPrecision(significand, exp, FormatPrecision);
3488
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003489 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003490
3491 // Fill the buffer.
3492 unsigned precision = significand.getBitWidth();
3493 APInt ten(precision, 10);
3494 APInt digit(precision, 0);
3495
3496 bool inTrail = true;
3497 while (significand != 0) {
3498 // digit <- significand % 10
3499 // significand <- significand / 10
3500 APInt::udivrem(significand, ten, significand, digit);
3501
3502 unsigned d = digit.getZExtValue();
3503
3504 // Drop trailing zeros.
3505 if (inTrail && !d) exp++;
3506 else {
3507 buffer.push_back((char) ('0' + d));
3508 inTrail = false;
3509 }
3510 }
3511
3512 assert(!buffer.empty() && "no characters in buffer!");
3513
3514 // Drop down to FormatPrecision.
3515 // TODO: don't do more precise calculations above than are required.
3516 AdjustToPrecision(buffer, exp, FormatPrecision);
3517
3518 unsigned NDigits = buffer.size();
3519
John McCalldd5044a2009-12-24 23:18:09 +00003520 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003521 bool FormatScientific;
3522 if (!FormatMaxPadding)
3523 FormatScientific = true;
3524 else {
John McCall29b5c282009-12-24 08:56:26 +00003525 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003526 // 765e3 --> 765000
3527 // ^^^
3528 // But we shouldn't make the number look more precise than it is.
3529 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3530 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003531 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003532 // Power of the most significant digit.
3533 int MSD = exp + (int) (NDigits - 1);
3534 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003535 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003536 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003537 } else {
3538 // 765e-5 == 0.00765
3539 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003540 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003541 }
3542 }
John McCall29b5c282009-12-24 08:56:26 +00003543 }
3544
3545 // Scientific formatting is pretty straightforward.
3546 if (FormatScientific) {
3547 exp += (NDigits - 1);
3548
3549 Str.push_back(buffer[NDigits-1]);
3550 Str.push_back('.');
3551 if (NDigits == 1)
3552 Str.push_back('0');
3553 else
3554 for (unsigned I = 1; I != NDigits; ++I)
3555 Str.push_back(buffer[NDigits-1-I]);
3556 Str.push_back('E');
3557
3558 Str.push_back(exp >= 0 ? '+' : '-');
3559 if (exp < 0) exp = -exp;
3560 SmallVector<char, 6> expbuf;
3561 do {
3562 expbuf.push_back((char) ('0' + (exp % 10)));
3563 exp /= 10;
3564 } while (exp);
3565 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3566 Str.push_back(expbuf[E-1-I]);
3567 return;
3568 }
3569
3570 // Non-scientific, positive exponents.
3571 if (exp >= 0) {
3572 for (unsigned I = 0; I != NDigits; ++I)
3573 Str.push_back(buffer[NDigits-1-I]);
3574 for (unsigned I = 0; I != (unsigned) exp; ++I)
3575 Str.push_back('0');
3576 return;
3577 }
3578
3579 // Non-scientific, negative exponents.
3580
3581 // The number of digits to the left of the decimal point.
3582 int NWholeDigits = exp + (int) NDigits;
3583
3584 unsigned I = 0;
3585 if (NWholeDigits > 0) {
3586 for (; I != (unsigned) NWholeDigits; ++I)
3587 Str.push_back(buffer[NDigits-I-1]);
3588 Str.push_back('.');
3589 } else {
3590 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3591
3592 Str.push_back('0');
3593 Str.push_back('.');
3594 for (unsigned Z = 1; Z != NZeros; ++Z)
3595 Str.push_back('0');
3596 }
3597
3598 for (; I != NDigits; ++I)
3599 Str.push_back(buffer[NDigits-I-1]);
3600}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003601
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003602bool IEEEFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003603 // Special floats and denormals have no exact inverse.
Michael Gottesman8136c382013-06-26 23:17:28 +00003604 if (!isFiniteNonZero())
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003605 return false;
3606
3607 // Check that the number is a power of two by making sure that only the
3608 // integer bit is set in the significand.
3609 if (significandLSB() != semantics->precision - 1)
3610 return false;
3611
3612 // Get the inverse.
Tim Shen85de51d2016-10-25 19:55:59 +00003613 IEEEFloat reciprocal(*semantics, 1ULL);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003614 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3615 return false;
3616
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003617 // Avoid multiplication with a denormal, it is not safe on all platforms and
3618 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003619 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003620 return false;
3621
Michael Gottesman8136c382013-06-26 23:17:28 +00003622 assert(reciprocal.isFiniteNonZero() &&
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003623 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3624
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003625 if (inv)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003626 *inv = APFloat(reciprocal, *semantics);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003627
3628 return true;
3629}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003630
Tim Shen85de51d2016-10-25 19:55:59 +00003631bool IEEEFloat::isSignaling() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003632 if (!isNaN())
3633 return false;
3634
3635 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3636 // first bit of the trailing significand being 0.
3637 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3638}
3639
3640/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3641///
3642/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3643/// appropriate sign switching before/after the computation.
Tim Shen85de51d2016-10-25 19:55:59 +00003644IEEEFloat::opStatus IEEEFloat::next(bool nextDown) {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003645 // If we are performing nextDown, swap sign so we have -x.
3646 if (nextDown)
3647 changeSign();
3648
3649 // Compute nextUp(x)
3650 opStatus result = opOK;
3651
3652 // Handle each float category separately.
3653 switch (category) {
3654 case fcInfinity:
3655 // nextUp(+inf) = +inf
3656 if (!isNegative())
3657 break;
3658 // nextUp(-inf) = -getLargest()
3659 makeLargest(true);
3660 break;
3661 case fcNaN:
3662 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3663 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3664 // change the payload.
3665 if (isSignaling()) {
3666 result = opInvalidOp;
Alp Tokercb402912014-01-24 17:20:08 +00003667 // For consistency, propagate the sign of the sNaN to the qNaN.
Craig Topperc10719f2014-04-07 04:17:22 +00003668 makeNaN(false, isNegative(), nullptr);
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003669 }
3670 break;
3671 case fcZero:
3672 // nextUp(pm 0) = +getSmallest()
3673 makeSmallest(false);
3674 break;
3675 case fcNormal:
3676 // nextUp(-getSmallest()) = -0
3677 if (isSmallest() && isNegative()) {
3678 APInt::tcSet(significandParts(), 0, partCount());
3679 category = fcZero;
3680 exponent = 0;
3681 break;
3682 }
3683
3684 // nextUp(getLargest()) == INFINITY
3685 if (isLargest() && !isNegative()) {
3686 APInt::tcSet(significandParts(), 0, partCount());
3687 category = fcInfinity;
3688 exponent = semantics->maxExponent + 1;
3689 break;
3690 }
3691
3692 // nextUp(normal) == normal + inc.
3693 if (isNegative()) {
3694 // If we are negative, we need to decrement the significand.
3695
3696 // We only cross a binade boundary that requires adjusting the exponent
3697 // if:
3698 // 1. exponent != semantics->minExponent. This implies we are not in the
3699 // smallest binade or are dealing with denormals.
3700 // 2. Our significand excluding the integral bit is all zeros.
3701 bool WillCrossBinadeBoundary =
3702 exponent != semantics->minExponent && isSignificandAllZeros();
3703
3704 // Decrement the significand.
3705 //
3706 // We always do this since:
Alp Tokerf907b892013-12-05 05:44:44 +00003707 // 1. If we are dealing with a non-binade decrement, by definition we
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003708 // just decrement the significand.
3709 // 2. If we are dealing with a normal -> normal binade decrement, since
3710 // we have an explicit integral bit the fact that all bits but the
3711 // integral bit are zero implies that subtracting one will yield a
3712 // significand with 0 integral bit and 1 in all other spots. Thus we
3713 // must just adjust the exponent and set the integral bit to 1.
3714 // 3. If we are dealing with a normal -> denormal binade decrement,
3715 // since we set the integral bit to 0 when we represent denormals, we
3716 // just decrement the significand.
3717 integerPart *Parts = significandParts();
3718 APInt::tcDecrement(Parts, partCount());
3719
3720 if (WillCrossBinadeBoundary) {
3721 // Our result is a normal number. Do the following:
3722 // 1. Set the integral bit to 1.
3723 // 2. Decrement the exponent.
3724 APInt::tcSetBit(Parts, semantics->precision - 1);
3725 exponent--;
3726 }
3727 } else {
3728 // If we are positive, we need to increment the significand.
3729
3730 // We only cross a binade boundary that requires adjusting the exponent if
3731 // the input is not a denormal and all of said input's significand bits
3732 // are set. If all of said conditions are true: clear the significand, set
3733 // the integral bit to 1, and increment the exponent. If we have a
3734 // denormal always increment since moving denormals and the numbers in the
3735 // smallest normal binade have the same exponent in our representation.
3736 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3737
3738 if (WillCrossBinadeBoundary) {
3739 integerPart *Parts = significandParts();
3740 APInt::tcSet(Parts, 0, partCount());
3741 APInt::tcSetBit(Parts, semantics->precision - 1);
3742 assert(exponent != semantics->maxExponent &&
3743 "We can not increment an exponent beyond the maxExponent allowed"
3744 " by the given floating point semantics.");
3745 exponent++;
3746 } else {
3747 incrementSignificand();
3748 }
3749 }
3750 break;
3751 }
3752
3753 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3754 if (nextDown)
3755 changeSign();
3756
3757 return result;
3758}
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003759
Tim Shen85de51d2016-10-25 19:55:59 +00003760void IEEEFloat::makeInf(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003761 category = fcInfinity;
3762 sign = Negative;
3763 exponent = semantics->maxExponent + 1;
3764 APInt::tcSet(significandParts(), 0, partCount());
3765}
3766
Tim Shen85de51d2016-10-25 19:55:59 +00003767void IEEEFloat::makeZero(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003768 category = fcZero;
3769 sign = Negative;
3770 exponent = semantics->minExponent-1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003771 APInt::tcSet(significandParts(), 0, partCount());
3772}
3773
Tim Shen85de51d2016-10-25 19:55:59 +00003774void IEEEFloat::makeQuiet() {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003775 assert(isNaN());
3776 APInt::tcSetBit(significandParts(), semantics->precision - 2);
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003777}
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003778
Tim Shen85de51d2016-10-25 19:55:59 +00003779int ilogb(const IEEEFloat &Arg) {
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003780 if (Arg.isNaN())
Tim Shen85de51d2016-10-25 19:55:59 +00003781 return IEEEFloat::IEK_NaN;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003782 if (Arg.isZero())
Tim Shen85de51d2016-10-25 19:55:59 +00003783 return IEEEFloat::IEK_Zero;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003784 if (Arg.isInfinity())
Tim Shen85de51d2016-10-25 19:55:59 +00003785 return IEEEFloat::IEK_Inf;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003786 if (!Arg.isDenormal())
3787 return Arg.exponent;
3788
Tim Shen85de51d2016-10-25 19:55:59 +00003789 IEEEFloat Normalized(Arg);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003790 int SignificandBits = Arg.getSemantics().precision - 1;
3791
3792 Normalized.exponent += SignificandBits;
Tim Shen85de51d2016-10-25 19:55:59 +00003793 Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003794 return Normalized.exponent - SignificandBits;
3795}
3796
Tim Shen85de51d2016-10-25 19:55:59 +00003797IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) {
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003798 auto MaxExp = X.getSemantics().maxExponent;
3799 auto MinExp = X.getSemantics().minExponent;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003800
Matt Arsenaultafa31cf2016-03-13 05:11:51 +00003801 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
3802 // overflow; clamp it to a safe range before adding, but ensure that the range
3803 // is large enough that the clamp does not change the result. The range we
3804 // need to support is the difference between the largest possible exponent and
3805 // the normalized exponent of half the smallest denormal.
3806
3807 int SignificandBits = X.getSemantics().precision - 1;
3808 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
3809
3810 // Clamp to one past the range ends to let normalize handle overlflow.
3811 X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement);
3812 X.normalize(RoundingMode, lfExactlyZero);
Matt Arsenaultea00b492016-03-23 23:51:45 +00003813 if (X.isNaN())
3814 X.makeQuiet();
Richard Trieu6ae37962015-04-30 23:07:00 +00003815 return X;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003816}
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003817
Tim Shen85de51d2016-10-25 19:55:59 +00003818IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003819 Exp = ilogb(Val);
3820
3821 // Quiet signalling nans.
Tim Shen85de51d2016-10-25 19:55:59 +00003822 if (Exp == IEEEFloat::IEK_NaN) {
3823 IEEEFloat Quiet(Val);
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003824 Quiet.makeQuiet();
3825 return Quiet;
3826 }
3827
Tim Shen85de51d2016-10-25 19:55:59 +00003828 if (Exp == IEEEFloat::IEK_Inf)
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003829 return Val;
3830
3831 // 1 is added because frexp is defined to return a normalized fraction in
3832 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
Tim Shen85de51d2016-10-25 19:55:59 +00003833 Exp = Exp == IEEEFloat::IEK_Zero ? 0 : Exp + 1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003834 return scalbn(Val, -Exp, RM);
3835}
Tim Shen85de51d2016-10-25 19:55:59 +00003836
Tim Shen139a58f2016-10-27 22:52:40 +00003837DoubleAPFloat::DoubleAPFloat(const fltSemantics &S)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003838 : Semantics(&S),
3839 Floats(new APFloat[2]{APFloat(semIEEEdouble), APFloat(semIEEEdouble)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003840 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003841}
3842
3843DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag)
3844 : Semantics(&S),
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003845 Floats(new APFloat[2]{APFloat(semIEEEdouble, uninitialized),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003846 APFloat(semIEEEdouble, uninitialized)}) {
3847 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003848}
3849
3850DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003851 : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble, I),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003852 APFloat(semIEEEdouble)}) {
3853 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003854}
3855
3856DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003857 : Semantics(&S),
3858 Floats(new APFloat[2]{
3859 APFloat(semIEEEdouble, APInt(64, I.getRawData()[0])),
3860 APFloat(semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003861 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003862}
3863
3864DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First,
3865 APFloat &&Second)
3866 : Semantics(&S),
3867 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003868 assert(Semantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003869 assert(&Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003870 assert(&Floats[1].getSemantics() == &semIEEEdouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003871}
3872
3873DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS)
3874 : Semantics(RHS.Semantics),
Tim Shenb49915482016-10-28 22:45:33 +00003875 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
3876 APFloat(RHS.Floats[1])}
3877 : nullptr) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003878 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003879}
3880
3881DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS)
3882 : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003883 RHS.Semantics = &semBogus;
3884 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003885}
3886
3887DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) {
Tim Shenb49915482016-10-28 22:45:33 +00003888 if (Semantics == RHS.Semantics && RHS.Floats) {
Tim Shen139a58f2016-10-27 22:52:40 +00003889 Floats[0] = RHS.Floats[0];
3890 Floats[1] = RHS.Floats[1];
3891 } else if (this != &RHS) {
3892 this->~DoubleAPFloat();
3893 new (this) DoubleAPFloat(RHS);
3894 }
3895 return *this;
3896}
3897
Tim Shen7f127622017-01-24 00:19:45 +00003898// Implement addition, subtraction, multiplication and division based on:
Tim Shen44bde892016-12-12 21:59:30 +00003899// "Software for Doubled-Precision Floating-Point Computations",
3900// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
3901APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
3902 const APFloat &c, const APFloat &cc,
3903 roundingMode RM) {
3904 int Status = opOK;
3905 APFloat z = a;
3906 Status |= z.add(c, RM);
3907 if (!z.isFinite()) {
3908 if (!z.isInfinity()) {
3909 Floats[0] = std::move(z);
3910 Floats[1].makeZero(false);
3911 return (opStatus)Status;
3912 }
3913 Status = opOK;
3914 auto AComparedToC = a.compareAbsoluteValue(c);
3915 z = cc;
3916 Status |= z.add(aa, RM);
3917 if (AComparedToC == APFloat::cmpGreaterThan) {
3918 // z = cc + aa + c + a;
3919 Status |= z.add(c, RM);
3920 Status |= z.add(a, RM);
3921 } else {
3922 // z = cc + aa + a + c;
3923 Status |= z.add(a, RM);
3924 Status |= z.add(c, RM);
3925 }
3926 if (!z.isFinite()) {
3927 Floats[0] = std::move(z);
3928 Floats[1].makeZero(false);
3929 return (opStatus)Status;
3930 }
3931 Floats[0] = z;
3932 APFloat zz = aa;
3933 Status |= zz.add(cc, RM);
3934 if (AComparedToC == APFloat::cmpGreaterThan) {
3935 // Floats[1] = a - z + c + zz;
3936 Floats[1] = a;
3937 Status |= Floats[1].subtract(z, RM);
3938 Status |= Floats[1].add(c, RM);
3939 Status |= Floats[1].add(zz, RM);
3940 } else {
3941 // Floats[1] = c - z + a + zz;
3942 Floats[1] = c;
3943 Status |= Floats[1].subtract(z, RM);
3944 Status |= Floats[1].add(a, RM);
3945 Status |= Floats[1].add(zz, RM);
3946 }
3947 } else {
3948 // q = a - z;
3949 APFloat q = a;
3950 Status |= q.subtract(z, RM);
3951
3952 // zz = q + c + (a - (q + z)) + aa + cc;
3953 // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
3954 auto zz = q;
3955 Status |= zz.add(c, RM);
3956 Status |= q.add(z, RM);
3957 Status |= q.subtract(a, RM);
3958 q.changeSign();
3959 Status |= zz.add(q, RM);
3960 Status |= zz.add(aa, RM);
3961 Status |= zz.add(cc, RM);
3962 if (zz.isZero() && !zz.isNegative()) {
3963 Floats[0] = std::move(z);
3964 Floats[1].makeZero(false);
3965 return opOK;
3966 }
3967 Floats[0] = z;
3968 Status |= Floats[0].add(zz, RM);
3969 if (!Floats[0].isFinite()) {
3970 Floats[1].makeZero(false);
3971 return (opStatus)Status;
3972 }
3973 Floats[1] = std::move(z);
3974 Status |= Floats[1].subtract(Floats[0], RM);
3975 Status |= Floats[1].add(zz, RM);
3976 }
3977 return (opStatus)Status;
3978}
3979
3980APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
3981 const DoubleAPFloat &RHS,
3982 DoubleAPFloat &Out,
3983 roundingMode RM) {
3984 if (LHS.getCategory() == fcNaN) {
3985 Out = LHS;
3986 return opOK;
3987 }
3988 if (RHS.getCategory() == fcNaN) {
3989 Out = RHS;
3990 return opOK;
3991 }
3992 if (LHS.getCategory() == fcZero) {
3993 Out = RHS;
3994 return opOK;
3995 }
3996 if (RHS.getCategory() == fcZero) {
3997 Out = LHS;
3998 return opOK;
3999 }
4000 if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity &&
4001 LHS.isNegative() != RHS.isNegative()) {
4002 Out.makeNaN(false, Out.isNegative(), nullptr);
4003 return opInvalidOp;
4004 }
4005 if (LHS.getCategory() == fcInfinity) {
4006 Out = LHS;
4007 return opOK;
4008 }
4009 if (RHS.getCategory() == fcInfinity) {
4010 Out = RHS;
4011 return opOK;
4012 }
4013 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
4014
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004015 APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
Tim Shen44bde892016-12-12 21:59:30 +00004016 CC(RHS.Floats[1]);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004017 assert(&A.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004018 assert(&AA.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004019 assert(&C.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004020 assert(&CC.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004021 assert(&Out.Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004022 assert(&Out.Floats[1].getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004023 return Out.addImpl(A, AA, C, CC, RM);
Tim Shen44bde892016-12-12 21:59:30 +00004024}
4025
4026APFloat::opStatus DoubleAPFloat::add(const DoubleAPFloat &RHS,
4027 roundingMode RM) {
4028 return addWithSpecial(*this, RHS, *this, RM);
4029}
4030
4031APFloat::opStatus DoubleAPFloat::subtract(const DoubleAPFloat &RHS,
4032 roundingMode RM) {
4033 changeSign();
4034 auto Ret = add(RHS, RM);
4035 changeSign();
4036 return Ret;
4037}
4038
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004039APFloat::opStatus DoubleAPFloat::multiply(const DoubleAPFloat &RHS,
4040 APFloat::roundingMode RM) {
Tim Shen7f127622017-01-24 00:19:45 +00004041 const auto &LHS = *this;
4042 auto &Out = *this;
4043 /* Interesting observation: For special categories, finding the lowest
4044 common ancestor of the following layered graph gives the correct
4045 return category:
4046
4047 NaN
4048 / \
4049 Zero Inf
4050 \ /
4051 Normal
4052
4053 e.g. NaN * NaN = NaN
4054 Zero * Inf = NaN
4055 Normal * Zero = Zero
4056 Normal * Inf = Inf
4057 */
4058 if (LHS.getCategory() == fcNaN) {
4059 Out = LHS;
4060 return opOK;
4061 }
4062 if (RHS.getCategory() == fcNaN) {
4063 Out = RHS;
4064 return opOK;
4065 }
4066 if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) ||
4067 (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) {
4068 Out.makeNaN(false, false, nullptr);
4069 return opOK;
4070 }
4071 if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) {
4072 Out = LHS;
4073 return opOK;
4074 }
4075 if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) {
4076 Out = RHS;
4077 return opOK;
4078 }
4079 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
4080 "Special cases not handled exhaustively");
4081
4082 int Status = opOK;
4083 APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
4084 // t = a * c
4085 APFloat T = A;
4086 Status |= T.multiply(C, RM);
4087 if (!T.isFiniteNonZero()) {
4088 Floats[0] = T;
4089 Floats[1].makeZero(false);
4090 return (opStatus)Status;
4091 }
4092
4093 // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
4094 APFloat Tau = A;
4095 T.changeSign();
4096 Status |= Tau.fusedMultiplyAdd(C, T, RM);
4097 T.changeSign();
4098 {
4099 // v = a * d
4100 APFloat V = A;
4101 Status |= V.multiply(D, RM);
4102 // w = b * c
4103 APFloat W = B;
4104 Status |= W.multiply(C, RM);
4105 Status |= V.add(W, RM);
4106 // tau += v + w
4107 Status |= Tau.add(V, RM);
4108 }
4109 // u = t + tau
4110 APFloat U = T;
4111 Status |= U.add(Tau, RM);
4112
4113 Floats[0] = U;
4114 if (!U.isFinite()) {
4115 Floats[1].makeZero(false);
4116 } else {
4117 // Floats[1] = (t - u) + tau
4118 Status |= T.subtract(U, RM);
4119 Status |= T.add(Tau, RM);
4120 Floats[1] = T;
4121 }
4122 return (opStatus)Status;
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004123}
4124
4125APFloat::opStatus DoubleAPFloat::divide(const DoubleAPFloat &RHS,
4126 APFloat::roundingMode RM) {
4127 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4128 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4129 auto Ret =
4130 Tmp.divide(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
4131 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4132 return Ret;
4133}
4134
4135APFloat::opStatus DoubleAPFloat::remainder(const DoubleAPFloat &RHS) {
4136 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4137 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4138 auto Ret =
4139 Tmp.remainder(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4140 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4141 return Ret;
4142}
4143
4144APFloat::opStatus DoubleAPFloat::mod(const DoubleAPFloat &RHS) {
4145 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4146 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4147 auto Ret = Tmp.mod(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4148 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4149 return Ret;
4150}
4151
4152APFloat::opStatus
4153DoubleAPFloat::fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
4154 const DoubleAPFloat &Addend,
4155 APFloat::roundingMode RM) {
4156 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4157 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4158 auto Ret = Tmp.fusedMultiplyAdd(
4159 APFloat(semPPCDoubleDoubleLegacy, Multiplicand.bitcastToAPInt()),
4160 APFloat(semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()), RM);
4161 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4162 return Ret;
4163}
4164
4165APFloat::opStatus DoubleAPFloat::roundToIntegral(APFloat::roundingMode RM) {
4166 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4167 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4168 auto Ret = Tmp.roundToIntegral(RM);
4169 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4170 return Ret;
4171}
4172
Tim Shen44bde892016-12-12 21:59:30 +00004173void DoubleAPFloat::changeSign() {
4174 Floats[0].changeSign();
4175 Floats[1].changeSign();
4176}
4177
4178APFloat::cmpResult
4179DoubleAPFloat::compareAbsoluteValue(const DoubleAPFloat &RHS) const {
4180 auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
4181 if (Result != cmpEqual)
4182 return Result;
4183 Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
4184 if (Result == cmpLessThan || Result == cmpGreaterThan) {
4185 auto Against = Floats[0].isNegative() ^ Floats[1].isNegative();
4186 auto RHSAgainst = RHS.Floats[0].isNegative() ^ RHS.Floats[1].isNegative();
4187 if (Against && !RHSAgainst)
4188 return cmpLessThan;
4189 if (!Against && RHSAgainst)
4190 return cmpGreaterThan;
4191 if (!Against && !RHSAgainst)
4192 return Result;
4193 if (Against && RHSAgainst)
4194 return (cmpResult)(cmpLessThan + cmpGreaterThan - Result);
4195 }
4196 return Result;
4197}
4198
4199APFloat::fltCategory DoubleAPFloat::getCategory() const {
4200 return Floats[0].getCategory();
4201}
4202
4203bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
4204
4205void DoubleAPFloat::makeInf(bool Neg) {
4206 Floats[0].makeInf(Neg);
4207 Floats[1].makeZero(false);
4208}
4209
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004210void DoubleAPFloat::makeZero(bool Neg) {
4211 Floats[0].makeZero(Neg);
4212 Floats[1].makeZero(false);
4213}
4214
4215void DoubleAPFloat::makeLargest(bool Neg) {
4216 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4217 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
4218 Floats[1] = APFloat(semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
4219 if (Neg)
4220 changeSign();
4221}
4222
4223void DoubleAPFloat::makeSmallest(bool Neg) {
4224 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4225 Floats[0].makeSmallest(Neg);
4226 Floats[1].makeZero(false);
4227}
4228
4229void DoubleAPFloat::makeSmallestNormalized(bool Neg) {
4230 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4231 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x0360000000000000ull));
4232 if (Neg)
4233 Floats[0].changeSign();
4234 Floats[1].makeZero(false);
4235}
4236
Tim Shen44bde892016-12-12 21:59:30 +00004237void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
4238 Floats[0].makeNaN(SNaN, Neg, fill);
4239 Floats[1].makeZero(false);
4240}
4241
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004242APFloat::cmpResult DoubleAPFloat::compare(const DoubleAPFloat &RHS) const {
4243 auto Result = Floats[0].compare(RHS.Floats[0]);
4244 if (Result == APFloat::cmpEqual)
4245 return Floats[1].compare(RHS.Floats[1]);
4246 return Result;
4247}
4248
4249bool DoubleAPFloat::bitwiseIsEqual(const DoubleAPFloat &RHS) const {
4250 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
4251 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
4252}
4253
4254hash_code hash_value(const DoubleAPFloat &Arg) {
4255 if (Arg.Floats)
4256 return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
4257 return hash_combine(Arg.Semantics);
4258}
4259
4260APInt DoubleAPFloat::bitcastToAPInt() const {
4261 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4262 uint64_t Data[] = {
4263 Floats[0].bitcastToAPInt().getRawData()[0],
4264 Floats[1].bitcastToAPInt().getRawData()[0],
4265 };
4266 return APInt(128, 2, Data);
4267}
4268
4269APFloat::opStatus DoubleAPFloat::convertFromString(StringRef S,
4270 roundingMode RM) {
4271 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4272 APFloat Tmp(semPPCDoubleDoubleLegacy);
4273 auto Ret = Tmp.convertFromString(S, RM);
4274 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4275 return Ret;
4276}
4277
4278APFloat::opStatus DoubleAPFloat::next(bool nextDown) {
4279 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4280 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4281 auto Ret = Tmp.next(nextDown);
4282 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4283 return Ret;
4284}
4285
4286APFloat::opStatus DoubleAPFloat::convertToInteger(integerPart *Input,
4287 unsigned int Width,
4288 bool IsSigned,
4289 roundingMode RM,
4290 bool *IsExact) const {
4291 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4292 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4293 .convertToInteger(Input, Width, IsSigned, RM, IsExact);
4294}
4295
4296APFloat::opStatus DoubleAPFloat::convertFromAPInt(const APInt &Input,
4297 bool IsSigned,
4298 roundingMode RM) {
4299 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4300 APFloat Tmp(semPPCDoubleDoubleLegacy);
4301 auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM);
4302 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4303 return Ret;
4304}
4305
4306APFloat::opStatus
4307DoubleAPFloat::convertFromSignExtendedInteger(const integerPart *Input,
4308 unsigned int InputSize,
4309 bool IsSigned, roundingMode RM) {
4310 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4311 APFloat Tmp(semPPCDoubleDoubleLegacy);
4312 auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM);
4313 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4314 return Ret;
4315}
4316
4317APFloat::opStatus
4318DoubleAPFloat::convertFromZeroExtendedInteger(const integerPart *Input,
4319 unsigned int InputSize,
4320 bool IsSigned, roundingMode RM) {
4321 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4322 APFloat Tmp(semPPCDoubleDoubleLegacy);
4323 auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM);
4324 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4325 return Ret;
4326}
4327
4328unsigned int DoubleAPFloat::convertToHexString(char *DST,
4329 unsigned int HexDigits,
4330 bool UpperCase,
4331 roundingMode RM) const {
4332 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4333 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4334 .convertToHexString(DST, HexDigits, UpperCase, RM);
4335}
4336
4337bool DoubleAPFloat::isDenormal() const {
4338 return getCategory() == fcNormal &&
4339 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
4340 Floats[0].compare(Floats[0] + Floats[1]) != cmpEqual);
4341}
4342
4343bool DoubleAPFloat::isSmallest() const {
4344 if (getCategory() != fcNormal)
4345 return false;
4346 DoubleAPFloat Tmp(*this);
4347 Tmp.makeSmallest(this->isNegative());
4348 return Tmp.compare(*this) == cmpEqual;
4349}
4350
4351bool DoubleAPFloat::isLargest() const {
4352 if (getCategory() != fcNormal)
4353 return false;
4354 DoubleAPFloat Tmp(*this);
4355 Tmp.makeLargest(this->isNegative());
4356 return Tmp.compare(*this) == cmpEqual;
4357}
4358
4359bool DoubleAPFloat::isInteger() const {
4360 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4361 APFloat Tmp(semPPCDoubleDoubleLegacy);
4362 (void)Tmp.add(Floats[0], rmNearestTiesToEven);
4363 (void)Tmp.add(Floats[1], rmNearestTiesToEven);
4364 return Tmp.isInteger();
4365}
4366
4367void DoubleAPFloat::toString(SmallVectorImpl<char> &Str,
4368 unsigned FormatPrecision,
4369 unsigned FormatMaxPadding) const {
4370 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4371 APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4372 .toString(Str, FormatPrecision, FormatMaxPadding);
4373}
4374
4375bool DoubleAPFloat::getExactInverse(APFloat *inv) const {
4376 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4377 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4378 if (!inv)
4379 return Tmp.getExactInverse(nullptr);
4380 APFloat Inv(semPPCDoubleDoubleLegacy);
4381 auto Ret = Tmp.getExactInverse(&Inv);
4382 *inv = APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt());
4383 return Ret;
4384}
4385
4386DoubleAPFloat scalbn(DoubleAPFloat Arg, int Exp, APFloat::roundingMode RM) {
4387 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4388 return DoubleAPFloat(semPPCDoubleDouble, scalbn(Arg.Floats[0], Exp, RM),
4389 scalbn(Arg.Floats[1], Exp, RM));
4390}
4391
4392DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
4393 APFloat::roundingMode RM) {
4394 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4395 APFloat First = frexp(Arg.Floats[0], Exp, RM);
4396 APFloat Second = Arg.Floats[1];
4397 if (Arg.getCategory() == APFloat::fcNormal)
4398 Second = scalbn(Second, -Exp, RM);
4399 return DoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second));
4400}
4401
Tim Shen85de51d2016-10-25 19:55:59 +00004402} // End detail namespace
4403
Tim Shen398f90f2016-11-06 07:38:37 +00004404APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
4405 if (usesLayout<IEEEFloat>(Semantics)) {
4406 new (&IEEE) IEEEFloat(std::move(F));
Tim Shen7b57ac42016-12-21 02:39:21 +00004407 return;
4408 }
4409 if (usesLayout<DoubleAPFloat>(Semantics)) {
Tim Shen398f90f2016-11-06 07:38:37 +00004410 new (&Double)
4411 DoubleAPFloat(Semantics, APFloat(std::move(F), F.getSemantics()),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004412 APFloat(semIEEEdouble));
Tim Shen7b57ac42016-12-21 02:39:21 +00004413 return;
Tim Shen398f90f2016-11-06 07:38:37 +00004414 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004415 llvm_unreachable("Unexpected semantics");
Tim Shen398f90f2016-11-06 07:38:37 +00004416}
4417
Tim Shen85de51d2016-10-25 19:55:59 +00004418APFloat::opStatus APFloat::convertFromString(StringRef Str, roundingMode RM) {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004419 if (usesLayout<IEEEFloat>(getSemantics()))
4420 return U.IEEE.convertFromString(Str, RM);
4421 if (usesLayout<DoubleAPFloat>(getSemantics()))
4422 return U.Double.convertFromString(Str, RM);
4423 llvm_unreachable("Unexpected semantics");
Tim Shen85de51d2016-10-25 19:55:59 +00004424}
4425
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004426hash_code hash_value(const APFloat &Arg) {
4427 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
4428 return hash_value(Arg.U.IEEE);
4429 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
4430 return hash_value(Arg.U.Double);
4431 llvm_unreachable("Unexpected semantics");
4432}
Tim Shen85de51d2016-10-25 19:55:59 +00004433
4434APFloat::APFloat(const fltSemantics &Semantics, StringRef S)
Tim Shen139a58f2016-10-27 22:52:40 +00004435 : APFloat(Semantics) {
4436 convertFromString(S, rmNearestTiesToEven);
4437}
4438
4439APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics,
4440 roundingMode RM, bool *losesInfo) {
4441 if (&getSemantics() == &ToSemantics)
4442 return opOK;
4443 if (usesLayout<IEEEFloat>(getSemantics()) &&
Tim Shen7b57ac42016-12-21 02:39:21 +00004444 usesLayout<IEEEFloat>(ToSemantics))
Tim Shen139a58f2016-10-27 22:52:40 +00004445 return U.IEEE.convert(ToSemantics, RM, losesInfo);
Tim Shen7b57ac42016-12-21 02:39:21 +00004446 if (usesLayout<IEEEFloat>(getSemantics()) &&
4447 usesLayout<DoubleAPFloat>(ToSemantics)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004448 assert(&ToSemantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004449 auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo);
4450 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
Tim Shen139a58f2016-10-27 22:52:40 +00004451 return Ret;
Tim Shen7b57ac42016-12-21 02:39:21 +00004452 }
4453 if (usesLayout<DoubleAPFloat>(getSemantics()) &&
4454 usesLayout<IEEEFloat>(ToSemantics)) {
Tim Shen139a58f2016-10-27 22:52:40 +00004455 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
Tim Shen398f90f2016-11-06 07:38:37 +00004456 *this = APFloat(std::move(getIEEE()), ToSemantics);
Tim Shen139a58f2016-10-27 22:52:40 +00004457 return Ret;
Tim Shen139a58f2016-10-27 22:52:40 +00004458 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004459 llvm_unreachable("Unexpected semantics");
Tim Shen139a58f2016-10-27 22:52:40 +00004460}
Tim Shen85de51d2016-10-25 19:55:59 +00004461
Tim Shen398f90f2016-11-06 07:38:37 +00004462APFloat APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE) {
4463 if (isIEEE) {
4464 switch (BitWidth) {
4465 case 16:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004466 return APFloat(semIEEEhalf, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004467 case 32:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004468 return APFloat(semIEEEsingle, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004469 case 64:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004470 return APFloat(semIEEEdouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004471 case 80:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004472 return APFloat(semX87DoubleExtended, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004473 case 128:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004474 return APFloat(semIEEEquad, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004475 default:
4476 llvm_unreachable("Unknown floating bit width");
4477 }
4478 } else {
4479 assert(BitWidth == 128);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004480 return APFloat(semPPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004481 }
4482}
4483
Tim Shen44bde892016-12-12 21:59:30 +00004484void APFloat::print(raw_ostream &OS) const {
4485 SmallVector<char, 16> Buffer;
4486 toString(Buffer);
4487 OS << Buffer << "\n";
4488}
4489
4490void APFloat::dump() const { print(dbgs()); }
4491
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004492void APFloat::Profile(FoldingSetNodeID &NID) const {
4493 NID.Add(bitcastToAPInt());
4494}
4495
4496/* Same as convertToInteger(integerPart*, ...), except the result is returned in
4497 an APSInt, whose initial bit-width and signed-ness are used to determine the
4498 precision of the conversion.
4499 */
4500APFloat::opStatus APFloat::convertToInteger(APSInt &result,
4501 roundingMode rounding_mode,
4502 bool *isExact) const {
4503 unsigned bitWidth = result.getBitWidth();
4504 SmallVector<uint64_t, 4> parts(result.getNumWords());
4505 opStatus status = convertToInteger(parts.data(), bitWidth, result.isSigned(),
4506 rounding_mode, isExact);
4507 // Keeps the original signed-ness.
4508 result = APInt(bitWidth, parts);
4509 return status;
4510}
4511
Tim Shen85de51d2016-10-25 19:55:59 +00004512} // End llvm namespace