blob: 3a33d7426830323fbbe37f513f0c5badb8607ac9 [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"
Torok Edwin56d06592009-07-11 20:10:48 +000022#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000023#include "llvm/Support/MathExtras.h"
Chris Lattner17f71652008-08-17 07:19:36 +000024#include <cstring>
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000025#include <limits.h>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000026
27using namespace llvm;
28
Michael Gottesman9b877e12013-06-24 09:57:57 +000029/// A macro used to combine two fcCategory enums into one key which can be used
30/// in a switch statement to classify how the interaction of two APFloat's
31/// categories affects an operation.
32///
33/// TODO: If clang source code is ever allowed to use constexpr in its own
34/// codebase, change this into a static inline function.
35#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000036
Neil Booth8f1946f2007-10-03 22:26:02 +000037/* Assumed in hexadecimal significand parsing, and conversion to
38 hexadecimal strings. */
Benjamin Kramer7000ca32014-10-12 17:56:40 +000039static_assert(integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000040
41namespace llvm {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000042 /* Represents floating point arithmetic semantics. */
43 struct fltSemantics {
44 /* The largest E such that 2^E is representable; this matches the
45 definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000046 APFloatBase::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000047
48 /* The smallest E such that 2^E is a normalized number; this
49 matches the definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000050 APFloatBase::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000051
52 /* Number of bits in the significand. This includes the integer
53 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000054 unsigned int precision;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000055
56 /* Number of bits actually used in the semantics. */
57 unsigned int sizeInBits;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000058 };
59
Tim Shen85de51d2016-10-25 19:55:59 +000060 const fltSemantics APFloatBase::IEEEhalf = {15, -14, 11, 16};
61 const fltSemantics APFloatBase::IEEEsingle = {127, -126, 24, 32};
62 const fltSemantics APFloatBase::IEEEdouble = {1023, -1022, 53, 64};
63 const fltSemantics APFloatBase::IEEEquad = {16383, -16382, 113, 128};
64 const fltSemantics APFloatBase::x87DoubleExtended = {16383, -16382, 64, 80};
65 const fltSemantics APFloatBase::Bogus = {0, 0, 0, 0};
Dale Johannesen007aa372007-10-11 18:07:22 +000066
Ulrich Weigandd9f7e252012-10-29 18:09:01 +000067 /* The PowerPC format consists of two doubles. It does not map cleanly
68 onto the usual format above. It is approximated using twice the
69 mantissa bits. Note that for exponents near the double minimum,
70 we no longer can represent the full 106 mantissa bits, so those
71 will be treated as denormal numbers.
72
73 FIXME: While this approximation is equivalent to what GCC uses for
74 compile-time arithmetic on PPC double-double numbers, it is not able
75 to represent all possible values held by a PPC double-double number,
76 for example: (long double) 1.0 + (long double) 0x1p-106
77 Should this be replaced by a full emulation of PPC double-double? */
Tim Shen139a58f2016-10-27 22:52:40 +000078 const fltSemantics APFloatBase::PPCDoubleDouble = {0, 0, 0, 0};
79
80 /* There are temporary semantics for the real PPCDoubleDouble implementation.
81 Currently, APFloat of PPCDoubleDouble holds one PPCDoubleDoubleImpl as the
82 high part of double double, and one IEEEdouble as the low part, so that
83 the old operations operate on PPCDoubleDoubleImpl, while the newly added
84 operations also populate the IEEEdouble.
85
86 TODO: Once all functions support DoubleAPFloat mode, we'll change all
87 PPCDoubleDoubleImpl to IEEEdouble and remove PPCDoubleDoubleImpl. */
88 static const fltSemantics PPCDoubleDoubleImpl = {1023, -1022 + 53, 53 + 53,
89 128};
Neil Boothb93d90e2007-10-12 16:02:31 +000090
91 /* A tight upper bound on number of parts required to hold the value
92 pow(5, power) is
93
Neil Booth91305512007-10-15 15:00:55 +000094 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +000095
Neil Boothb93d90e2007-10-12 16:02:31 +000096 However, whilst the result may require only this many parts,
97 because we are multiplying two values to get it, the
98 multiplication may require an extra part with the excess part
99 being zero (consider the trivial case of 1 * 1, tcFullMultiply
100 requires two parts to hold the single-part result). So we add an
101 extra one to guarantee enough space whilst multiplying. */
102 const unsigned int maxExponent = 16383;
103 const unsigned int maxPrecision = 113;
104 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth91305512007-10-15 15:00:55 +0000105 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
106 / (351 * integerPartWidth));
Tim Shen85de51d2016-10-25 19:55:59 +0000107
108 unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
109 return semantics.precision;
110 }
111 APFloatBase::ExponentType
112 APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) {
113 return semantics.maxExponent;
114 }
115 APFloatBase::ExponentType
116 APFloatBase::semanticsMinExponent(const fltSemantics &semantics) {
117 return semantics.minExponent;
118 }
119 unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
120 return semantics.sizeInBits;
121 }
122
123 unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) {
124 return Sem.sizeInBits;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000125}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000126
Chris Lattner91702092009-03-12 23:59:55 +0000127/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000128
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000129static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000130partCountForBits(unsigned int bits)
131{
132 return ((bits) + integerPartWidth - 1) / integerPartWidth;
133}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000134
Chris Lattner91702092009-03-12 23:59:55 +0000135/* Returns 0U-9U. Return values >= 10U are not digits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000136static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000137decDigitValue(unsigned int c)
138{
139 return c - '0';
140}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000141
Chris Lattner91702092009-03-12 23:59:55 +0000142/* Return the value of a decimal exponent of the form
143 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000144
Chris Lattner91702092009-03-12 23:59:55 +0000145 If the exponent overflows, returns a large exponent with the
146 appropriate sign. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000147static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000148readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000149{
150 bool isNegative;
151 unsigned int absExponent;
152 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000153 StringRef::iterator p = begin;
154
155 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000156
Chris Lattner91702092009-03-12 23:59:55 +0000157 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000158 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000159 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000160 assert(p != end && "Exponent has no digits");
161 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000162
Chris Lattner91702092009-03-12 23:59:55 +0000163 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000164 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000165
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000166 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000167 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000168
Chris Lattner91702092009-03-12 23:59:55 +0000169 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000170 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000171
Chris Lattner91702092009-03-12 23:59:55 +0000172 value += absExponent * 10;
173 if (absExponent >= overlargeExponent) {
174 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000175 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000176 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000177 }
Chris Lattner91702092009-03-12 23:59:55 +0000178 absExponent = value;
179 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000180
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000181 assert(p == end && "Invalid exponent in exponent");
182
Chris Lattner91702092009-03-12 23:59:55 +0000183 if (isNegative)
184 return -(int) absExponent;
185 else
186 return (int) absExponent;
187}
188
189/* This is ugly and needs cleaning up, but I don't immediately see
190 how whilst remaining safe. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000191static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000192totalExponent(StringRef::iterator p, StringRef::iterator end,
193 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000194{
195 int unsignedExponent;
196 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000197 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000198
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000199 assert(p != end && "Exponent has no digits");
200
Chris Lattner91702092009-03-12 23:59:55 +0000201 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000202 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000203 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000204 assert(p != end && "Exponent has no digits");
205 }
Chris Lattner91702092009-03-12 23:59:55 +0000206
207 unsignedExponent = 0;
208 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000209 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000210 unsigned int value;
211
212 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000213 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000214
Chris Lattner91702092009-03-12 23:59:55 +0000215 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000216 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000217 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000218 break;
219 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000220 }
221
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000222 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000223 overflow = true;
224
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000225 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000226 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000227 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000228 exponent = -exponent;
229 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000230 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000231 overflow = true;
232 }
233
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000234 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000235 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000236
237 return exponent;
238}
239
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000240static StringRef::iterator
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000241skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
242 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000243{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000244 StringRef::iterator p = begin;
245 *dot = end;
Nick Lewycky095b92e2014-09-06 01:16:42 +0000246 while (p != end && *p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000247 p++;
248
Nick Lewycky095b92e2014-09-06 01:16:42 +0000249 if (p != end && *p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000250 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000251
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000252 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000253
Nick Lewycky095b92e2014-09-06 01:16:42 +0000254 while (p != end && *p == '0')
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000255 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000256 }
257
Chris Lattner91702092009-03-12 23:59:55 +0000258 return p;
259}
Neil Booth4ed401b2007-10-14 10:16:12 +0000260
Chris Lattner91702092009-03-12 23:59:55 +0000261/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000262
Chris Lattner91702092009-03-12 23:59:55 +0000263 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000264
Chris Lattner91702092009-03-12 23:59:55 +0000265 where the decimal point and exponent are optional, fill out the
266 structure D. Exponent is appropriate if the significand is
267 treated as an integer, and normalizedExponent if the significand
268 is taken to have the decimal point after a single leading
269 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000270
Chris Lattner91702092009-03-12 23:59:55 +0000271 If the value is zero, V->firstSigDigit points to a non-digit, and
272 the return exponent is zero.
273*/
274struct decimalInfo {
275 const char *firstSigDigit;
276 const char *lastSigDigit;
277 int exponent;
278 int normalizedExponent;
279};
Neil Booth4ed401b2007-10-14 10:16:12 +0000280
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000281static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000282interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
283 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000284{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000285 StringRef::iterator dot = end;
286 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000287
Chris Lattner91702092009-03-12 23:59:55 +0000288 D->firstSigDigit = p;
289 D->exponent = 0;
290 D->normalizedExponent = 0;
291
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000292 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000293 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000294 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000295 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000296 if (p == end)
297 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000298 }
Chris Lattner91702092009-03-12 23:59:55 +0000299 if (decDigitValue(*p) >= 10U)
300 break;
Chris Lattner91702092009-03-12 23:59:55 +0000301 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000302
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000303 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000304 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
305 assert(p != begin && "Significand has no digits");
306 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000307
308 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000309 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000310
Chris Lattner91702092009-03-12 23:59:55 +0000311 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000312 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000313 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000314 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000315
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000316 /* If number is all zeroes accept any exponent. */
317 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000318 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000319 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000320 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000321 do
322 p--;
323 while (p != begin && *p == '0');
324 while (p != begin && *p == '.');
325 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000326
Chris Lattner91702092009-03-12 23:59:55 +0000327 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000328 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000329 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000330 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000331 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000332 }
333
Chris Lattner91702092009-03-12 23:59:55 +0000334 D->lastSigDigit = p;
335}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000336
Chris Lattner91702092009-03-12 23:59:55 +0000337/* Return the trailing fraction of a hexadecimal number.
338 DIGITVALUE is the first hex digit of the fraction, P points to
339 the next digit. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000340static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000341trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
342 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000343{
344 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000345
Chris Lattner91702092009-03-12 23:59:55 +0000346 /* If the first trailing digit isn't 0 or 8 we can work out the
347 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000348 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000349 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000350 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000351 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000352
Eli Friedmand2eb07a2013-07-17 22:17:29 +0000353 // Otherwise we need to find the first non-zero digit.
354 while (p != end && (*p == '0' || *p == '.'))
Chris Lattner91702092009-03-12 23:59:55 +0000355 p++;
356
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000357 assert(p != end && "Invalid trailing hexadecimal fraction!");
358
Chris Lattner91702092009-03-12 23:59:55 +0000359 hexDigit = hexDigitValue(*p);
360
361 /* If we ran off the end it is exactly zero or one-half, otherwise
362 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000363 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000364 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
365 else
366 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
367}
368
369/* Return the fraction lost were a bignum truncated losing the least
370 significant BITS bits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000371static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000372lostFractionThroughTruncation(const integerPart *parts,
373 unsigned int partCount,
374 unsigned int bits)
375{
376 unsigned int lsb;
377
378 lsb = APInt::tcLSB(parts, partCount);
379
380 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000381 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000382 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000383 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000384 return lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000385 if (bits <= partCount * integerPartWidth &&
386 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000387 return lfMoreThanHalf;
388
389 return lfLessThanHalf;
390}
391
392/* Shift DST right BITS bits noting lost fraction. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000393static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000394shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
395{
396 lostFraction lost_fraction;
397
398 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
399
400 APInt::tcShiftRight(dst, parts, bits);
401
402 return lost_fraction;
403}
404
405/* Combine the effect of two lost fractions. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000406static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000407combineLostFractions(lostFraction moreSignificant,
408 lostFraction lessSignificant)
409{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000410 if (lessSignificant != lfExactlyZero) {
411 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000412 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000413 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000414 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000415 }
416
Chris Lattner91702092009-03-12 23:59:55 +0000417 return moreSignificant;
418}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000419
Chris Lattner91702092009-03-12 23:59:55 +0000420/* The error from the true value, in half-ulps, on multiplying two
421 floating point numbers, which differ from the value they
422 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
423 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000424
Chris Lattner91702092009-03-12 23:59:55 +0000425 See "How to Read Floating Point Numbers Accurately" by William D
426 Clinger. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000427static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000428HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
429{
430 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000431
Chris Lattner91702092009-03-12 23:59:55 +0000432 if (HUerr1 + HUerr2 == 0)
433 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
434 else
435 return inexactMultiply + 2 * (HUerr1 + HUerr2);
436}
Neil Booth8f1946f2007-10-03 22:26:02 +0000437
Chris Lattner91702092009-03-12 23:59:55 +0000438/* The number of ulps from the boundary (zero, or half if ISNEAREST)
439 when the least significant BITS are truncated. BITS cannot be
440 zero. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000441static integerPart
Chris Lattner91702092009-03-12 23:59:55 +0000442ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
443{
444 unsigned int count, partBits;
445 integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000446
Evan Cheng67c90212009-10-27 21:35:42 +0000447 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000448
Chris Lattner91702092009-03-12 23:59:55 +0000449 bits--;
450 count = bits / integerPartWidth;
451 partBits = bits % integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000452
Chris Lattner91702092009-03-12 23:59:55 +0000453 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000454
Chris Lattner91702092009-03-12 23:59:55 +0000455 if (isNearest)
456 boundary = (integerPart) 1 << (partBits - 1);
457 else
458 boundary = 0;
459
460 if (count == 0) {
461 if (part - boundary <= boundary - part)
462 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000463 else
Chris Lattner91702092009-03-12 23:59:55 +0000464 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000465 }
466
Chris Lattner91702092009-03-12 23:59:55 +0000467 if (part == boundary) {
468 while (--count)
469 if (parts[count])
470 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000471
Chris Lattner91702092009-03-12 23:59:55 +0000472 return parts[0];
473 } else if (part == boundary - 1) {
474 while (--count)
475 if (~parts[count])
476 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000477
Chris Lattner91702092009-03-12 23:59:55 +0000478 return -parts[0];
479 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000480
Chris Lattner91702092009-03-12 23:59:55 +0000481 return ~(integerPart) 0; /* A lot. */
482}
Neil Boothb93d90e2007-10-12 16:02:31 +0000483
Chris Lattner91702092009-03-12 23:59:55 +0000484/* Place pow(5, power) in DST, and return the number of parts used.
485 DST must be at least one part larger than size of the answer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000486static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000487powerOf5(integerPart *dst, unsigned int power)
488{
489 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
490 15625, 78125 };
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000491 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
492 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000493
Chris Lattner0bf18692009-03-13 00:03:51 +0000494 unsigned int partsCount[16] = { 1 };
Chris Lattner91702092009-03-12 23:59:55 +0000495 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
496 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000497 assert(power <= maxExponent);
498
499 p1 = dst;
500 p2 = scratch;
501
502 *p1 = firstEightPowers[power & 7];
503 power >>= 3;
504
505 result = 1;
506 pow5 = pow5s;
507
508 for (unsigned int n = 0; power; power >>= 1, n++) {
509 unsigned int pc;
510
511 pc = partsCount[n];
512
513 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
514 if (pc == 0) {
515 pc = partsCount[n - 1];
516 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
517 pc *= 2;
518 if (pow5[pc - 1] == 0)
519 pc--;
520 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000521 }
522
Chris Lattner91702092009-03-12 23:59:55 +0000523 if (power & 1) {
524 integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000525
Chris Lattner91702092009-03-12 23:59:55 +0000526 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
527 result += pc;
528 if (p2[result - 1] == 0)
529 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000530
Chris Lattner91702092009-03-12 23:59:55 +0000531 /* Now result is in p1 with partsCount parts and p2 is scratch
532 space. */
Richard Trieu7a083812016-02-18 22:09:30 +0000533 tmp = p1;
534 p1 = p2;
535 p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000536 }
537
Chris Lattner91702092009-03-12 23:59:55 +0000538 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000539 }
540
Chris Lattner91702092009-03-12 23:59:55 +0000541 if (p1 != dst)
542 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000543
Chris Lattner91702092009-03-12 23:59:55 +0000544 return result;
545}
Neil Boothb93d90e2007-10-12 16:02:31 +0000546
Chris Lattner91702092009-03-12 23:59:55 +0000547/* Zero at the end to avoid modular arithmetic when adding one; used
548 when rounding up during hexadecimal output. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000549static const char hexDigitsLower[] = "0123456789abcdef0";
550static const char hexDigitsUpper[] = "0123456789ABCDEF0";
551static const char infinityL[] = "infinity";
552static const char infinityU[] = "INFINITY";
553static const char NaNL[] = "nan";
554static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000555
Chris Lattner91702092009-03-12 23:59:55 +0000556/* Write out an integerPart in hexadecimal, starting with the most
557 significant nibble. Write out exactly COUNT hexdigits, return
558 COUNT. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000559static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000560partAsHex (char *dst, integerPart part, unsigned int count,
561 const char *hexDigitChars)
562{
563 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000564
Evan Cheng67c90212009-10-27 21:35:42 +0000565 assert(count != 0 && count <= integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000566
Chris Lattner91702092009-03-12 23:59:55 +0000567 part >>= (integerPartWidth - 4 * count);
568 while (count--) {
569 dst[count] = hexDigitChars[part & 0xf];
570 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000571 }
572
Chris Lattner91702092009-03-12 23:59:55 +0000573 return result;
574}
Neil Booth8f1946f2007-10-03 22:26:02 +0000575
Chris Lattner91702092009-03-12 23:59:55 +0000576/* Write out an unsigned decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000577static char *
Chris Lattner91702092009-03-12 23:59:55 +0000578writeUnsignedDecimal (char *dst, unsigned int n)
579{
580 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000581
Chris Lattner91702092009-03-12 23:59:55 +0000582 p = buff;
583 do
584 *p++ = '0' + n % 10;
585 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000586
Chris Lattner91702092009-03-12 23:59:55 +0000587 do
588 *dst++ = *--p;
589 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000590
Chris Lattner91702092009-03-12 23:59:55 +0000591 return dst;
592}
Neil Booth8f1946f2007-10-03 22:26:02 +0000593
Chris Lattner91702092009-03-12 23:59:55 +0000594/* Write out a signed decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000595static char *
Chris Lattner91702092009-03-12 23:59:55 +0000596writeSignedDecimal (char *dst, int value)
597{
598 if (value < 0) {
599 *dst++ = '-';
600 dst = writeUnsignedDecimal(dst, -(unsigned) value);
601 } else
602 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000603
Chris Lattner91702092009-03-12 23:59:55 +0000604 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000605}
606
Tim Shen85de51d2016-10-25 19:55:59 +0000607namespace detail {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000608/* Constructors. */
Tim Shen85de51d2016-10-25 19:55:59 +0000609void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000610 unsigned int count;
611
612 semantics = ourSemantics;
613 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000614 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000615 significand.parts = new integerPart[count];
616}
617
Tim Shen85de51d2016-10-25 19:55:59 +0000618void IEEEFloat::freeSignificand() {
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000619 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000620 delete [] significand.parts;
621}
622
Tim Shen85de51d2016-10-25 19:55:59 +0000623void IEEEFloat::assign(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000624 assert(semantics == rhs.semantics);
625
626 sign = rhs.sign;
627 category = rhs.category;
628 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000629 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000630 copySignificand(rhs);
631}
632
Tim Shen85de51d2016-10-25 19:55:59 +0000633void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
Michael Gottesman8136c382013-06-26 23:17:28 +0000634 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000635 assert(rhs.partCount() >= partCount());
636
637 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000638 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000639}
640
Neil Booth5fe658b2007-10-14 10:39:51 +0000641/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000642 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000643 which may not be ideal. If float, this is QNaN(0). */
Tim Shen85de51d2016-10-25 19:55:59 +0000644void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
Neil Booth5fe658b2007-10-14 10:39:51 +0000645 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000646 sign = Negative;
647
John McCallc12b1332010-02-28 12:49:50 +0000648 integerPart *significand = significandParts();
649 unsigned numParts = partCount();
650
John McCalldcb9a7a2010-02-28 02:51:25 +0000651 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000652 if (!fill || fill->getNumWords() < numParts)
653 APInt::tcSet(significand, 0, numParts);
654 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000655 APInt::tcAssign(significand, fill->getRawData(),
656 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000657
658 // Zero out the excess bits of the significand.
659 unsigned bitsToPreserve = semantics->precision - 1;
660 unsigned part = bitsToPreserve / 64;
661 bitsToPreserve %= 64;
662 significand[part] &= ((1ULL << bitsToPreserve) - 1);
663 for (part++; part != numParts; ++part)
664 significand[part] = 0;
665 }
666
667 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000668
669 if (SNaN) {
670 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000671 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000672
673 // If there are no bits set in the payload, we have to set
674 // *something* to make it a NaN instead of an infinity;
675 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000676 if (APInt::tcIsZero(significand, numParts))
677 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000678 } else {
679 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000680 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000681 }
John McCallc12b1332010-02-28 12:49:50 +0000682
683 // For x87 extended precision, we want to make a NaN, not a
684 // pseudo-NaN. Maybe we should expose the ability to make
685 // pseudo-NaNs?
686 if (semantics == &APFloat::x87DoubleExtended)
687 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000688}
689
Tim Shen85de51d2016-10-25 19:55:59 +0000690IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000691 if (this != &rhs) {
692 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000693 freeSignificand();
694 initialize(rhs.semantics);
695 }
696 assign(rhs);
697 }
698
699 return *this;
700}
701
Tim Shen85de51d2016-10-25 19:55:59 +0000702IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000703 freeSignificand();
704
705 semantics = rhs.semantics;
706 significand = rhs.significand;
707 exponent = rhs.exponent;
708 category = rhs.category;
709 sign = rhs.sign;
710
711 rhs.semantics = &Bogus;
712 return *this;
713}
714
Tim Shen85de51d2016-10-25 19:55:59 +0000715bool IEEEFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000716 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000717 (APInt::tcExtractBit(significandParts(),
718 semantics->precision - 1) == 0);
719}
720
Tim Shen85de51d2016-10-25 19:55:59 +0000721bool IEEEFloat::isSmallest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000722 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000723 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000724 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000725 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000726 significandMSB() == 0;
727}
728
Tim Shen85de51d2016-10-25 19:55:59 +0000729bool IEEEFloat::isSignificandAllOnes() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000730 // Test if the significand excluding the integral bit is all ones. This allows
731 // us to test for binade boundaries.
732 const integerPart *Parts = significandParts();
733 const unsigned PartCount = partCount();
734 for (unsigned i = 0; i < PartCount - 1; i++)
735 if (~Parts[i])
736 return false;
737
738 // Set the unused high bits to all ones when we compare.
739 const unsigned NumHighBits =
740 PartCount*integerPartWidth - semantics->precision + 1;
741 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
742 "fill than integerPartWidth");
743 const integerPart HighBitFill =
744 ~integerPart(0) << (integerPartWidth - NumHighBits);
745 if (~(Parts[PartCount - 1] | HighBitFill))
746 return false;
747
748 return true;
749}
750
Tim Shen85de51d2016-10-25 19:55:59 +0000751bool IEEEFloat::isSignificandAllZeros() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000752 // Test if the significand excluding the integral bit is all zeros. This
753 // allows us to test for binade boundaries.
754 const integerPart *Parts = significandParts();
755 const unsigned PartCount = partCount();
756
757 for (unsigned i = 0; i < PartCount - 1; i++)
758 if (Parts[i])
759 return false;
760
761 const unsigned NumHighBits =
762 PartCount*integerPartWidth - semantics->precision + 1;
763 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
764 "clear than integerPartWidth");
765 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
766
767 if (Parts[PartCount - 1] & HighBitMask)
768 return false;
769
770 return true;
771}
772
Tim Shen85de51d2016-10-25 19:55:59 +0000773bool IEEEFloat::isLargest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000774 // The largest number by magnitude in our format will be the floating point
775 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000776 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000777 && isSignificandAllOnes();
778}
779
Tim Shen85de51d2016-10-25 19:55:59 +0000780bool IEEEFloat::isInteger() const {
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000781 // This could be made more efficient; I'm going for obviously correct.
782 if (!isFinite()) return false;
Tim Shen85de51d2016-10-25 19:55:59 +0000783 IEEEFloat truncated = *this;
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000784 truncated.roundToIntegral(rmTowardZero);
785 return compare(truncated) == cmpEqual;
786}
787
Tim Shen85de51d2016-10-25 19:55:59 +0000788bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000789 if (this == &rhs)
790 return true;
791 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000792 category != rhs.category ||
793 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000794 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000795 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000796 return true;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000797
798 if (isFiniteNonZero() && exponent != rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000799 return false;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000800
801 return std::equal(significandParts(), significandParts() + partCount(),
802 rhs.significandParts());
Dale Johannesena719a602007-08-24 00:56:33 +0000803}
804
Tim Shen85de51d2016-10-25 19:55:59 +0000805IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000806 initialize(&ourSemantics);
807 sign = 0;
Michael Gottesman30a90eb2013-07-27 21:49:21 +0000808 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000809 zeroSignificand();
810 exponent = ourSemantics.precision - 1;
811 significandParts()[0] = value;
812 normalize(rmNearestTiesToEven, lfExactlyZero);
813}
814
Tim Shen85de51d2016-10-25 19:55:59 +0000815IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000816 initialize(&ourSemantics);
817 category = fcZero;
818 sign = false;
819}
820
Tim Shenb49915482016-10-28 22:45:33 +0000821// Delegate to the previous constructor, because later copy constructor may
822// actually inspects category, which can't be garbage.
823IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
Tim Shen1bab9cf2016-10-29 00:51:41 +0000824 : IEEEFloat(ourSemantics) {}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000825
Tim Shen85de51d2016-10-25 19:55:59 +0000826IEEEFloat::IEEEFloat(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000827 initialize(rhs.semantics);
828 assign(rhs);
829}
830
Tim Shen85de51d2016-10-25 19:55:59 +0000831IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&Bogus) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000832 *this = std::move(rhs);
833}
834
Tim Shen85de51d2016-10-25 19:55:59 +0000835IEEEFloat::~IEEEFloat() { freeSignificand(); }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000836
Ted Kremenek6f30a072008-02-11 17:24:50 +0000837// Profile - This method 'profiles' an APFloat for use with FoldingSet.
Tim Shen85de51d2016-10-25 19:55:59 +0000838void IEEEFloat::Profile(FoldingSetNodeID &ID) const {
Dale Johannesen54306fe2008-10-09 18:53:47 +0000839 ID.Add(bitcastToAPInt());
Ted Kremenek6f30a072008-02-11 17:24:50 +0000840}
841
Tim Shen85de51d2016-10-25 19:55:59 +0000842unsigned int IEEEFloat::partCount() const {
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000843 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000844}
845
Tim Shen85de51d2016-10-25 19:55:59 +0000846const integerPart *IEEEFloat::significandParts() const {
847 return const_cast<IEEEFloat *>(this)->significandParts();
JF Bastiena1d3c242015-08-26 02:32:45 +0000848}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000849
Tim Shen85de51d2016-10-25 19:55:59 +0000850integerPart *IEEEFloat::significandParts() {
Evan Cheng67c90212009-10-27 21:35:42 +0000851 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000852 return significand.parts;
853 else
854 return &significand.part;
855}
856
Tim Shen85de51d2016-10-25 19:55:59 +0000857void IEEEFloat::zeroSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000858 APInt::tcSet(significandParts(), 0, partCount());
859}
860
861/* Increment an fcNormal floating point number's significand. */
Tim Shen85de51d2016-10-25 19:55:59 +0000862void IEEEFloat::incrementSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000863 integerPart carry;
864
865 carry = APInt::tcIncrement(significandParts(), partCount());
866
867 /* Our callers should never cause us to overflow. */
868 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000869 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000870}
871
872/* Add the significand of the RHS. Returns the carry flag. */
Tim Shen85de51d2016-10-25 19:55:59 +0000873integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000874 integerPart *parts;
875
876 parts = significandParts();
877
878 assert(semantics == rhs.semantics);
879 assert(exponent == rhs.exponent);
880
881 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
882}
883
884/* Subtract the significand of the RHS with a borrow flag. Returns
885 the borrow flag. */
Tim Shen85de51d2016-10-25 19:55:59 +0000886integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
887 integerPart borrow) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000888 integerPart *parts;
889
890 parts = significandParts();
891
892 assert(semantics == rhs.semantics);
893 assert(exponent == rhs.exponent);
894
895 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000896 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000897}
898
899/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
900 on to the full-precision result of the multiplication. Returns the
901 lost fraction. */
Tim Shen85de51d2016-10-25 19:55:59 +0000902lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
903 const IEEEFloat *addend) {
Neil Booth9acbf5a2007-09-26 21:33:42 +0000904 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000905 unsigned int partsCount, newPartsCount, precision;
906 integerPart *lhsSignificand;
907 integerPart scratch[4];
908 integerPart *fullSignificand;
909 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000910 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000911
912 assert(semantics == rhs.semantics);
913
914 precision = semantics->precision;
Lang Hames56c0eb22014-11-19 19:15:41 +0000915
916 // Allocate space for twice as many bits as the original significand, plus one
917 // extra bit for the addition to overflow into.
918 newPartsCount = partCountForBits(precision * 2 + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000919
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000920 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000921 fullSignificand = new integerPart[newPartsCount];
922 else
923 fullSignificand = scratch;
924
925 lhsSignificand = significandParts();
926 partsCount = partCount();
927
928 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000929 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000930
931 lost_fraction = lfExactlyZero;
932 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
933 exponent += rhs.exponent;
934
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000935 // Assume the operands involved in the multiplication are single-precision
936 // FP, and the two multiplicants are:
937 // *this = a23 . a22 ... a0 * 2^e1
938 // rhs = b23 . b22 ... b0 * 2^e2
939 // the result of multiplication is:
Lang Hames56c0eb22014-11-19 19:15:41 +0000940 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
941 // Note that there are three significant bits at the left-hand side of the
942 // radix point: two for the multiplication, and an overflow bit for the
943 // addition (that will always be zero at this point). Move the radix point
944 // toward left by two bits, and adjust exponent accordingly.
945 exponent += 2;
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000946
Hal Finkel171c2ec2014-10-14 19:23:07 +0000947 if (addend && addend->isNonZero()) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000948 // The intermediate result of the multiplication has "2 * precision"
949 // signicant bit; adjust the addend to be consistent with mul result.
950 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000951 Significand savedSignificand = significand;
952 const fltSemantics *savedSemantics = semantics;
953 fltSemantics extendedSemantics;
954 opStatus status;
955 unsigned int extendedPrecision;
956
Lang Hames56c0eb22014-11-19 19:15:41 +0000957 // Normalize our MSB to one below the top bit to allow for overflow.
958 extendedPrecision = 2 * precision + 1;
959 if (omsb != extendedPrecision - 1) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000960 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000961 APInt::tcShiftLeft(fullSignificand, newPartsCount,
Lang Hames56c0eb22014-11-19 19:15:41 +0000962 (extendedPrecision - 1) - omsb);
963 exponent -= (extendedPrecision - 1) - omsb;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000964 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000965
966 /* Create new semantics. */
967 extendedSemantics = *semantics;
968 extendedSemantics.precision = extendedPrecision;
969
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000970 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000971 significand.part = fullSignificand[0];
972 else
973 significand.parts = fullSignificand;
974 semantics = &extendedSemantics;
975
Tim Shen85de51d2016-10-25 19:55:59 +0000976 IEEEFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000977 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000978 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000979 (void)status;
Lang Hames56c0eb22014-11-19 19:15:41 +0000980
981 // Shift the significand of the addend right by one bit. This guarantees
982 // that the high bit of the significand is zero (same as fullSignificand),
983 // so the addition will overflow (if it does overflow at all) into the top bit.
984 lost_fraction = extendedAddend.shiftSignificandRight(1);
985 assert(lost_fraction == lfExactlyZero &&
986 "Lost precision while shifting addend for fused-multiply-add.");
987
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000988 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
989
990 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000991 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000992 fullSignificand[0] = significand.part;
993 significand = savedSignificand;
994 semantics = savedSemantics;
995
996 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
997 }
998
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000999 // Convert the result having "2 * precision" significant-bits back to the one
1000 // having "precision" significant-bits. First, move the radix point from
1001 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1002 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
Lang Hames56c0eb22014-11-19 19:15:41 +00001003 exponent -= precision + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001004
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001005 // In case MSB resides at the left-hand side of radix point, shift the
1006 // mantissa right by some amount to make sure the MSB reside right before
1007 // the radix point (i.e. "MSB . rest-significant-bits").
1008 //
1009 // Note that the result is not normalized when "omsb < precision". So, the
Tim Shen85de51d2016-10-25 19:55:59 +00001010 // caller needs to call IEEEFloat::normalize() if normalized value is
1011 // expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001012 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001013 unsigned int bits, significantParts;
1014 lostFraction lf;
1015
1016 bits = omsb - precision;
1017 significantParts = partCountForBits(omsb);
1018 lf = shiftRight(fullSignificand, significantParts, bits);
1019 lost_fraction = combineLostFractions(lf, lost_fraction);
1020 exponent += bits;
1021 }
1022
1023 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1024
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001025 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001026 delete [] fullSignificand;
1027
1028 return lost_fraction;
1029}
1030
1031/* Multiply the significands of LHS and RHS to DST. */
Tim Shen85de51d2016-10-25 19:55:59 +00001032lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001033 unsigned int bit, i, partsCount;
1034 const integerPart *rhsSignificand;
1035 integerPart *lhsSignificand, *dividend, *divisor;
1036 integerPart scratch[4];
1037 lostFraction lost_fraction;
1038
1039 assert(semantics == rhs.semantics);
1040
1041 lhsSignificand = significandParts();
1042 rhsSignificand = rhs.significandParts();
1043 partsCount = partCount();
1044
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001045 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001046 dividend = new integerPart[partsCount * 2];
1047 else
1048 dividend = scratch;
1049
1050 divisor = dividend + partsCount;
1051
1052 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001053 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001054 dividend[i] = lhsSignificand[i];
1055 divisor[i] = rhsSignificand[i];
1056 lhsSignificand[i] = 0;
1057 }
1058
1059 exponent -= rhs.exponent;
1060
1061 unsigned int precision = semantics->precision;
1062
1063 /* Normalize the divisor. */
1064 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001065 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001066 exponent += bit;
1067 APInt::tcShiftLeft(divisor, partsCount, bit);
1068 }
1069
1070 /* Normalize the dividend. */
1071 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001072 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001073 exponent -= bit;
1074 APInt::tcShiftLeft(dividend, partsCount, bit);
1075 }
1076
Neil Boothb93d90e2007-10-12 16:02:31 +00001077 /* Ensure the dividend >= divisor initially for the loop below.
1078 Incidentally, this means that the division loop below is
1079 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001080 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001081 exponent--;
1082 APInt::tcShiftLeft(dividend, partsCount, 1);
1083 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1084 }
1085
1086 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001087 for (bit = precision; bit; bit -= 1) {
1088 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001089 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1090 APInt::tcSetBit(lhsSignificand, bit - 1);
1091 }
1092
1093 APInt::tcShiftLeft(dividend, partsCount, 1);
1094 }
1095
1096 /* Figure out the lost fraction. */
1097 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1098
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001099 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001100 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001101 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001102 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001103 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001104 lost_fraction = lfExactlyZero;
1105 else
1106 lost_fraction = lfLessThanHalf;
1107
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001108 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001109 delete [] dividend;
1110
1111 return lost_fraction;
1112}
1113
Tim Shen85de51d2016-10-25 19:55:59 +00001114unsigned int IEEEFloat::significandMSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001115 return APInt::tcMSB(significandParts(), partCount());
1116}
1117
Tim Shen85de51d2016-10-25 19:55:59 +00001118unsigned int IEEEFloat::significandLSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001119 return APInt::tcLSB(significandParts(), partCount());
1120}
1121
1122/* Note that a zero result is NOT normalized to fcZero. */
Tim Shen85de51d2016-10-25 19:55:59 +00001123lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001124 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001125 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001126
1127 exponent += bits;
1128
1129 return shiftRight(significandParts(), partCount(), bits);
1130}
1131
1132/* Shift the significand left BITS bits, subtract BITS from its exponent. */
Tim Shen85de51d2016-10-25 19:55:59 +00001133void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001134 assert(bits < semantics->precision);
1135
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001136 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001137 unsigned int partsCount = partCount();
1138
1139 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1140 exponent -= bits;
1141
1142 assert(!APInt::tcIsZero(significandParts(), partsCount));
1143 }
1144}
1145
Tim Shen85de51d2016-10-25 19:55:59 +00001146IEEEFloat::cmpResult
1147IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001148 int compare;
1149
1150 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001151 assert(isFiniteNonZero());
1152 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001153
1154 compare = exponent - rhs.exponent;
1155
1156 /* If exponents are equal, do an unsigned bignum comparison of the
1157 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001158 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001159 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001160 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001161
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001162 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001163 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001164 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001165 return cmpLessThan;
1166 else
1167 return cmpEqual;
1168}
1169
1170/* Handle overflow. Sign is preserved. We either become infinity or
1171 the largest finite number. */
Tim Shen85de51d2016-10-25 19:55:59 +00001172IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001173 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001174 if (rounding_mode == rmNearestTiesToEven ||
1175 rounding_mode == rmNearestTiesToAway ||
1176 (rounding_mode == rmTowardPositive && !sign) ||
1177 (rounding_mode == rmTowardNegative && sign)) {
1178 category = fcInfinity;
1179 return (opStatus) (opOverflow | opInexact);
1180 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001181
1182 /* Otherwise we become the largest finite number. */
1183 category = fcNormal;
1184 exponent = semantics->maxExponent;
1185 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001186 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001187
1188 return opInexact;
1189}
1190
Neil Booth1ca1f802007-10-03 15:16:41 +00001191/* Returns TRUE if, when truncating the current number, with BIT the
1192 new LSB, with the given lost fraction and rounding mode, the result
1193 would need to be rounded away from zero (i.e., by increasing the
1194 signficand). This routine must work for fcZero of both signs, and
1195 fcNormal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001196bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1197 lostFraction lost_fraction,
1198 unsigned int bit) const {
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001199 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001200 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001201
Neil Booth1ca1f802007-10-03 15:16:41 +00001202 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001203 assert(lost_fraction != lfExactlyZero);
1204
Mike Stump889285d2009-05-13 23:23:20 +00001205 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001206 case rmNearestTiesToAway:
1207 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1208
1209 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001210 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001211 return true;
1212
1213 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001214 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001215 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001216
1217 return false;
1218
1219 case rmTowardZero:
1220 return false;
1221
1222 case rmTowardPositive:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001223 return !sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001224
1225 case rmTowardNegative:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001226 return sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001227 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001228 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001229}
1230
Tim Shen85de51d2016-10-25 19:55:59 +00001231IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1232 lostFraction lost_fraction) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001233 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001234 int exponentChange;
1235
Michael Gottesman8136c382013-06-26 23:17:28 +00001236 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001237 return opOK;
1238
1239 /* Before rounding normalize the exponent of fcNormal numbers. */
1240 omsb = significandMSB() + 1;
1241
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001242 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001243 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001244 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001245 the exponent. */
1246 exponentChange = omsb - semantics->precision;
1247
1248 /* If the resulting exponent is too high, overflow according to
1249 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001250 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001251 return handleOverflow(rounding_mode);
1252
1253 /* Subnormal numbers have exponent minExponent, and their MSB
1254 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001255 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001256 exponentChange = semantics->minExponent - exponent;
1257
1258 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001259 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001260 assert(lost_fraction == lfExactlyZero);
1261
1262 shiftSignificandLeft(-exponentChange);
1263
1264 return opOK;
1265 }
1266
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001267 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001268 lostFraction lf;
1269
1270 /* Shift right and capture any new lost fraction. */
1271 lf = shiftSignificandRight(exponentChange);
1272
1273 lost_fraction = combineLostFractions(lf, lost_fraction);
1274
1275 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001276 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001277 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001278 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001279 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001280 }
1281 }
1282
1283 /* Now round the number according to rounding_mode given the lost
1284 fraction. */
1285
1286 /* As specified in IEEE 754, since we do not trap we do not report
1287 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001288 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001289 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001290 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001291 category = fcZero;
1292
1293 return opOK;
1294 }
1295
1296 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001297 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1298 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001299 exponent = semantics->minExponent;
1300
1301 incrementSignificand();
1302 omsb = significandMSB() + 1;
1303
1304 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001305 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001306 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001307 significand right one. However if we already have the
1308 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001309 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001310 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001311
Neil Booth9acbf5a2007-09-26 21:33:42 +00001312 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001313 }
1314
1315 shiftSignificandRight(1);
1316
1317 return opInexact;
1318 }
1319 }
1320
1321 /* The normal case - we were and are not denormal, and any
1322 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001323 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001324 return opInexact;
1325
1326 /* We have a non-zero denormal. */
1327 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001328
1329 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001330 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001331 category = fcZero;
1332
1333 /* The fcZero case is a denormal that underflowed to zero. */
1334 return (opStatus) (opUnderflow | opInexact);
1335}
1336
Tim Shen85de51d2016-10-25 19:55:59 +00001337IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1338 bool subtract) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001339 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001340 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001341 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001342
Michael Gottesman9b877e12013-06-24 09:57:57 +00001343 case PackCategoriesIntoKey(fcNaN, fcZero):
1344 case PackCategoriesIntoKey(fcNaN, fcNormal):
1345 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1346 case PackCategoriesIntoKey(fcNaN, fcNaN):
1347 case PackCategoriesIntoKey(fcNormal, fcZero):
1348 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1349 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001350 return opOK;
1351
Michael Gottesman9b877e12013-06-24 09:57:57 +00001352 case PackCategoriesIntoKey(fcZero, fcNaN):
1353 case PackCategoriesIntoKey(fcNormal, fcNaN):
1354 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Stephen Canond3278282014-06-08 16:53:31 +00001355 // We need to be sure to flip the sign here for subtraction because we
1356 // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1357 sign = rhs.sign ^ subtract;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001358 category = fcNaN;
1359 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001360 return opOK;
1361
Michael Gottesman9b877e12013-06-24 09:57:57 +00001362 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1363 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001364 category = fcInfinity;
1365 sign = rhs.sign ^ subtract;
1366 return opOK;
1367
Michael Gottesman9b877e12013-06-24 09:57:57 +00001368 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001369 assign(rhs);
1370 sign = rhs.sign ^ subtract;
1371 return opOK;
1372
Michael Gottesman9b877e12013-06-24 09:57:57 +00001373 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001374 /* Sign depends on rounding mode; handled by caller. */
1375 return opOK;
1376
Michael Gottesman9b877e12013-06-24 09:57:57 +00001377 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001378 /* Differently signed infinities can only be validly
1379 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001380 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001381 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001382 return opInvalidOp;
1383 }
1384
1385 return opOK;
1386
Michael Gottesman9b877e12013-06-24 09:57:57 +00001387 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001388 return opDivByZero;
1389 }
1390}
1391
1392/* Add or subtract two normal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001393lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1394 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001395 integerPart carry;
1396 lostFraction lost_fraction;
1397 int bits;
1398
1399 /* Determine if the operation on the absolute values is effectively
1400 an addition or subtraction. */
Aaron Ballmand5cc45f2015-03-24 12:47:51 +00001401 subtract ^= static_cast<bool>(sign ^ rhs.sign);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001402
1403 /* Are we bigger exponent-wise than the RHS? */
1404 bits = exponent - rhs.exponent;
1405
1406 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001407 if (subtract) {
Tim Shen85de51d2016-10-25 19:55:59 +00001408 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001409 bool reverse;
1410
Chris Lattner3da18eb2007-08-24 03:02:34 +00001411 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001412 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1413 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001414 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001415 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1416 shiftSignificandLeft(1);
1417 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001418 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001419 lost_fraction = shiftSignificandRight(-bits - 1);
1420 temp_rhs.shiftSignificandLeft(1);
1421 reverse = true;
1422 }
1423
Chris Lattner3da18eb2007-08-24 03:02:34 +00001424 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001425 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001426 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001427 copySignificand(temp_rhs);
1428 sign = !sign;
1429 } else {
1430 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001431 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001432 }
1433
1434 /* Invert the lost fraction - it was on the RHS and
1435 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001436 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001437 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001438 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001439 lost_fraction = lfLessThanHalf;
1440
1441 /* The code above is intended to ensure that no borrow is
1442 necessary. */
1443 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001444 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001445 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001446 if (bits > 0) {
Tim Shen85de51d2016-10-25 19:55:59 +00001447 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001448
1449 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1450 carry = addSignificand(temp_rhs);
1451 } else {
1452 lost_fraction = shiftSignificandRight(-bits);
1453 carry = addSignificand(rhs);
1454 }
1455
1456 /* We have a guard bit; generating a carry cannot happen. */
1457 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001458 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001459 }
1460
1461 return lost_fraction;
1462}
1463
Tim Shen85de51d2016-10-25 19:55:59 +00001464IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001465 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001466 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001467 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001468
Michael Gottesman9b877e12013-06-24 09:57:57 +00001469 case PackCategoriesIntoKey(fcNaN, fcZero):
1470 case PackCategoriesIntoKey(fcNaN, fcNormal):
1471 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1472 case PackCategoriesIntoKey(fcNaN, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001473 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001474 return opOK;
1475
Michael Gottesman9b877e12013-06-24 09:57:57 +00001476 case PackCategoriesIntoKey(fcZero, fcNaN):
1477 case PackCategoriesIntoKey(fcNormal, fcNaN):
1478 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001479 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001480 category = fcNaN;
1481 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001482 return opOK;
1483
Michael Gottesman9b877e12013-06-24 09:57:57 +00001484 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1485 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1486 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001487 category = fcInfinity;
1488 return opOK;
1489
Michael Gottesman9b877e12013-06-24 09:57:57 +00001490 case PackCategoriesIntoKey(fcZero, fcNormal):
1491 case PackCategoriesIntoKey(fcNormal, fcZero):
1492 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001493 category = fcZero;
1494 return opOK;
1495
Michael Gottesman9b877e12013-06-24 09:57:57 +00001496 case PackCategoriesIntoKey(fcZero, fcInfinity):
1497 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001498 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001499 return opInvalidOp;
1500
Michael Gottesman9b877e12013-06-24 09:57:57 +00001501 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001502 return opOK;
1503 }
1504}
1505
Tim Shen85de51d2016-10-25 19:55:59 +00001506IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001507 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001508 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001509 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001510
Michael Gottesman9b877e12013-06-24 09:57:57 +00001511 case PackCategoriesIntoKey(fcZero, fcNaN):
1512 case PackCategoriesIntoKey(fcNormal, fcNaN):
1513 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001514 category = fcNaN;
1515 copySignificand(rhs);
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001516 case PackCategoriesIntoKey(fcNaN, fcZero):
1517 case PackCategoriesIntoKey(fcNaN, fcNormal):
1518 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1519 case PackCategoriesIntoKey(fcNaN, fcNaN):
1520 sign = false;
1521 case PackCategoriesIntoKey(fcInfinity, fcZero):
1522 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1523 case PackCategoriesIntoKey(fcZero, fcInfinity):
1524 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001525 return opOK;
1526
Michael Gottesman9b877e12013-06-24 09:57:57 +00001527 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001528 category = fcZero;
1529 return opOK;
1530
Michael Gottesman9b877e12013-06-24 09:57:57 +00001531 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001532 category = fcInfinity;
1533 return opDivByZero;
1534
Michael Gottesman9b877e12013-06-24 09:57:57 +00001535 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1536 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001537 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001538 return opInvalidOp;
1539
Michael Gottesman9b877e12013-06-24 09:57:57 +00001540 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001541 return opOK;
1542 }
1543}
1544
Tim Shen85de51d2016-10-25 19:55:59 +00001545IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001546 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001547 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001548 llvm_unreachable(nullptr);
Dale Johannesenb5721632009-01-21 00:35:19 +00001549
Michael Gottesman9b877e12013-06-24 09:57:57 +00001550 case PackCategoriesIntoKey(fcNaN, fcZero):
1551 case PackCategoriesIntoKey(fcNaN, fcNormal):
1552 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1553 case PackCategoriesIntoKey(fcNaN, fcNaN):
1554 case PackCategoriesIntoKey(fcZero, fcInfinity):
1555 case PackCategoriesIntoKey(fcZero, fcNormal):
1556 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001557 return opOK;
1558
Michael Gottesman9b877e12013-06-24 09:57:57 +00001559 case PackCategoriesIntoKey(fcZero, fcNaN):
1560 case PackCategoriesIntoKey(fcNormal, fcNaN):
1561 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001562 sign = false;
Dale Johannesenb5721632009-01-21 00:35:19 +00001563 category = fcNaN;
1564 copySignificand(rhs);
1565 return opOK;
1566
Michael Gottesman9b877e12013-06-24 09:57:57 +00001567 case PackCategoriesIntoKey(fcNormal, fcZero):
1568 case PackCategoriesIntoKey(fcInfinity, fcZero):
1569 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1570 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1571 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001572 makeNaN();
1573 return opInvalidOp;
1574
Michael Gottesman9b877e12013-06-24 09:57:57 +00001575 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001576 return opOK;
1577 }
1578}
1579
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001580/* Change sign. */
Tim Shen85de51d2016-10-25 19:55:59 +00001581void IEEEFloat::changeSign() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001582 /* Look mummy, this one's easy. */
1583 sign = !sign;
1584}
1585
Tim Shen85de51d2016-10-25 19:55:59 +00001586void IEEEFloat::clearSign() {
Dale Johannesen689d17d2007-08-31 23:35:31 +00001587 /* So is this one. */
1588 sign = 0;
1589}
1590
Tim Shen85de51d2016-10-25 19:55:59 +00001591void IEEEFloat::copySign(const IEEEFloat &rhs) {
Dale Johannesen689d17d2007-08-31 23:35:31 +00001592 /* And this one. */
1593 sign = rhs.sign;
1594}
1595
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001596/* Normalized addition or subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001597IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
1598 roundingMode rounding_mode,
1599 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001600 opStatus fs;
1601
1602 fs = addOrSubtractSpecials(rhs, subtract);
1603
1604 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001605 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001606 lostFraction lost_fraction;
1607
1608 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1609 fs = normalize(rounding_mode, lost_fraction);
1610
1611 /* Can only be zero if we lost no fraction. */
1612 assert(category != fcZero || lost_fraction == lfExactlyZero);
1613 }
1614
1615 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1616 positive zero unless rounding to minus infinity, except that
1617 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001618 if (category == fcZero) {
1619 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001620 sign = (rounding_mode == rmTowardNegative);
1621 }
1622
1623 return fs;
1624}
1625
1626/* Normalized addition. */
Tim Shen85de51d2016-10-25 19:55:59 +00001627IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs,
1628 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001629 return addOrSubtract(rhs, rounding_mode, false);
1630}
1631
1632/* Normalized subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001633IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs,
1634 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001635 return addOrSubtract(rhs, rounding_mode, true);
1636}
1637
1638/* Normalized multiply. */
Tim Shen85de51d2016-10-25 19:55:59 +00001639IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs,
1640 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001641 opStatus fs;
1642
1643 sign ^= rhs.sign;
1644 fs = multiplySpecials(rhs);
1645
Michael Gottesman8136c382013-06-26 23:17:28 +00001646 if (isFiniteNonZero()) {
Craig Topperc10719f2014-04-07 04:17:22 +00001647 lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001648 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001649 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001650 fs = (opStatus) (fs | opInexact);
1651 }
1652
1653 return fs;
1654}
1655
1656/* Normalized divide. */
Tim Shen85de51d2016-10-25 19:55:59 +00001657IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs,
1658 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001659 opStatus fs;
1660
1661 sign ^= rhs.sign;
1662 fs = divideSpecials(rhs);
1663
Michael Gottesman8136c382013-06-26 23:17:28 +00001664 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001665 lostFraction lost_fraction = divideSignificand(rhs);
1666 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001667 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001668 fs = (opStatus) (fs | opInexact);
1669 }
1670
1671 return fs;
1672}
1673
Dale Johannesenfe750172009-01-20 18:35:05 +00001674/* Normalized remainder. This is not currently correct in all cases. */
Tim Shen85de51d2016-10-25 19:55:59 +00001675IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) {
Dale Johannesenfe750172009-01-20 18:35:05 +00001676 opStatus fs;
Tim Shen85de51d2016-10-25 19:55:59 +00001677 IEEEFloat V = *this;
Dale Johannesenfe750172009-01-20 18:35:05 +00001678 unsigned int origSign = sign;
1679
Dale Johannesenfe750172009-01-20 18:35:05 +00001680 fs = V.divide(rhs, rmNearestTiesToEven);
1681 if (fs == opDivByZero)
1682 return fs;
1683
1684 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001685 integerPart *x = new integerPart[parts];
Dale Johannesenfe750172009-01-20 18:35:05 +00001686 bool ignored;
1687 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1688 rmNearestTiesToEven, &ignored);
1689 if (fs==opInvalidOp)
1690 return fs;
1691
1692 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1693 rmNearestTiesToEven);
1694 assert(fs==opOK); // should always work
1695
1696 fs = V.multiply(rhs, rmNearestTiesToEven);
1697 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1698
1699 fs = subtract(V, rmNearestTiesToEven);
1700 assert(fs==opOK || fs==opInexact); // likewise
1701
1702 if (isZero())
1703 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001704 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001705 return fs;
1706}
1707
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001708/* Normalized llvm frem (C fmod).
Dale Johannesenfe750172009-01-20 18:35:05 +00001709 This is not currently correct in all cases. */
Tim Shen85de51d2016-10-25 19:55:59 +00001710IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) {
Dale Johannesen689d17d2007-08-31 23:35:31 +00001711 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001712 fs = modSpecials(rhs);
Dale Johannesen689d17d2007-08-31 23:35:31 +00001713
Michael Gottesman8136c382013-06-26 23:17:28 +00001714 if (isFiniteNonZero() && rhs.isFiniteNonZero()) {
Tim Shen85de51d2016-10-25 19:55:59 +00001715 IEEEFloat V = *this;
Dale Johannesenb5721632009-01-21 00:35:19 +00001716 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001717
Dale Johannesenb5721632009-01-21 00:35:19 +00001718 fs = V.divide(rhs, rmNearestTiesToEven);
1719 if (fs == opDivByZero)
1720 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001721
Dale Johannesenb5721632009-01-21 00:35:19 +00001722 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001723 integerPart *x = new integerPart[parts];
Dale Johannesenb5721632009-01-21 00:35:19 +00001724 bool ignored;
1725 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1726 rmTowardZero, &ignored);
1727 if (fs==opInvalidOp)
1728 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001729
Dale Johannesenb5721632009-01-21 00:35:19 +00001730 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1731 rmNearestTiesToEven);
1732 assert(fs==opOK); // should always work
Dale Johannesen728687c2007-09-05 20:39:49 +00001733
Stephen Canonb12db0e2015-09-21 19:29:25 +00001734 fs = V.multiply(rhs, rmNearestTiesToEven);
Dale Johannesenb5721632009-01-21 00:35:19 +00001735 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1736
Stephen Canonb12db0e2015-09-21 19:29:25 +00001737 fs = subtract(V, rmNearestTiesToEven);
Dale Johannesenb5721632009-01-21 00:35:19 +00001738 assert(fs==opOK || fs==opInexact); // likewise
1739
1740 if (isZero())
1741 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001742 delete[] x;
Dale Johannesenb5721632009-01-21 00:35:19 +00001743 }
Dale Johannesen689d17d2007-08-31 23:35:31 +00001744 return fs;
1745}
1746
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001747/* Normalized fused-multiply-add. */
Tim Shen85de51d2016-10-25 19:55:59 +00001748IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand,
1749 const IEEEFloat &addend,
1750 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001751 opStatus fs;
1752
1753 /* Post-multiplication sign, before addition. */
1754 sign ^= multiplicand.sign;
1755
1756 /* If and only if all arguments are normal do we need to do an
1757 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001758 if (isFiniteNonZero() &&
1759 multiplicand.isFiniteNonZero() &&
Hal Finkel171c2ec2014-10-14 19:23:07 +00001760 addend.isFinite()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001761 lostFraction lost_fraction;
1762
1763 lost_fraction = multiplySignificand(multiplicand, &addend);
1764 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001765 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001766 fs = (opStatus) (fs | opInexact);
1767
1768 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1769 positive zero unless rounding to minus infinity, except that
1770 adding two like-signed zeroes gives that zero. */
Lang Hames12b12e82015-01-04 01:20:55 +00001771 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001772 sign = (rounding_mode == rmTowardNegative);
1773 } else {
1774 fs = multiplySpecials(multiplicand);
1775
1776 /* FS can only be opOK or opInvalidOp. There is no more work
1777 to do in the latter case. The IEEE-754R standard says it is
1778 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001779 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001780
1781 If we need to do the addition we can do so with normal
1782 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001783 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001784 fs = addOrSubtract(addend, rounding_mode, false);
1785 }
1786
1787 return fs;
1788}
1789
Owen Andersona40319b2012-08-13 23:32:49 +00001790/* Rounding-mode corrrect round to integral value. */
Tim Shen85de51d2016-10-25 19:55:59 +00001791IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) {
Owen Andersona40319b2012-08-13 23:32:49 +00001792 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001793
Owen Anderson352dfff2012-08-15 18:28:45 +00001794 // If the exponent is large enough, we know that this value is already
1795 // integral, and the arithmetic below would potentially cause it to saturate
1796 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001797 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001798 return opOK;
1799
Owen Andersona40319b2012-08-13 23:32:49 +00001800 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1801 // precision of our format, and then subtract it back off again. The choice
1802 // of rounding modes for the addition/subtraction determines the rounding mode
1803 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001804 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001805 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001806 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1807 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Tim Shen85de51d2016-10-25 19:55:59 +00001808 IEEEFloat MagicConstant(*semantics);
Owen Andersona40319b2012-08-13 23:32:49 +00001809 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1810 rmNearestTiesToEven);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001811 MagicConstant.copySign(*this);
1812
Owen Andersona40319b2012-08-13 23:32:49 +00001813 if (fs != opOK)
1814 return fs;
1815
Owen Anderson1ff74b02012-08-15 05:39:46 +00001816 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1817 bool inputSign = isNegative();
1818
Owen Andersona40319b2012-08-13 23:32:49 +00001819 fs = add(MagicConstant, rounding_mode);
1820 if (fs != opOK && fs != opInexact)
1821 return fs;
1822
1823 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001824
1825 // Restore the input sign.
1826 if (inputSign != isNegative())
1827 changeSign();
1828
Owen Andersona40319b2012-08-13 23:32:49 +00001829 return fs;
1830}
1831
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001832
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001833/* Comparison requires normalized numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001834IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001835 cmpResult result;
1836
1837 assert(semantics == rhs.semantics);
1838
Michael Gottesman9b877e12013-06-24 09:57:57 +00001839 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001840 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001841 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001842
Michael Gottesman9b877e12013-06-24 09:57:57 +00001843 case PackCategoriesIntoKey(fcNaN, fcZero):
1844 case PackCategoriesIntoKey(fcNaN, fcNormal):
1845 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1846 case PackCategoriesIntoKey(fcNaN, fcNaN):
1847 case PackCategoriesIntoKey(fcZero, fcNaN):
1848 case PackCategoriesIntoKey(fcNormal, fcNaN):
1849 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001850 return cmpUnordered;
1851
Michael Gottesman9b877e12013-06-24 09:57:57 +00001852 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1853 case PackCategoriesIntoKey(fcInfinity, fcZero):
1854 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001855 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001856 return cmpLessThan;
1857 else
1858 return cmpGreaterThan;
1859
Michael Gottesman9b877e12013-06-24 09:57:57 +00001860 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1861 case PackCategoriesIntoKey(fcZero, fcInfinity):
1862 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001863 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001864 return cmpGreaterThan;
1865 else
1866 return cmpLessThan;
1867
Michael Gottesman9b877e12013-06-24 09:57:57 +00001868 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001869 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001870 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001871 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001872 return cmpLessThan;
1873 else
1874 return cmpGreaterThan;
1875
Michael Gottesman9b877e12013-06-24 09:57:57 +00001876 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001877 return cmpEqual;
1878
Michael Gottesman9b877e12013-06-24 09:57:57 +00001879 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001880 break;
1881 }
1882
1883 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001884 if (sign != rhs.sign) {
1885 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001886 result = cmpLessThan;
1887 else
1888 result = cmpGreaterThan;
1889 } else {
1890 /* Compare absolute values; invert result if negative. */
1891 result = compareAbsoluteValue(rhs);
1892
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001893 if (sign) {
1894 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001895 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001896 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001897 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001898 }
1899 }
1900
1901 return result;
1902}
1903
Tim Shen85de51d2016-10-25 19:55:59 +00001904/// IEEEFloat::convert - convert a value of one floating point type to another.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001905/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1906/// records whether the transformation lost information, i.e. whether
1907/// converting the result back to the original type will produce the
1908/// original value (this is almost the same as return value==fsOK, but there
1909/// are edge cases where this is not so).
1910
Tim Shen85de51d2016-10-25 19:55:59 +00001911IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics,
1912 roundingMode rounding_mode,
1913 bool *losesInfo) {
Neil Bootha8d72692007-09-22 02:56:19 +00001914 lostFraction lostFraction;
1915 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001916 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001917 int shift;
1918 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001919
Neil Bootha8d72692007-09-22 02:56:19 +00001920 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001921 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001922 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001923 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001924
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001925 bool X86SpecialNan = false;
Tim Shen85de51d2016-10-25 19:55:59 +00001926 if (&fromSemantics == &IEEEFloat::x87DoubleExtended &&
1927 &toSemantics != &IEEEFloat::x87DoubleExtended && category == fcNaN &&
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001928 (!(*significandParts() & 0x8000000000000000ULL) ||
1929 !(*significandParts() & 0x4000000000000000ULL))) {
1930 // x86 has some unusual NaNs which cannot be represented in any other
1931 // format; note them here.
1932 X86SpecialNan = true;
1933 }
1934
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00001935 // If this is a truncation of a denormal number, and the target semantics
1936 // has larger exponent range than the source semantics (this can happen
1937 // when truncating from PowerPC double-double to double format), the
1938 // right shift could lose result mantissa bits. Adjust exponent instead
1939 // of performing excessive shift.
1940 if (shift < 0 && isFiniteNonZero()) {
1941 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1942 if (exponent + exponentChange < toSemantics.minExponent)
1943 exponentChange = toSemantics.minExponent - exponent;
1944 if (exponentChange < shift)
1945 exponentChange = shift;
1946 if (exponentChange < 0) {
1947 shift -= exponentChange;
1948 exponent += exponentChange;
1949 }
1950 }
1951
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001952 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00001953 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001954 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1955
1956 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00001957 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001958 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001959 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001960 newParts = new integerPart[newPartCount];
1961 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00001962 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001963 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001964 freeSignificand();
1965 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001966 } else if (newPartCount == 1 && oldPartCount != 1) {
1967 // Switch to built-in storage for a single part.
1968 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00001969 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001970 newPart = significandParts()[0];
1971 freeSignificand();
1972 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001973 }
1974
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001975 // Now that we have the right storage, switch the semantics.
1976 semantics = &toSemantics;
1977
1978 // If this is an extension, perform the shift now that the storage is
1979 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00001980 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001981 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1982
Michael Gottesman8136c382013-06-26 23:17:28 +00001983 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00001984 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001985 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001986 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001987 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00001988
1989 // For x87 extended precision, we want to make a NaN, not a special NaN if
1990 // the input wasn't special either.
Tim Shen85de51d2016-10-25 19:55:59 +00001991 if (!X86SpecialNan && semantics == &IEEEFloat::x87DoubleExtended)
Benjamin Kramerb361adb2013-01-25 17:01:00 +00001992 APInt::tcSetBit(significandParts(), semantics->precision - 1);
1993
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001994 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1995 // does not give you back the same bits. This is dubious, and we
1996 // don't currently do it. You're really supposed to get
1997 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001998 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001999 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002000 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002001 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002002 }
2003
2004 return fs;
2005}
2006
2007/* Convert a floating point number to an integer according to the
2008 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002009 returns an invalid operation exception and the contents of the
2010 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002011 range but the floating point number is not the exact integer, the C
2012 standard doesn't require an inexact exception to be raised. IEEE
2013 854 does require it so we do that.
2014
2015 Note that for conversions to integer type the C standard requires
2016 round-to-zero to always be used. */
Tim Shen85de51d2016-10-25 19:55:59 +00002017IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
2018 integerPart *parts, unsigned int width, bool isSigned,
2019 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002020 lostFraction lost_fraction;
2021 const integerPart *src;
2022 unsigned int dstPartsCount, truncatedBits;
2023
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002024 *isExact = false;
2025
Neil Booth618d0fc2007-11-01 22:43:37 +00002026 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002027 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002028 return opInvalidOp;
2029
2030 dstPartsCount = partCountForBits(width);
2031
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002032 if (category == fcZero) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002033 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002034 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002035 *isExact = !sign;
2036 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002037 }
2038
2039 src = significandParts();
2040
2041 /* Step 1: place our absolute value, with any fraction truncated, in
2042 the destination. */
2043 if (exponent < 0) {
2044 /* Our absolute value is less than one; truncate everything. */
2045 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002046 /* For exponent -1 the integer bit represents .5, look at that.
2047 For smaller exponents leftmost truncated bit is 0. */
2048 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002049 } else {
2050 /* We want the most significant (exponent + 1) bits; the rest are
2051 truncated. */
2052 unsigned int bits = exponent + 1U;
2053
2054 /* Hopelessly large in magnitude? */
2055 if (bits > width)
2056 return opInvalidOp;
2057
2058 if (bits < semantics->precision) {
2059 /* We truncate (semantics->precision - bits) bits. */
2060 truncatedBits = semantics->precision - bits;
2061 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2062 } else {
2063 /* We want at least as many bits as are available. */
2064 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2065 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2066 truncatedBits = 0;
2067 }
2068 }
2069
2070 /* Step 2: work out any lost fraction, and increment the absolute
2071 value if we would round away from zero. */
2072 if (truncatedBits) {
2073 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2074 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002075 if (lost_fraction != lfExactlyZero &&
2076 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002077 if (APInt::tcIncrement(parts, dstPartsCount))
2078 return opInvalidOp; /* Overflow. */
2079 }
2080 } else {
2081 lost_fraction = lfExactlyZero;
2082 }
2083
2084 /* Step 3: check if we fit in the destination. */
2085 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2086
2087 if (sign) {
2088 if (!isSigned) {
2089 /* Negative numbers cannot be represented as unsigned. */
2090 if (omsb != 0)
2091 return opInvalidOp;
2092 } else {
2093 /* It takes omsb bits to represent the unsigned integer value.
2094 We lose a bit for the sign, but care is needed as the
2095 maximally negative integer is a special case. */
2096 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2097 return opInvalidOp;
2098
2099 /* This case can happen because of rounding. */
2100 if (omsb > width)
2101 return opInvalidOp;
2102 }
2103
2104 APInt::tcNegate (parts, dstPartsCount);
2105 } else {
2106 if (omsb >= width + !isSigned)
2107 return opInvalidOp;
2108 }
2109
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002110 if (lost_fraction == lfExactlyZero) {
2111 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002112 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002113 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002114 return opInexact;
2115}
2116
2117/* Same as convertToSignExtendedInteger, except we provide
2118 deterministic values in case of an invalid operation exception,
2119 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002120 for underflow or overflow.
2121 The *isExact output tells whether the result is exact, in the sense
2122 that converting it back to the original floating point type produces
2123 the original value. This is almost equivalent to result==opOK,
2124 except for negative zeroes.
2125*/
Tim Shen85de51d2016-10-25 19:55:59 +00002126IEEEFloat::opStatus IEEEFloat::convertToInteger(integerPart *parts,
2127 unsigned int width,
2128 bool isSigned,
2129 roundingMode rounding_mode,
2130 bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002131 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002132
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002133 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002134 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002135
Neil Booth618d0fc2007-11-01 22:43:37 +00002136 if (fs == opInvalidOp) {
2137 unsigned int bits, dstPartsCount;
2138
2139 dstPartsCount = partCountForBits(width);
2140
2141 if (category == fcNaN)
2142 bits = 0;
2143 else if (sign)
2144 bits = isSigned;
2145 else
2146 bits = width - isSigned;
2147
2148 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2149 if (sign && isSigned)
2150 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002151 }
2152
Neil Booth618d0fc2007-11-01 22:43:37 +00002153 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002154}
2155
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002156/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2157 an APSInt, whose initial bit-width and signed-ness are used to determine the
2158 precision of the conversion.
2159 */
Tim Shen85de51d2016-10-25 19:55:59 +00002160IEEEFloat::opStatus IEEEFloat::convertToInteger(APSInt &result,
2161 roundingMode rounding_mode,
2162 bool *isExact) const {
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002163 unsigned bitWidth = result.getBitWidth();
2164 SmallVector<uint64_t, 4> parts(result.getNumWords());
2165 opStatus status = convertToInteger(
2166 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2167 // Keeps the original signed-ness.
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002168 result = APInt(bitWidth, parts);
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002169 return status;
2170}
2171
Neil Booth6c1c8582007-10-07 12:07:53 +00002172/* Convert an unsigned integer SRC to a floating point number,
2173 rounding according to ROUNDING_MODE. The sign of the floating
2174 point number is not modified. */
Tim Shen85de51d2016-10-25 19:55:59 +00002175IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2176 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
Neil Booth49c6aab2007-10-08 14:39:42 +00002177 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002178 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002179 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002180
2181 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002182 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002183 dst = significandParts();
2184 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002185 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002186
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002187 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002188 be that many; extract what we can. */
2189 if (precision <= omsb) {
2190 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002191 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002192 omsb - precision);
2193 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2194 } else {
2195 exponent = precision - 1;
2196 lost_fraction = lfExactlyZero;
2197 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002198 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002199
2200 return normalize(rounding_mode, lost_fraction);
2201}
2202
Tim Shen85de51d2016-10-25 19:55:59 +00002203IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned,
2204 roundingMode rounding_mode) {
Dan Gohman35723eb2008-02-29 01:26:11 +00002205 unsigned int partCount = Val.getNumWords();
2206 APInt api = Val;
2207
2208 sign = false;
2209 if (isSigned && api.isNegative()) {
2210 sign = true;
2211 api = -api;
2212 }
2213
2214 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2215}
2216
Neil Booth03f58ab2007-10-07 12:15:41 +00002217/* Convert a two's complement integer SRC to a floating point number,
2218 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2219 integer is signed, in which case it must be sign-extended. */
Tim Shen85de51d2016-10-25 19:55:59 +00002220IEEEFloat::opStatus
2221IEEEFloat::convertFromSignExtendedInteger(const integerPart *src,
2222 unsigned int srcCount, bool isSigned,
2223 roundingMode rounding_mode) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002224 opStatus status;
2225
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002226 if (isSigned &&
2227 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002228 integerPart *copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002229
2230 /* If we're signed and negative negate a copy. */
2231 sign = true;
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002232 copy = new integerPart[srcCount];
Neil Booth03f58ab2007-10-07 12:15:41 +00002233 APInt::tcAssign(copy, src, srcCount);
2234 APInt::tcNegate(copy, srcCount);
2235 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002236 delete [] copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002237 } else {
2238 sign = false;
2239 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2240 }
2241
2242 return status;
2243}
2244
Neil Booth5f009732007-10-07 11:45:55 +00002245/* FIXME: should this just take a const APInt reference? */
Tim Shen85de51d2016-10-25 19:55:59 +00002246IEEEFloat::opStatus
2247IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2248 unsigned int width, bool isSigned,
2249 roundingMode rounding_mode) {
Dale Johannesen42305122007-09-21 22:09:37 +00002250 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002251 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002252
2253 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002254 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002255 sign = true;
2256 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002257 }
2258
Neil Boothba205222007-10-07 12:10:57 +00002259 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002260}
2261
Tim Shen85de51d2016-10-25 19:55:59 +00002262IEEEFloat::opStatus
2263IEEEFloat::convertFromHexadecimalString(StringRef s,
2264 roundingMode rounding_mode) {
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002265 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002266
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002267 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002268 zeroSignificand();
2269 exponent = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002270
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002271 integerPart *significand = significandParts();
2272 unsigned partsCount = partCount();
2273 unsigned bitPos = partsCount * integerPartWidth;
2274 bool computedTrailingFraction = false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002275
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002276 // Skip leading zeroes and any (hexa)decimal point.
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002277 StringRef::iterator begin = s.begin();
2278 StringRef::iterator end = s.end();
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002279 StringRef::iterator dot;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002280 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002281 StringRef::iterator firstSignificantDigit = p;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002282
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002283 while (p != end) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002284 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002285
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002286 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002287 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002288 dot = p++;
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002289 continue;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002290 }
2291
2292 hex_value = hexDigitValue(*p);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002293 if (hex_value == -1U)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002294 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002295
2296 p++;
2297
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002298 // Store the number while we have space.
2299 if (bitPos) {
2300 bitPos -= 4;
2301 hex_value <<= bitPos % integerPartWidth;
2302 significand[bitPos / integerPartWidth] |= hex_value;
2303 } else if (!computedTrailingFraction) {
2304 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2305 computedTrailingFraction = true;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002306 }
2307 }
2308
2309 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002310 assert(p != end && "Hex strings require an exponent");
2311 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2312 assert(p != begin && "Significand has no digits");
2313 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002314
2315 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002316 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002317 int expAdjustment;
2318
2319 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002320 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002321 dot = p;
2322
2323 /* Calculate the exponent adjustment implicit in the number of
2324 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002325 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002326 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002327 expAdjustment++;
2328 expAdjustment = expAdjustment * 4 - 1;
2329
2330 /* Adjust for writing the significand starting at the most
2331 significant nibble. */
2332 expAdjustment += semantics->precision;
2333 expAdjustment -= partsCount * integerPartWidth;
2334
2335 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002336 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002337 }
2338
2339 return normalize(rounding_mode, lost_fraction);
2340}
2341
Tim Shen85de51d2016-10-25 19:55:59 +00002342IEEEFloat::opStatus
2343IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2344 unsigned sigPartCount, int exp,
2345 roundingMode rounding_mode) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002346 unsigned int parts, pow5PartCount;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00002347 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002348 integerPart pow5Parts[maxPowerOfFiveParts];
2349 bool isNearest;
2350
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002351 isNearest = (rounding_mode == rmNearestTiesToEven ||
2352 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002353
2354 parts = partCountForBits(semantics->precision + 11);
2355
2356 /* Calculate pow(5, abs(exp)). */
2357 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2358
2359 for (;; parts *= 2) {
2360 opStatus sigStatus, powStatus;
2361 unsigned int excessPrecision, truncatedBits;
2362
2363 calcSemantics.precision = parts * integerPartWidth - 1;
2364 excessPrecision = calcSemantics.precision - semantics->precision;
2365 truncatedBits = excessPrecision;
2366
Tim Shen139a58f2016-10-27 22:52:40 +00002367 IEEEFloat decSig(calcSemantics, uninitialized);
2368 decSig.makeZero(sign);
Tim Shen85de51d2016-10-25 19:55:59 +00002369 IEEEFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002370
2371 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2372 rmNearestTiesToEven);
2373 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2374 rmNearestTiesToEven);
2375 /* Add exp, as 10^n = 5^n * 2^n. */
2376 decSig.exponent += exp;
2377
2378 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002379 integerPart HUerr, HUdistance;
2380 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002381
2382 if (exp >= 0) {
2383 /* multiplySignificand leaves the precision-th bit set to 1. */
Craig Topperc10719f2014-04-07 04:17:22 +00002384 calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
Neil Boothb93d90e2007-10-12 16:02:31 +00002385 powHUerr = powStatus != opOK;
2386 } else {
2387 calcLostFraction = decSig.divideSignificand(pow5);
2388 /* Denormal numbers have less precision. */
2389 if (decSig.exponent < semantics->minExponent) {
2390 excessPrecision += (semantics->minExponent - decSig.exponent);
2391 truncatedBits = excessPrecision;
2392 if (excessPrecision > calcSemantics.precision)
2393 excessPrecision = calcSemantics.precision;
2394 }
2395 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002396 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002397 }
2398
2399 /* Both multiplySignificand and divideSignificand return the
2400 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002401 assert(APInt::tcExtractBit
2402 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002403
2404 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2405 powHUerr);
2406 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2407 excessPrecision, isNearest);
2408
2409 /* Are we guaranteed to round correctly if we truncate? */
2410 if (HUdistance >= HUerr) {
2411 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2412 calcSemantics.precision - excessPrecision,
2413 excessPrecision);
2414 /* Take the exponent of decSig. If we tcExtract-ed less bits
2415 above we must adjust our exponent to compensate for the
2416 implicit right shift. */
2417 exponent = (decSig.exponent + semantics->precision
2418 - (calcSemantics.precision - excessPrecision));
2419 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2420 decSig.partCount(),
2421 truncatedBits);
2422 return normalize(rounding_mode, calcLostFraction);
2423 }
2424 }
2425}
2426
Tim Shen85de51d2016-10-25 19:55:59 +00002427IEEEFloat::opStatus
2428IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
Neil Booth4ed401b2007-10-14 10:16:12 +00002429 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002430 opStatus fs;
2431
Neil Booth4ed401b2007-10-14 10:16:12 +00002432 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002433 StringRef::iterator p = str.begin();
2434 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002435
Neil Booth91305512007-10-15 15:00:55 +00002436 /* Handle the quick cases. First the case of no significant digits,
2437 i.e. zero, and then exponents that are obviously too large or too
2438 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2439 definitely overflows if
2440
2441 (exp - 1) * L >= maxExponent
2442
2443 and definitely underflows to zero where
2444
2445 (exp + 1) * L <= minExponent - precision
2446
2447 With integer arithmetic the tightest bounds for L are
2448
2449 93/28 < L < 196/59 [ numerator <= 256 ]
2450 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2451 */
2452
Michael Gottesman228156c2013-07-01 23:54:08 +00002453 // Test if we have a zero number allowing for strings with no null terminators
2454 // and zero decimals with non-zero exponents.
2455 //
2456 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2457 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2458 // be at most one dot. On the other hand, if we have a zero with a non-zero
2459 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002460 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002461 category = fcZero;
2462 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002463
2464 /* Check whether the normalized exponent is high enough to overflow
2465 max during the log-rebasing in the max-exponent check below. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002466 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
John McCallb42cc682010-02-26 22:20:41 +00002467 fs = handleOverflow(rounding_mode);
2468
2469 /* If it wasn't, then it also wasn't high enough to overflow max
2470 during the log-rebasing in the min-exponent check. Check that it
2471 won't overflow min in either check, then perform the min-exponent
2472 check. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002473 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
John McCallb42cc682010-02-26 22:20:41 +00002474 (D.normalizedExponent + 1) * 28738 <=
2475 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002476 /* Underflow to zero and round. */
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002477 category = fcNormal;
Neil Booth91305512007-10-15 15:00:55 +00002478 zeroSignificand();
2479 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002480
2481 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002482 } else if ((D.normalizedExponent - 1) * 42039
2483 >= 12655 * semantics->maxExponent) {
2484 /* Overflow and round. */
2485 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002486 } else {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002487 integerPart *decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002488 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002489
Neil Booth4ed401b2007-10-14 10:16:12 +00002490 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002491 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002492 to hold the full significand, and an extra part required by
2493 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002494 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002495 partCount = partCountForBits(1 + 196 * partCount / 59);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002496 decSignificand = new integerPart[partCount + 1];
Neil Booth4ed401b2007-10-14 10:16:12 +00002497 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002498
Neil Booth4ed401b2007-10-14 10:16:12 +00002499 /* Convert to binary efficiently - we do almost all multiplication
2500 in an integerPart. When this would overflow do we do a single
2501 bignum multiplication, and then revert again to multiplication
2502 in an integerPart. */
2503 do {
2504 integerPart decValue, val, multiplier;
2505
2506 val = 0;
2507 multiplier = 1;
2508
2509 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002510 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002511 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002512 if (p == str.end()) {
2513 break;
2514 }
2515 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002516 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002517 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002518 multiplier *= 10;
2519 val = val * 10 + decValue;
2520 /* The maximum number that can be multiplied by ten with any
2521 digit added without overflowing an integerPart. */
2522 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2523
2524 /* Multiply out the current part. */
2525 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2526 partCount, partCount + 1, false);
2527
2528 /* If we used another part (likely but not guaranteed), increase
2529 the count. */
2530 if (decSignificand[partCount])
2531 partCount++;
2532 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002533
Neil Boothae077d22007-11-01 22:51:07 +00002534 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002535 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002536 D.exponent, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002537
2538 delete [] decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002539 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002540
2541 return fs;
2542}
2543
Tim Shen85de51d2016-10-25 19:55:59 +00002544bool IEEEFloat::convertFromStringSpecials(StringRef str) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002545 if (str.equals("inf") || str.equals("INFINITY")) {
2546 makeInf(false);
2547 return true;
2548 }
2549
2550 if (str.equals("-inf") || str.equals("-INFINITY")) {
2551 makeInf(true);
2552 return true;
2553 }
2554
2555 if (str.equals("nan") || str.equals("NaN")) {
2556 makeNaN(false, false);
2557 return true;
2558 }
2559
2560 if (str.equals("-nan") || str.equals("-NaN")) {
2561 makeNaN(false, true);
2562 return true;
2563 }
2564
2565 return false;
2566}
2567
Tim Shen85de51d2016-10-25 19:55:59 +00002568IEEEFloat::opStatus IEEEFloat::convertFromString(StringRef str,
2569 roundingMode rounding_mode) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002570 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002571
Michael Gottesman40e8a182013-06-24 09:58:05 +00002572 // Handle special cases.
2573 if (convertFromStringSpecials(str))
2574 return opOK;
2575
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002576 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002577 StringRef::iterator p = str.begin();
2578 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002579 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002580 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002581 p++;
2582 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002583 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002584 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002585
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002586 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002587 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002588 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002589 rounding_mode);
2590 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002591
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002592 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002593}
Dale Johannesena719a602007-08-24 00:56:33 +00002594
Neil Booth8f1946f2007-10-03 22:26:02 +00002595/* Write out a hexadecimal representation of the floating point value
2596 to DST, which must be of sufficient size, in the C99 form
2597 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2598 excluding the terminating NUL.
2599
2600 If UPPERCASE, the output is in upper case, otherwise in lower case.
2601
2602 HEXDIGITS digits appear altogether, rounding the value if
2603 necessary. If HEXDIGITS is 0, the minimal precision to display the
2604 number precisely is used instead. If nothing would appear after
2605 the decimal point it is suppressed.
2606
2607 The decimal exponent is always printed and has at least one digit.
2608 Zero values display an exponent of zero. Infinities and NaNs
2609 appear as "infinity" or "nan" respectively.
2610
2611 The above rules are as specified by C99. There is ambiguity about
2612 what the leading hexadecimal digit should be. This implementation
2613 uses whatever is necessary so that the exponent is displayed as
2614 stored. This implies the exponent will fall within the IEEE format
2615 range, and the leading hexadecimal digit will be 0 (for denormals),
2616 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2617 any other digits zero).
2618*/
Tim Shen85de51d2016-10-25 19:55:59 +00002619unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
2620 bool upperCase,
2621 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002622 char *p;
2623
2624 p = dst;
2625 if (sign)
2626 *dst++ = '-';
2627
2628 switch (category) {
2629 case fcInfinity:
2630 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2631 dst += sizeof infinityL - 1;
2632 break;
2633
2634 case fcNaN:
2635 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2636 dst += sizeof NaNU - 1;
2637 break;
2638
2639 case fcZero:
2640 *dst++ = '0';
2641 *dst++ = upperCase ? 'X': 'x';
2642 *dst++ = '0';
2643 if (hexDigits > 1) {
2644 *dst++ = '.';
2645 memset (dst, '0', hexDigits - 1);
2646 dst += hexDigits - 1;
2647 }
2648 *dst++ = upperCase ? 'P': 'p';
2649 *dst++ = '0';
2650 break;
2651
2652 case fcNormal:
2653 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2654 break;
2655 }
2656
2657 *dst = 0;
2658
Evan Cheng82b9e962008-05-02 21:15:08 +00002659 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002660}
2661
2662/* Does the hard work of outputting the correctly rounded hexadecimal
2663 form of a normal floating point number with the specified number of
2664 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2665 digits necessary to print the value precisely is output. */
Tim Shen85de51d2016-10-25 19:55:59 +00002666char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2667 bool upperCase,
2668 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002669 unsigned int count, valueBits, shift, partsCount, outputDigits;
2670 const char *hexDigitChars;
2671 const integerPart *significand;
2672 char *p;
2673 bool roundUp;
2674
2675 *dst++ = '0';
2676 *dst++ = upperCase ? 'X': 'x';
2677
2678 roundUp = false;
2679 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2680
2681 significand = significandParts();
2682 partsCount = partCount();
2683
2684 /* +3 because the first digit only uses the single integer bit, so
2685 we have 3 virtual zero most-significant-bits. */
2686 valueBits = semantics->precision + 3;
2687 shift = integerPartWidth - valueBits % integerPartWidth;
2688
2689 /* The natural number of digits required ignoring trailing
2690 insignificant zeroes. */
2691 outputDigits = (valueBits - significandLSB () + 3) / 4;
2692
2693 /* hexDigits of zero means use the required number for the
2694 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002695 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002696 if (hexDigits) {
2697 if (hexDigits < outputDigits) {
2698 /* We are dropping non-zero bits, so need to check how to round.
2699 "bits" is the number of dropped bits. */
2700 unsigned int bits;
2701 lostFraction fraction;
2702
2703 bits = valueBits - hexDigits * 4;
2704 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2705 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2706 }
2707 outputDigits = hexDigits;
2708 }
2709
2710 /* Write the digits consecutively, and start writing in the location
2711 of the hexadecimal point. We move the most significant digit
2712 left and add the hexadecimal point later. */
2713 p = ++dst;
2714
2715 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2716
2717 while (outputDigits && count) {
2718 integerPart part;
2719
2720 /* Put the most significant integerPartWidth bits in "part". */
2721 if (--count == partsCount)
2722 part = 0; /* An imaginary higher zero part. */
2723 else
2724 part = significand[count] << shift;
2725
2726 if (count && shift)
2727 part |= significand[count - 1] >> (integerPartWidth - shift);
2728
2729 /* Convert as much of "part" to hexdigits as we can. */
2730 unsigned int curDigits = integerPartWidth / 4;
2731
2732 if (curDigits > outputDigits)
2733 curDigits = outputDigits;
2734 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2735 outputDigits -= curDigits;
2736 }
2737
2738 if (roundUp) {
2739 char *q = dst;
2740
2741 /* Note that hexDigitChars has a trailing '0'. */
2742 do {
2743 q--;
2744 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002745 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002746 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002747 } else {
2748 /* Add trailing zeroes. */
2749 memset (dst, '0', outputDigits);
2750 dst += outputDigits;
2751 }
2752
2753 /* Move the most significant digit to before the point, and if there
2754 is something after the decimal point add it. This must come
2755 after rounding above. */
2756 p[-1] = p[0];
2757 if (dst -1 == p)
2758 dst--;
2759 else
2760 p[0] = '.';
2761
2762 /* Finally output the exponent. */
2763 *dst++ = upperCase ? 'P': 'p';
2764
Neil Booth32897f52007-10-06 07:29:25 +00002765 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002766}
2767
Tim Shen85de51d2016-10-25 19:55:59 +00002768hash_code hash_value(const IEEEFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002769 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002770 return hash_combine((uint8_t)Arg.category,
2771 // NaN has no sign, fix it at zero.
2772 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2773 Arg.semantics->precision);
2774
2775 // Normal floats need their exponent and significand hashed.
2776 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2777 Arg.semantics->precision, Arg.exponent,
2778 hash_combine_range(
2779 Arg.significandParts(),
2780 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002781}
2782
2783// Conversion from APFloat to/from host float/double. It may eventually be
2784// possible to eliminate these and have everybody deal with APFloats, but that
2785// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002786// Current implementation requires integerPartWidth==64, which is correct at
2787// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002788
Dale Johannesen728687c2007-09-05 20:39:49 +00002789// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002790// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002791
Tim Shen85de51d2016-10-25 19:55:59 +00002792APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
Dan Gohmanb456a152008-01-29 12:08:20 +00002793 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002794 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002795
2796 uint64_t myexponent, mysignificand;
2797
Michael Gottesman8136c382013-06-26 23:17:28 +00002798 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002799 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002800 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002801 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2802 myexponent = 0; // denormal
2803 } else if (category==fcZero) {
2804 myexponent = 0;
2805 mysignificand = 0;
2806 } else if (category==fcInfinity) {
2807 myexponent = 0x7fff;
2808 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002809 } else {
2810 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002811 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002812 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002813 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002814
2815 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002816 words[0] = mysignificand;
2817 words[1] = ((uint64_t)(sign & 1) << 15) |
2818 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002819 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002820}
2821
Tim Shen85de51d2016-10-25 19:55:59 +00002822APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const {
Tim Shen139a58f2016-10-27 22:52:40 +00002823 assert(semantics == (const llvm::fltSemantics *)&PPCDoubleDoubleImpl);
Evan Cheng67c90212009-10-27 21:35:42 +00002824 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002825
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002826 uint64_t words[2];
2827 opStatus fs;
2828 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002829
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002830 // Convert number to double. To avoid spurious underflows, we re-
2831 // normalize against the "double" minExponent first, and only *then*
2832 // truncate the mantissa. The result of that second conversion
2833 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002834 // Declare fltSemantics before APFloat that uses it (and
2835 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002836 fltSemantics extendedSemantics = *semantics;
2837 extendedSemantics.minExponent = IEEEdouble.minExponent;
Tim Shen85de51d2016-10-25 19:55:59 +00002838 IEEEFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002839 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2840 assert(fs == opOK && !losesInfo);
2841 (void)fs;
2842
Tim Shen85de51d2016-10-25 19:55:59 +00002843 IEEEFloat u(extended);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002844 fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2845 assert(fs == opOK || fs == opInexact);
2846 (void)fs;
2847 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2848
2849 // If conversion was exact or resulted in a special case, we're done;
2850 // just set the second double to zero. Otherwise, re-convert back to
2851 // the extended format and compute the difference. This now should
2852 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002853 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002854 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2855 assert(fs == opOK && !losesInfo);
2856 (void)fs;
2857
Tim Shen85de51d2016-10-25 19:55:59 +00002858 IEEEFloat v(extended);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002859 v.subtract(u, rmNearestTiesToEven);
2860 fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2861 assert(fs == opOK && !losesInfo);
2862 (void)fs;
2863 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002864 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002865 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002866 }
2867
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002868 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002869}
2870
Tim Shen85de51d2016-10-25 19:55:59 +00002871APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002872 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002873 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002874
2875 uint64_t myexponent, mysignificand, mysignificand2;
2876
Michael Gottesman8136c382013-06-26 23:17:28 +00002877 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002878 myexponent = exponent+16383; //bias
2879 mysignificand = significandParts()[0];
2880 mysignificand2 = significandParts()[1];
2881 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2882 myexponent = 0; // denormal
2883 } else if (category==fcZero) {
2884 myexponent = 0;
2885 mysignificand = mysignificand2 = 0;
2886 } else if (category==fcInfinity) {
2887 myexponent = 0x7fff;
2888 mysignificand = mysignificand2 = 0;
2889 } else {
2890 assert(category == fcNaN && "Unknown category!");
2891 myexponent = 0x7fff;
2892 mysignificand = significandParts()[0];
2893 mysignificand2 = significandParts()[1];
2894 }
2895
2896 uint64_t words[2];
2897 words[0] = mysignificand;
2898 words[1] = ((uint64_t)(sign & 1) << 63) |
2899 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002900 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002901
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002902 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002903}
2904
Tim Shen85de51d2016-10-25 19:55:59 +00002905APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
Dan Gohman58c468f2007-09-14 20:08:19 +00002906 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002907 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002908
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002909 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002910
Michael Gottesman8136c382013-06-26 23:17:28 +00002911 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002912 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002913 mysignificand = *significandParts();
2914 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2915 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002916 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002917 myexponent = 0;
2918 mysignificand = 0;
2919 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002920 myexponent = 0x7ff;
2921 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002922 } else {
2923 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002924 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002925 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002926 }
Dale Johannesena719a602007-08-24 00:56:33 +00002927
Evan Cheng82b9e962008-05-02 21:15:08 +00002928 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002929 ((myexponent & 0x7ff) << 52) |
2930 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002931}
2932
Tim Shen85de51d2016-10-25 19:55:59 +00002933APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
Dan Gohman58c468f2007-09-14 20:08:19 +00002934 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002935 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002936
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002937 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002938
Michael Gottesman8136c382013-06-26 23:17:28 +00002939 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002940 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00002941 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00002942 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00002943 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002944 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002945 myexponent = 0;
2946 mysignificand = 0;
2947 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002948 myexponent = 0xff;
2949 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002950 } else {
2951 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00002952 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00002953 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002954 }
Dale Johannesena719a602007-08-24 00:56:33 +00002955
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002956 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2957 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00002958}
2959
Tim Shen85de51d2016-10-25 19:55:59 +00002960APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
Chris Lattner4794b2b2009-10-16 02:13:51 +00002961 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00002962 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00002963
2964 uint32_t myexponent, mysignificand;
2965
Michael Gottesman8136c382013-06-26 23:17:28 +00002966 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00002967 myexponent = exponent+15; //bias
2968 mysignificand = (uint32_t)*significandParts();
2969 if (myexponent == 1 && !(mysignificand & 0x400))
2970 myexponent = 0; // denormal
2971 } else if (category==fcZero) {
2972 myexponent = 0;
2973 mysignificand = 0;
2974 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00002975 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002976 mysignificand = 0;
2977 } else {
2978 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00002979 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002980 mysignificand = (uint32_t)*significandParts();
2981 }
2982
2983 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2984 (mysignificand & 0x3ff)));
2985}
2986
Dale Johannesen007aa372007-10-11 18:07:22 +00002987// This function creates an APInt that is just a bit map of the floating
2988// point constant as it would appear in memory. It is not a conversion,
2989// and treating the result as a normal integer is unlikely to be useful.
2990
Tim Shen85de51d2016-10-25 19:55:59 +00002991APInt IEEEFloat::bitcastToAPInt() const {
Chris Lattner4794b2b2009-10-16 02:13:51 +00002992 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2993 return convertHalfAPFloatToAPInt();
2994
Dan Gohmanb456a152008-01-29 12:08:20 +00002995 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00002996 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002997
Dan Gohmanb456a152008-01-29 12:08:20 +00002998 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00002999 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003000
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003001 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
3002 return convertQuadrupleAPFloatToAPInt();
3003
Tim Shen139a58f2016-10-27 22:52:40 +00003004 if (semantics == (const llvm::fltSemantics *)&PPCDoubleDoubleImpl)
Dale Johannesen007aa372007-10-11 18:07:22 +00003005 return convertPPCDoubleDoubleAPFloatToAPInt();
3006
Dan Gohmanb456a152008-01-29 12:08:20 +00003007 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003008 "unknown format!");
3009 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003010}
3011
Tim Shen85de51d2016-10-25 19:55:59 +00003012float IEEEFloat::convertToFloat() const {
Chris Lattner688f9912009-09-24 21:44:20 +00003013 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
3014 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003015 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003016 return api.bitsToFloat();
3017}
3018
Tim Shen85de51d2016-10-25 19:55:59 +00003019double IEEEFloat::convertToDouble() const {
Chris Lattner688f9912009-09-24 21:44:20 +00003020 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
3021 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003022 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003023 return api.bitsToDouble();
3024}
3025
Dale Johannesenfff29952008-10-06 18:22:29 +00003026/// Integer bit is explicit in this format. Intel hardware (387 and later)
3027/// does not support these bit patterns:
3028/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3029/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3030/// exponent = 0, integer bit 1 ("pseudodenormal")
3031/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3032/// At the moment, the first two are treated as NaNs, the second two as Normal.
Tim Shen85de51d2016-10-25 19:55:59 +00003033void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003034 assert(api.getBitWidth()==80);
3035 uint64_t i1 = api.getRawData()[0];
3036 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003037 uint64_t myexponent = (i2 & 0x7fff);
3038 uint64_t mysignificand = i1;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003039
Tim Shen85de51d2016-10-25 19:55:59 +00003040 initialize(&IEEEFloat::x87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003041 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003042
Dale Johannesen93eefa02009-03-23 21:16:53 +00003043 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003044 if (myexponent==0 && mysignificand==0) {
3045 // exponent, significand meaningless
3046 category = fcZero;
3047 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3048 // exponent, significand meaningless
3049 category = fcInfinity;
3050 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3051 // exponent meaningless
3052 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003053 significandParts()[0] = mysignificand;
3054 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003055 } else {
3056 category = fcNormal;
3057 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003058 significandParts()[0] = mysignificand;
3059 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003060 if (myexponent==0) // denormal
3061 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003062 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003063}
3064
Tim Shen85de51d2016-10-25 19:55:59 +00003065void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) {
Dale Johannesen007aa372007-10-11 18:07:22 +00003066 assert(api.getBitWidth()==128);
3067 uint64_t i1 = api.getRawData()[0];
3068 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003069 opStatus fs;
3070 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003071
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003072 // Get the first double and convert to our format.
3073 initFromDoubleAPInt(APInt(64, i1));
Tim Shen139a58f2016-10-27 22:52:40 +00003074 fs = convert(PPCDoubleDoubleImpl, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003075 assert(fs == opOK && !losesInfo);
3076 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003077
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003078 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003079 if (isFiniteNonZero()) {
Tim Shen85de51d2016-10-25 19:55:59 +00003080 IEEEFloat v(IEEEdouble, APInt(64, i2));
Tim Shen139a58f2016-10-27 22:52:40 +00003081 fs = v.convert(PPCDoubleDoubleImpl, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003082 assert(fs == opOK && !losesInfo);
3083 (void)fs;
3084
3085 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003086 }
3087}
3088
Tim Shen85de51d2016-10-25 19:55:59 +00003089void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003090 assert(api.getBitWidth()==128);
3091 uint64_t i1 = api.getRawData()[0];
3092 uint64_t i2 = api.getRawData()[1];
3093 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3094 uint64_t mysignificand = i1;
3095 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3096
Tim Shen85de51d2016-10-25 19:55:59 +00003097 initialize(&IEEEFloat::IEEEquad);
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003098 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003099
3100 sign = static_cast<unsigned int>(i2>>63);
3101 if (myexponent==0 &&
3102 (mysignificand==0 && mysignificand2==0)) {
3103 // exponent, significand meaningless
3104 category = fcZero;
3105 } else if (myexponent==0x7fff &&
3106 (mysignificand==0 && mysignificand2==0)) {
3107 // exponent, significand meaningless
3108 category = fcInfinity;
3109 } else if (myexponent==0x7fff &&
3110 (mysignificand!=0 || mysignificand2 !=0)) {
3111 // exponent meaningless
3112 category = fcNaN;
3113 significandParts()[0] = mysignificand;
3114 significandParts()[1] = mysignificand2;
3115 } else {
3116 category = fcNormal;
3117 exponent = myexponent - 16383;
3118 significandParts()[0] = mysignificand;
3119 significandParts()[1] = mysignificand2;
3120 if (myexponent==0) // denormal
3121 exponent = -16382;
3122 else
3123 significandParts()[1] |= 0x1000000000000LL; // integer bit
3124 }
3125}
3126
Tim Shen85de51d2016-10-25 19:55:59 +00003127void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003128 assert(api.getBitWidth()==64);
3129 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003130 uint64_t myexponent = (i >> 52) & 0x7ff;
3131 uint64_t mysignificand = i & 0xfffffffffffffLL;
3132
Tim Shen85de51d2016-10-25 19:55:59 +00003133 initialize(&IEEEFloat::IEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003134 assert(partCount()==1);
3135
Evan Cheng82b9e962008-05-02 21:15:08 +00003136 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003137 if (myexponent==0 && mysignificand==0) {
3138 // exponent, significand meaningless
3139 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003140 } else if (myexponent==0x7ff && mysignificand==0) {
3141 // exponent, significand meaningless
3142 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003143 } else if (myexponent==0x7ff && mysignificand!=0) {
3144 // exponent meaningless
3145 category = fcNaN;
3146 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003147 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003148 category = fcNormal;
3149 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003150 *significandParts() = mysignificand;
3151 if (myexponent==0) // denormal
3152 exponent = -1022;
3153 else
3154 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003155 }
Dale Johannesena719a602007-08-24 00:56:33 +00003156}
3157
Tim Shen85de51d2016-10-25 19:55:59 +00003158void IEEEFloat::initFromFloatAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003159 assert(api.getBitWidth()==32);
3160 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003161 uint32_t myexponent = (i >> 23) & 0xff;
3162 uint32_t mysignificand = i & 0x7fffff;
3163
Tim Shen85de51d2016-10-25 19:55:59 +00003164 initialize(&IEEEFloat::IEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003165 assert(partCount()==1);
3166
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003167 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003168 if (myexponent==0 && mysignificand==0) {
3169 // exponent, significand meaningless
3170 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003171 } else if (myexponent==0xff && mysignificand==0) {
3172 // exponent, significand meaningless
3173 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003174 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003175 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003176 category = fcNaN;
3177 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003178 } else {
3179 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003180 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003181 *significandParts() = mysignificand;
3182 if (myexponent==0) // denormal
3183 exponent = -126;
3184 else
3185 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003186 }
3187}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003188
Tim Shen85de51d2016-10-25 19:55:59 +00003189void IEEEFloat::initFromHalfAPInt(const APInt &api) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003190 assert(api.getBitWidth()==16);
3191 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003192 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003193 uint32_t mysignificand = i & 0x3ff;
3194
Tim Shen85de51d2016-10-25 19:55:59 +00003195 initialize(&IEEEFloat::IEEEhalf);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003196 assert(partCount()==1);
3197
3198 sign = i >> 15;
3199 if (myexponent==0 && mysignificand==0) {
3200 // exponent, significand meaningless
3201 category = fcZero;
3202 } else if (myexponent==0x1f && mysignificand==0) {
3203 // exponent, significand meaningless
3204 category = fcInfinity;
3205 } else if (myexponent==0x1f && mysignificand!=0) {
3206 // sign, exponent, significand meaningless
3207 category = fcNaN;
3208 *significandParts() = mysignificand;
3209 } else {
3210 category = fcNormal;
3211 exponent = myexponent - 15; //bias
3212 *significandParts() = mysignificand;
3213 if (myexponent==0) // denormal
3214 exponent = -14;
3215 else
3216 *significandParts() |= 0x400; // integer bit
3217 }
3218}
3219
Dale Johannesen245dceb2007-09-11 18:32:33 +00003220/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003221/// we infer the floating point type from the size of the APInt. The
3222/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3223/// when the size is anything else).
Tim Shen85de51d2016-10-25 19:55:59 +00003224void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
Tim Northover29178a32013-01-22 09:46:31 +00003225 if (Sem == &IEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003226 return initFromHalfAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003227 if (Sem == &IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003228 return initFromFloatAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003229 if (Sem == &IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003230 return initFromDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003231 if (Sem == &x87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003232 return initFromF80LongDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003233 if (Sem == &IEEEquad)
3234 return initFromQuadrupleAPInt(api);
Tim Shen139a58f2016-10-27 22:52:40 +00003235 if (Sem == &PPCDoubleDoubleImpl)
Tim Northover29178a32013-01-22 09:46:31 +00003236 return initFromPPCDoubleDoubleAPInt(api);
3237
Craig Topper2617dcc2014-04-15 06:32:26 +00003238 llvm_unreachable(nullptr);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003239}
3240
Tim Shen139a58f2016-10-27 22:52:40 +00003241IEEEFloat IEEEFloat::getAllOnesValue(unsigned BitWidth) {
Tim Northover29178a32013-01-22 09:46:31 +00003242 switch (BitWidth) {
3243 case 16:
Tim Shen85de51d2016-10-25 19:55:59 +00003244 return IEEEFloat(IEEEhalf, APInt::getAllOnesValue(BitWidth));
Tim Northover29178a32013-01-22 09:46:31 +00003245 case 32:
Tim Shen85de51d2016-10-25 19:55:59 +00003246 return IEEEFloat(IEEEsingle, APInt::getAllOnesValue(BitWidth));
Tim Northover29178a32013-01-22 09:46:31 +00003247 case 64:
Tim Shen85de51d2016-10-25 19:55:59 +00003248 return IEEEFloat(IEEEdouble, APInt::getAllOnesValue(BitWidth));
Tim Northover29178a32013-01-22 09:46:31 +00003249 case 80:
Tim Shen85de51d2016-10-25 19:55:59 +00003250 return IEEEFloat(x87DoubleExtended, APInt::getAllOnesValue(BitWidth));
Tim Northover29178a32013-01-22 09:46:31 +00003251 case 128:
Tim Shen139a58f2016-10-27 22:52:40 +00003252 return IEEEFloat(IEEEquad, APInt::getAllOnesValue(BitWidth));
Tim Northover29178a32013-01-22 09:46:31 +00003253 default:
3254 llvm_unreachable("Unknown floating bit width");
3255 }
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003256}
3257
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003258/// Make this number the largest magnitude normal number in the given
3259/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003260void IEEEFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003261 // We want (in interchange format):
3262 // sign = {Negative}
3263 // exponent = 1..10
3264 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003265 category = fcNormal;
3266 sign = Negative;
3267 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003268
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003269 // Use memset to set all but the highest integerPart to all ones.
3270 integerPart *significand = significandParts();
3271 unsigned PartCount = partCount();
3272 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003273
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003274 // Set the high integerPart especially setting all unused top bits for
3275 // internal consistency.
3276 const unsigned NumUnusedHighBits =
3277 PartCount*integerPartWidth - semantics->precision;
Alexey Samsonovba1ecbc2014-09-06 00:41:19 +00003278 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3279 ? (~integerPart(0) >> NumUnusedHighBits)
3280 : 0;
John McCall29b5c282009-12-24 08:56:26 +00003281}
3282
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003283/// Make this number the smallest magnitude denormal number in the given
3284/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003285void IEEEFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003286 // We want (in interchange format):
3287 // sign = {Negative}
3288 // exponent = 0..0
3289 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003290 category = fcNormal;
3291 sign = Negative;
3292 exponent = semantics->minExponent;
3293 APInt::tcSet(significandParts(), 1, partCount());
3294}
John McCall29b5c282009-12-24 08:56:26 +00003295
Tim Shen139a58f2016-10-27 22:52:40 +00003296void IEEEFloat::makeSmallestNormalized(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003297 // We want (in interchange format):
3298 // sign = {Negative}
3299 // exponent = 0..0
3300 // significand = 10..0
3301
Tim Shen139a58f2016-10-27 22:52:40 +00003302 category = fcNormal;
3303 zeroSignificand();
3304 sign = Negative;
3305 exponent = semantics->minExponent;
3306 significandParts()[partCountForBits(semantics->precision) - 1] |=
3307 (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003308}
3309
Tim Shen85de51d2016-10-25 19:55:59 +00003310IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
Tim Northover29178a32013-01-22 09:46:31 +00003311 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003312}
3313
Tim Shen85de51d2016-10-25 19:55:59 +00003314IEEEFloat::IEEEFloat(float f) {
Tim Northover29178a32013-01-22 09:46:31 +00003315 initFromAPInt(&IEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003316}
3317
Tim Shen85de51d2016-10-25 19:55:59 +00003318IEEEFloat::IEEEFloat(double d) {
Tim Northover29178a32013-01-22 09:46:31 +00003319 initFromAPInt(&IEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003320}
John McCall29b5c282009-12-24 08:56:26 +00003321
3322namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003323 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3324 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003325 }
3326
John McCalle6212ace2009-12-24 12:16:56 +00003327 /// Removes data from the given significand until it is no more
3328 /// precise than is required for the desired precision.
3329 void AdjustToPrecision(APInt &significand,
3330 int &exp, unsigned FormatPrecision) {
3331 unsigned bits = significand.getActiveBits();
3332
3333 // 196/59 is a very slight overestimate of lg_2(10).
3334 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3335
3336 if (bits <= bitsRequired) return;
3337
3338 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3339 if (!tensRemovable) return;
3340
3341 exp += tensRemovable;
3342
3343 APInt divisor(significand.getBitWidth(), 1);
3344 APInt powten(significand.getBitWidth(), 10);
3345 while (true) {
3346 if (tensRemovable & 1)
3347 divisor *= powten;
3348 tensRemovable >>= 1;
3349 if (!tensRemovable) break;
3350 powten *= powten;
3351 }
3352
3353 significand = significand.udiv(divisor);
3354
Hao Liube99cc32013-03-20 01:46:36 +00003355 // Truncate the significand down to its active bit count.
3356 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003357 }
3358
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003359
John McCall29b5c282009-12-24 08:56:26 +00003360 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3361 int &exp, unsigned FormatPrecision) {
3362 unsigned N = buffer.size();
3363 if (N <= FormatPrecision) return;
3364
3365 // The most significant figures are the last ones in the buffer.
3366 unsigned FirstSignificant = N - FormatPrecision;
3367
3368 // Round.
3369 // FIXME: this probably shouldn't use 'round half up'.
3370
3371 // Rounding down is just a truncation, except we also want to drop
3372 // trailing zeros from the new result.
3373 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003374 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003375 FirstSignificant++;
3376
3377 exp += FirstSignificant;
3378 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3379 return;
3380 }
3381
3382 // Rounding up requires a decimal add-with-carry. If we continue
3383 // the carry, the newly-introduced zeros will just be truncated.
3384 for (unsigned I = FirstSignificant; I != N; ++I) {
3385 if (buffer[I] == '9') {
3386 FirstSignificant++;
3387 } else {
3388 buffer[I]++;
3389 break;
3390 }
3391 }
3392
3393 // If we carried through, we have exactly one digit of precision.
3394 if (FirstSignificant == N) {
3395 exp += FirstSignificant;
3396 buffer.clear();
3397 buffer.push_back('1');
3398 return;
3399 }
3400
3401 exp += FirstSignificant;
3402 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3403 }
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003404}
John McCall29b5c282009-12-24 08:56:26 +00003405
Tim Shen85de51d2016-10-25 19:55:59 +00003406void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
3407 unsigned FormatMaxPadding) const {
John McCall29b5c282009-12-24 08:56:26 +00003408 switch (category) {
3409 case fcInfinity:
3410 if (isNegative())
3411 return append(Str, "-Inf");
3412 else
3413 return append(Str, "+Inf");
3414
3415 case fcNaN: return append(Str, "NaN");
3416
3417 case fcZero:
3418 if (isNegative())
3419 Str.push_back('-');
3420
3421 if (!FormatMaxPadding)
3422 append(Str, "0.0E+0");
3423 else
3424 Str.push_back('0');
3425 return;
3426
3427 case fcNormal:
3428 break;
3429 }
3430
3431 if (isNegative())
3432 Str.push_back('-');
3433
3434 // Decompose the number into an APInt and an exponent.
3435 int exp = exponent - ((int) semantics->precision - 1);
3436 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003437 makeArrayRef(significandParts(),
3438 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003439
John McCalldd5044a2009-12-24 23:18:09 +00003440 // Set FormatPrecision if zero. We want to do this before we
3441 // truncate trailing zeros, as those are part of the precision.
3442 if (!FormatPrecision) {
Eli Friedmane72f1322013-08-29 23:44:34 +00003443 // We use enough digits so the number can be round-tripped back to an
3444 // APFloat. The formula comes from "How to Print Floating-Point Numbers
3445 // Accurately" by Steele and White.
3446 // FIXME: Using a formula based purely on the precision is conservative;
3447 // we can print fewer digits depending on the actual value being printed.
John McCalldd5044a2009-12-24 23:18:09 +00003448
Eli Friedmane72f1322013-08-29 23:44:34 +00003449 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3450 FormatPrecision = 2 + semantics->precision * 59 / 196;
John McCalldd5044a2009-12-24 23:18:09 +00003451 }
3452
John McCall29b5c282009-12-24 08:56:26 +00003453 // Ignore trailing binary zeros.
3454 int trailingZeros = significand.countTrailingZeros();
3455 exp += trailingZeros;
3456 significand = significand.lshr(trailingZeros);
3457
3458 // Change the exponent from 2^e to 10^e.
3459 if (exp == 0) {
3460 // Nothing to do.
3461 } else if (exp > 0) {
3462 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003463 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003464 significand <<= exp;
3465 exp = 0;
3466 } else { /* exp < 0 */
3467 int texp = -exp;
3468
3469 // We transform this using the identity:
3470 // (N)(2^-e) == (N)(5^e)(10^-e)
3471 // This means we have to multiply N (the significand) by 5^e.
3472 // To avoid overflow, we have to operate on numbers large
3473 // enough to store N * 5^e:
3474 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003475 // <= semantics->precision + e * 137 / 59
3476 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003477
Eli Friedman19546412011-10-07 23:40:49 +00003478 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003479
3480 // Multiply significand by 5^e.
3481 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003482 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003483 APInt five_to_the_i(precision, 5);
3484 while (true) {
3485 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003486
John McCall29b5c282009-12-24 08:56:26 +00003487 texp >>= 1;
3488 if (!texp) break;
3489 five_to_the_i *= five_to_the_i;
3490 }
3491 }
3492
John McCalle6212ace2009-12-24 12:16:56 +00003493 AdjustToPrecision(significand, exp, FormatPrecision);
3494
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003495 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003496
3497 // Fill the buffer.
3498 unsigned precision = significand.getBitWidth();
3499 APInt ten(precision, 10);
3500 APInt digit(precision, 0);
3501
3502 bool inTrail = true;
3503 while (significand != 0) {
3504 // digit <- significand % 10
3505 // significand <- significand / 10
3506 APInt::udivrem(significand, ten, significand, digit);
3507
3508 unsigned d = digit.getZExtValue();
3509
3510 // Drop trailing zeros.
3511 if (inTrail && !d) exp++;
3512 else {
3513 buffer.push_back((char) ('0' + d));
3514 inTrail = false;
3515 }
3516 }
3517
3518 assert(!buffer.empty() && "no characters in buffer!");
3519
3520 // Drop down to FormatPrecision.
3521 // TODO: don't do more precise calculations above than are required.
3522 AdjustToPrecision(buffer, exp, FormatPrecision);
3523
3524 unsigned NDigits = buffer.size();
3525
John McCalldd5044a2009-12-24 23:18:09 +00003526 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003527 bool FormatScientific;
3528 if (!FormatMaxPadding)
3529 FormatScientific = true;
3530 else {
John McCall29b5c282009-12-24 08:56:26 +00003531 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003532 // 765e3 --> 765000
3533 // ^^^
3534 // But we shouldn't make the number look more precise than it is.
3535 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3536 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003537 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003538 // Power of the most significant digit.
3539 int MSD = exp + (int) (NDigits - 1);
3540 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003541 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003542 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003543 } else {
3544 // 765e-5 == 0.00765
3545 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003546 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003547 }
3548 }
John McCall29b5c282009-12-24 08:56:26 +00003549 }
3550
3551 // Scientific formatting is pretty straightforward.
3552 if (FormatScientific) {
3553 exp += (NDigits - 1);
3554
3555 Str.push_back(buffer[NDigits-1]);
3556 Str.push_back('.');
3557 if (NDigits == 1)
3558 Str.push_back('0');
3559 else
3560 for (unsigned I = 1; I != NDigits; ++I)
3561 Str.push_back(buffer[NDigits-1-I]);
3562 Str.push_back('E');
3563
3564 Str.push_back(exp >= 0 ? '+' : '-');
3565 if (exp < 0) exp = -exp;
3566 SmallVector<char, 6> expbuf;
3567 do {
3568 expbuf.push_back((char) ('0' + (exp % 10)));
3569 exp /= 10;
3570 } while (exp);
3571 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3572 Str.push_back(expbuf[E-1-I]);
3573 return;
3574 }
3575
3576 // Non-scientific, positive exponents.
3577 if (exp >= 0) {
3578 for (unsigned I = 0; I != NDigits; ++I)
3579 Str.push_back(buffer[NDigits-1-I]);
3580 for (unsigned I = 0; I != (unsigned) exp; ++I)
3581 Str.push_back('0');
3582 return;
3583 }
3584
3585 // Non-scientific, negative exponents.
3586
3587 // The number of digits to the left of the decimal point.
3588 int NWholeDigits = exp + (int) NDigits;
3589
3590 unsigned I = 0;
3591 if (NWholeDigits > 0) {
3592 for (; I != (unsigned) NWholeDigits; ++I)
3593 Str.push_back(buffer[NDigits-I-1]);
3594 Str.push_back('.');
3595 } else {
3596 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3597
3598 Str.push_back('0');
3599 Str.push_back('.');
3600 for (unsigned Z = 1; Z != NZeros; ++Z)
3601 Str.push_back('0');
3602 }
3603
3604 for (; I != NDigits; ++I)
3605 Str.push_back(buffer[NDigits-I-1]);
3606}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003607
Tim Shen85de51d2016-10-25 19:55:59 +00003608bool IEEEFloat::getExactInverse(IEEEFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003609 // Special floats and denormals have no exact inverse.
Michael Gottesman8136c382013-06-26 23:17:28 +00003610 if (!isFiniteNonZero())
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003611 return false;
3612
3613 // Check that the number is a power of two by making sure that only the
3614 // integer bit is set in the significand.
3615 if (significandLSB() != semantics->precision - 1)
3616 return false;
3617
3618 // Get the inverse.
Tim Shen85de51d2016-10-25 19:55:59 +00003619 IEEEFloat reciprocal(*semantics, 1ULL);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003620 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3621 return false;
3622
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003623 // Avoid multiplication with a denormal, it is not safe on all platforms and
3624 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003625 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003626 return false;
3627
Michael Gottesman8136c382013-06-26 23:17:28 +00003628 assert(reciprocal.isFiniteNonZero() &&
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003629 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3630
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003631 if (inv)
3632 *inv = reciprocal;
3633
3634 return true;
3635}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003636
Tim Shen85de51d2016-10-25 19:55:59 +00003637bool IEEEFloat::isSignaling() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003638 if (!isNaN())
3639 return false;
3640
3641 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3642 // first bit of the trailing significand being 0.
3643 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3644}
3645
3646/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3647///
3648/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3649/// appropriate sign switching before/after the computation.
Tim Shen85de51d2016-10-25 19:55:59 +00003650IEEEFloat::opStatus IEEEFloat::next(bool nextDown) {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003651 // If we are performing nextDown, swap sign so we have -x.
3652 if (nextDown)
3653 changeSign();
3654
3655 // Compute nextUp(x)
3656 opStatus result = opOK;
3657
3658 // Handle each float category separately.
3659 switch (category) {
3660 case fcInfinity:
3661 // nextUp(+inf) = +inf
3662 if (!isNegative())
3663 break;
3664 // nextUp(-inf) = -getLargest()
3665 makeLargest(true);
3666 break;
3667 case fcNaN:
3668 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3669 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3670 // change the payload.
3671 if (isSignaling()) {
3672 result = opInvalidOp;
Alp Tokercb402912014-01-24 17:20:08 +00003673 // For consistency, propagate the sign of the sNaN to the qNaN.
Craig Topperc10719f2014-04-07 04:17:22 +00003674 makeNaN(false, isNegative(), nullptr);
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003675 }
3676 break;
3677 case fcZero:
3678 // nextUp(pm 0) = +getSmallest()
3679 makeSmallest(false);
3680 break;
3681 case fcNormal:
3682 // nextUp(-getSmallest()) = -0
3683 if (isSmallest() && isNegative()) {
3684 APInt::tcSet(significandParts(), 0, partCount());
3685 category = fcZero;
3686 exponent = 0;
3687 break;
3688 }
3689
3690 // nextUp(getLargest()) == INFINITY
3691 if (isLargest() && !isNegative()) {
3692 APInt::tcSet(significandParts(), 0, partCount());
3693 category = fcInfinity;
3694 exponent = semantics->maxExponent + 1;
3695 break;
3696 }
3697
3698 // nextUp(normal) == normal + inc.
3699 if (isNegative()) {
3700 // If we are negative, we need to decrement the significand.
3701
3702 // We only cross a binade boundary that requires adjusting the exponent
3703 // if:
3704 // 1. exponent != semantics->minExponent. This implies we are not in the
3705 // smallest binade or are dealing with denormals.
3706 // 2. Our significand excluding the integral bit is all zeros.
3707 bool WillCrossBinadeBoundary =
3708 exponent != semantics->minExponent && isSignificandAllZeros();
3709
3710 // Decrement the significand.
3711 //
3712 // We always do this since:
Alp Tokerf907b892013-12-05 05:44:44 +00003713 // 1. If we are dealing with a non-binade decrement, by definition we
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003714 // just decrement the significand.
3715 // 2. If we are dealing with a normal -> normal binade decrement, since
3716 // we have an explicit integral bit the fact that all bits but the
3717 // integral bit are zero implies that subtracting one will yield a
3718 // significand with 0 integral bit and 1 in all other spots. Thus we
3719 // must just adjust the exponent and set the integral bit to 1.
3720 // 3. If we are dealing with a normal -> denormal binade decrement,
3721 // since we set the integral bit to 0 when we represent denormals, we
3722 // just decrement the significand.
3723 integerPart *Parts = significandParts();
3724 APInt::tcDecrement(Parts, partCount());
3725
3726 if (WillCrossBinadeBoundary) {
3727 // Our result is a normal number. Do the following:
3728 // 1. Set the integral bit to 1.
3729 // 2. Decrement the exponent.
3730 APInt::tcSetBit(Parts, semantics->precision - 1);
3731 exponent--;
3732 }
3733 } else {
3734 // If we are positive, we need to increment the significand.
3735
3736 // We only cross a binade boundary that requires adjusting the exponent if
3737 // the input is not a denormal and all of said input's significand bits
3738 // are set. If all of said conditions are true: clear the significand, set
3739 // the integral bit to 1, and increment the exponent. If we have a
3740 // denormal always increment since moving denormals and the numbers in the
3741 // smallest normal binade have the same exponent in our representation.
3742 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3743
3744 if (WillCrossBinadeBoundary) {
3745 integerPart *Parts = significandParts();
3746 APInt::tcSet(Parts, 0, partCount());
3747 APInt::tcSetBit(Parts, semantics->precision - 1);
3748 assert(exponent != semantics->maxExponent &&
3749 "We can not increment an exponent beyond the maxExponent allowed"
3750 " by the given floating point semantics.");
3751 exponent++;
3752 } else {
3753 incrementSignificand();
3754 }
3755 }
3756 break;
3757 }
3758
3759 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3760 if (nextDown)
3761 changeSign();
3762
3763 return result;
3764}
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003765
Tim Shen85de51d2016-10-25 19:55:59 +00003766void IEEEFloat::makeInf(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003767 category = fcInfinity;
3768 sign = Negative;
3769 exponent = semantics->maxExponent + 1;
3770 APInt::tcSet(significandParts(), 0, partCount());
3771}
3772
Tim Shen85de51d2016-10-25 19:55:59 +00003773void IEEEFloat::makeZero(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003774 category = fcZero;
3775 sign = Negative;
3776 exponent = semantics->minExponent-1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003777 APInt::tcSet(significandParts(), 0, partCount());
3778}
3779
Tim Shen85de51d2016-10-25 19:55:59 +00003780void IEEEFloat::makeQuiet() {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003781 assert(isNaN());
3782 APInt::tcSetBit(significandParts(), semantics->precision - 2);
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003783}
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003784
Tim Shen85de51d2016-10-25 19:55:59 +00003785int ilogb(const IEEEFloat &Arg) {
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003786 if (Arg.isNaN())
Tim Shen85de51d2016-10-25 19:55:59 +00003787 return IEEEFloat::IEK_NaN;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003788 if (Arg.isZero())
Tim Shen85de51d2016-10-25 19:55:59 +00003789 return IEEEFloat::IEK_Zero;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003790 if (Arg.isInfinity())
Tim Shen85de51d2016-10-25 19:55:59 +00003791 return IEEEFloat::IEK_Inf;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003792 if (!Arg.isDenormal())
3793 return Arg.exponent;
3794
Tim Shen85de51d2016-10-25 19:55:59 +00003795 IEEEFloat Normalized(Arg);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003796 int SignificandBits = Arg.getSemantics().precision - 1;
3797
3798 Normalized.exponent += SignificandBits;
Tim Shen85de51d2016-10-25 19:55:59 +00003799 Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003800 return Normalized.exponent - SignificandBits;
3801}
3802
Tim Shen85de51d2016-10-25 19:55:59 +00003803IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) {
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003804 auto MaxExp = X.getSemantics().maxExponent;
3805 auto MinExp = X.getSemantics().minExponent;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003806
Matt Arsenaultafa31cf2016-03-13 05:11:51 +00003807 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
3808 // overflow; clamp it to a safe range before adding, but ensure that the range
3809 // is large enough that the clamp does not change the result. The range we
3810 // need to support is the difference between the largest possible exponent and
3811 // the normalized exponent of half the smallest denormal.
3812
3813 int SignificandBits = X.getSemantics().precision - 1;
3814 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
3815
3816 // Clamp to one past the range ends to let normalize handle overlflow.
3817 X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement);
3818 X.normalize(RoundingMode, lfExactlyZero);
Matt Arsenaultea00b492016-03-23 23:51:45 +00003819 if (X.isNaN())
3820 X.makeQuiet();
Richard Trieu6ae37962015-04-30 23:07:00 +00003821 return X;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003822}
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003823
Tim Shen85de51d2016-10-25 19:55:59 +00003824IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003825 Exp = ilogb(Val);
3826
3827 // Quiet signalling nans.
Tim Shen85de51d2016-10-25 19:55:59 +00003828 if (Exp == IEEEFloat::IEK_NaN) {
3829 IEEEFloat Quiet(Val);
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003830 Quiet.makeQuiet();
3831 return Quiet;
3832 }
3833
Tim Shen85de51d2016-10-25 19:55:59 +00003834 if (Exp == IEEEFloat::IEK_Inf)
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003835 return Val;
3836
3837 // 1 is added because frexp is defined to return a normalized fraction in
3838 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
Tim Shen85de51d2016-10-25 19:55:59 +00003839 Exp = Exp == IEEEFloat::IEK_Zero ? 0 : Exp + 1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003840 return scalbn(Val, -Exp, RM);
3841}
Tim Shen85de51d2016-10-25 19:55:59 +00003842
Tim Shen139a58f2016-10-27 22:52:40 +00003843DoubleAPFloat::DoubleAPFloat(const fltSemantics &S)
3844 : Semantics(&S), Floats(new APFloat[2]{APFloat(PPCDoubleDoubleImpl),
3845 APFloat(IEEEdouble)}) {
3846 assert(Semantics == &PPCDoubleDouble);
3847}
3848
3849DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag)
3850 : Semantics(&S),
3851 Floats(new APFloat[2]{APFloat(PPCDoubleDoubleImpl, uninitialized),
3852 APFloat(IEEEdouble, uninitialized)}) {
3853 assert(Semantics == &PPCDoubleDouble);
3854}
3855
3856DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I)
3857 : Semantics(&S), Floats(new APFloat[2]{APFloat(PPCDoubleDoubleImpl, I),
3858 APFloat(IEEEdouble)}) {
3859 assert(Semantics == &PPCDoubleDouble);
3860}
3861
3862DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I)
3863 : Semantics(&S), Floats(new APFloat[2]{APFloat(PPCDoubleDoubleImpl, I),
3864 APFloat(IEEEdouble)}) {
3865 assert(Semantics == &PPCDoubleDouble);
3866}
3867
3868DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First,
3869 APFloat &&Second)
3870 : Semantics(&S),
3871 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
3872 assert(Semantics == &PPCDoubleDouble);
3873 // TODO Check for First == &IEEEdouble once the transition is done.
3874 assert(&Floats[0].getSemantics() == &PPCDoubleDoubleImpl);
3875 assert(&Floats[1].getSemantics() == &IEEEdouble);
3876}
3877
3878DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS)
3879 : Semantics(RHS.Semantics),
Tim Shenb49915482016-10-28 22:45:33 +00003880 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
3881 APFloat(RHS.Floats[1])}
3882 : nullptr) {
Tim Shen139a58f2016-10-27 22:52:40 +00003883 assert(Semantics == &PPCDoubleDouble);
3884}
3885
3886DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS)
3887 : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) {
3888 RHS.Semantics = &Bogus;
3889 assert(Semantics == &PPCDoubleDouble);
3890}
3891
3892DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) {
Tim Shenb49915482016-10-28 22:45:33 +00003893 if (Semantics == RHS.Semantics && RHS.Floats) {
Tim Shen139a58f2016-10-27 22:52:40 +00003894 Floats[0] = RHS.Floats[0];
3895 Floats[1] = RHS.Floats[1];
3896 } else if (this != &RHS) {
3897 this->~DoubleAPFloat();
3898 new (this) DoubleAPFloat(RHS);
3899 }
3900 return *this;
3901}
3902
Tim Shen85de51d2016-10-25 19:55:59 +00003903} // End detail namespace
3904
3905APFloat::opStatus APFloat::convertFromString(StringRef Str, roundingMode RM) {
Tim Shen139a58f2016-10-27 22:52:40 +00003906 return getIEEE().convertFromString(Str, RM);
Tim Shen85de51d2016-10-25 19:55:59 +00003907}
3908
Tim Shen139a58f2016-10-27 22:52:40 +00003909hash_code hash_value(const APFloat &Arg) { return hash_value(Arg.getIEEE()); }
Tim Shen85de51d2016-10-25 19:55:59 +00003910
3911APFloat::APFloat(const fltSemantics &Semantics, StringRef S)
Tim Shen139a58f2016-10-27 22:52:40 +00003912 : APFloat(Semantics) {
3913 convertFromString(S, rmNearestTiesToEven);
3914}
3915
3916APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics,
3917 roundingMode RM, bool *losesInfo) {
3918 if (&getSemantics() == &ToSemantics)
3919 return opOK;
3920 if (usesLayout<IEEEFloat>(getSemantics()) &&
3921 usesLayout<IEEEFloat>(ToSemantics)) {
3922 return U.IEEE.convert(ToSemantics, RM, losesInfo);
3923 } else if (usesLayout<IEEEFloat>(getSemantics()) &&
3924 usesLayout<DoubleAPFloat>(ToSemantics)) {
3925 assert(&ToSemantics == &PPCDoubleDouble);
3926 auto Ret = U.IEEE.convert(PPCDoubleDoubleImpl, RM, losesInfo);
3927 *this = APFloat(
3928 DoubleAPFloat(PPCDoubleDouble, std::move(*this), APFloat(IEEEdouble)));
3929 return Ret;
3930 } else if (usesLayout<DoubleAPFloat>(getSemantics()) &&
3931 usesLayout<IEEEFloat>(ToSemantics)) {
3932 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
3933 *this = APFloat(std::move(getIEEE()));
3934 return Ret;
3935 } else {
3936 llvm_unreachable("Unexpected semantics");
3937 }
3938}
Tim Shen85de51d2016-10-25 19:55:59 +00003939
3940} // End llvm namespace