blob: 904e9bf90ce89775a1461c10b005eb124f6088f3 [file] [log] [blame]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision floating
11// point values and provide a variety of arithmetic operations on them.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnere5256752007-12-08 19:00:03 +000015#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +000016#include "llvm/ADT/APSInt.h"
Mehdi Amini47b292d2016-04-16 07:51:28 +000017#include "llvm/ADT/ArrayRef.h"
Ted Kremenek6f30a072008-02-11 17:24:50 +000018#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000019#include "llvm/ADT/Hashing.h"
Jordan Rosee1f76582013-01-18 21:45:30 +000020#include "llvm/ADT/StringExtras.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000021#include "llvm/ADT/StringRef.h"
Tim Shen44bde892016-12-12 21:59:30 +000022#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000023#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000024#include "llvm/Support/MathExtras.h"
Tim Shen44bde892016-12-12 21:59:30 +000025#include "llvm/Support/raw_ostream.h"
Chris Lattner17f71652008-08-17 07:19:36 +000026#include <cstring>
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000027#include <limits.h>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000028
Tim Shen601ba8c2017-01-27 02:11:07 +000029#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
30 do { \
31 if (usesLayout<IEEEFloat>(getSemantics())) \
32 return U.IEEE.METHOD_CALL; \
33 if (usesLayout<DoubleAPFloat>(getSemantics())) \
34 return U.Double.METHOD_CALL; \
35 llvm_unreachable("Unexpected semantics"); \
36 } while (false)
37
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000038using namespace llvm;
39
Michael Gottesman9b877e12013-06-24 09:57:57 +000040/// A macro used to combine two fcCategory enums into one key which can be used
41/// in a switch statement to classify how the interaction of two APFloat's
42/// categories affects an operation.
43///
44/// TODO: If clang source code is ever allowed to use constexpr in its own
45/// codebase, change this into a static inline function.
46#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000047
Neil Booth8f1946f2007-10-03 22:26:02 +000048/* Assumed in hexadecimal significand parsing, and conversion to
49 hexadecimal strings. */
Benjamin Kramer7000ca32014-10-12 17:56:40 +000050static_assert(integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000051
52namespace llvm {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000053 /* Represents floating point arithmetic semantics. */
54 struct fltSemantics {
55 /* The largest E such that 2^E is representable; this matches the
56 definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000057 APFloatBase::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000058
59 /* The smallest E such that 2^E is a normalized number; this
60 matches the definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000061 APFloatBase::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000062
63 /* Number of bits in the significand. This includes the integer
64 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000065 unsigned int precision;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000066
67 /* Number of bits actually used in the semantics. */
68 unsigned int sizeInBits;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000069 };
70
Stephan Bergmann17c7f702016-12-14 11:57:17 +000071 static const fltSemantics semIEEEhalf = {15, -14, 11, 16};
72 static const fltSemantics semIEEEsingle = {127, -126, 24, 32};
73 static const fltSemantics semIEEEdouble = {1023, -1022, 53, 64};
74 static const fltSemantics semIEEEquad = {16383, -16382, 113, 128};
75 static const fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80};
76 static const fltSemantics semBogus = {0, 0, 0, 0};
Dale Johannesen007aa372007-10-11 18:07:22 +000077
Tim Shen7117e692017-01-26 00:11:07 +000078 /* The IBM double-double semantics. Such a number consists of a pair of IEEE
79 64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal,
80 (double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo.
81 Therefore it has two 53-bit mantissa parts that aren't necessarily adjacent
82 to each other, and two 11-bit exponents.
Michal Gorny21c12042017-01-03 16:33:50 +000083
84 Note: we need to make the value different from semBogus as otherwise
85 an unsafe optimization may collapse both values to a single address,
86 and we heavily rely on them having distinct addresses. */
87 static const fltSemantics semPPCDoubleDouble = {-1, 0, 0, 0};
Tim Shen139a58f2016-10-27 22:52:40 +000088
Tim Shenfd1e5aa2017-01-23 22:39:35 +000089 /* These are legacy semantics for the fallback, inaccrurate implementation of
90 IBM double-double, if the accurate semPPCDoubleDouble doesn't handle the
Tim Shen7117e692017-01-26 00:11:07 +000091 operation. It's equivalent to having an IEEE number with consecutive 106
92 bits of mantissa and 11 bits of exponent.
93
94 It's not equivalent to IBM double-double. For example, a legit IBM
95 double-double, 1 + epsilon:
96
97 1 + epsilon = 1 + (1 >> 1076)
98
99 is not representable by a consecutive 106 bits of mantissa.
Tim Shen139a58f2016-10-27 22:52:40 +0000100
Tim Shenfd1e5aa2017-01-23 22:39:35 +0000101 Currently, these semantics are used in the following way:
102
Tim Shen7117e692017-01-26 00:11:07 +0000103 semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) ->
104 (64-bit APInt, 64-bit APInt) -> (128-bit APInt) ->
105 semPPCDoubleDoubleLegacy -> IEEE operations
Tim Shenfd1e5aa2017-01-23 22:39:35 +0000106
107 We use bitcastToAPInt() to get the bit representation (in APInt) of the
108 underlying IEEEdouble, then use the APInt constructor to construct the
109 legacy IEEE float.
110
111 TODO: Implement all operations in semPPCDoubleDouble, and delete these
112 semantics. */
113 static const fltSemantics semPPCDoubleDoubleLegacy = {1023, -1022 + 53,
114 53 + 53, 128};
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000115
116 const fltSemantics &APFloatBase::IEEEhalf() {
117 return semIEEEhalf;
118 }
119 const fltSemantics &APFloatBase::IEEEsingle() {
120 return semIEEEsingle;
121 }
122 const fltSemantics &APFloatBase::IEEEdouble() {
123 return semIEEEdouble;
124 }
125 const fltSemantics &APFloatBase::IEEEquad() {
126 return semIEEEquad;
127 }
128 const fltSemantics &APFloatBase::x87DoubleExtended() {
129 return semX87DoubleExtended;
130 }
131 const fltSemantics &APFloatBase::Bogus() {
132 return semBogus;
133 }
134 const fltSemantics &APFloatBase::PPCDoubleDouble() {
135 return semPPCDoubleDouble;
136 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000137
138 /* A tight upper bound on number of parts required to hold the value
139 pow(5, power) is
140
Neil Booth91305512007-10-15 15:00:55 +0000141 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000142
Neil Boothb93d90e2007-10-12 16:02:31 +0000143 However, whilst the result may require only this many parts,
144 because we are multiplying two values to get it, the
145 multiplication may require an extra part with the excess part
146 being zero (consider the trivial case of 1 * 1, tcFullMultiply
147 requires two parts to hold the single-part result). So we add an
148 extra one to guarantee enough space whilst multiplying. */
149 const unsigned int maxExponent = 16383;
150 const unsigned int maxPrecision = 113;
151 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth91305512007-10-15 15:00:55 +0000152 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
153 / (351 * integerPartWidth));
Tim Shen85de51d2016-10-25 19:55:59 +0000154
155 unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
156 return semantics.precision;
157 }
158 APFloatBase::ExponentType
159 APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) {
160 return semantics.maxExponent;
161 }
162 APFloatBase::ExponentType
163 APFloatBase::semanticsMinExponent(const fltSemantics &semantics) {
164 return semantics.minExponent;
165 }
166 unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
167 return semantics.sizeInBits;
168 }
169
170 unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) {
171 return Sem.sizeInBits;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000172}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000173
Chris Lattner91702092009-03-12 23:59:55 +0000174/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000175
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000176static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000177partCountForBits(unsigned int bits)
178{
179 return ((bits) + integerPartWidth - 1) / integerPartWidth;
180}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000181
Chris Lattner91702092009-03-12 23:59:55 +0000182/* Returns 0U-9U. Return values >= 10U are not digits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000183static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000184decDigitValue(unsigned int c)
185{
186 return c - '0';
187}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000188
Chris Lattner91702092009-03-12 23:59:55 +0000189/* Return the value of a decimal exponent of the form
190 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000191
Chris Lattner91702092009-03-12 23:59:55 +0000192 If the exponent overflows, returns a large exponent with the
193 appropriate sign. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000194static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000195readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000196{
197 bool isNegative;
198 unsigned int absExponent;
199 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000200 StringRef::iterator p = begin;
201
202 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000203
Chris Lattner91702092009-03-12 23:59:55 +0000204 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000205 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000206 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000207 assert(p != end && "Exponent has no digits");
208 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000209
Chris Lattner91702092009-03-12 23:59:55 +0000210 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000211 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000212
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000213 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000214 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000215
Chris Lattner91702092009-03-12 23:59:55 +0000216 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000217 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000218
Chris Lattner91702092009-03-12 23:59:55 +0000219 value += absExponent * 10;
220 if (absExponent >= overlargeExponent) {
221 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000222 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000223 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000224 }
Chris Lattner91702092009-03-12 23:59:55 +0000225 absExponent = value;
226 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000227
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000228 assert(p == end && "Invalid exponent in exponent");
229
Chris Lattner91702092009-03-12 23:59:55 +0000230 if (isNegative)
231 return -(int) absExponent;
232 else
233 return (int) absExponent;
234}
235
236/* This is ugly and needs cleaning up, but I don't immediately see
237 how whilst remaining safe. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000238static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000239totalExponent(StringRef::iterator p, StringRef::iterator end,
240 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000241{
242 int unsignedExponent;
243 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000244 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000245
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000246 assert(p != end && "Exponent has no digits");
247
Chris Lattner91702092009-03-12 23:59:55 +0000248 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000249 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000250 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000251 assert(p != end && "Exponent has no digits");
252 }
Chris Lattner91702092009-03-12 23:59:55 +0000253
254 unsignedExponent = 0;
255 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000256 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000257 unsigned int value;
258
259 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000260 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000261
Chris Lattner91702092009-03-12 23:59:55 +0000262 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000263 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000264 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000265 break;
266 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000267 }
268
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000269 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000270 overflow = true;
271
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000272 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000273 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000274 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000275 exponent = -exponent;
276 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000277 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000278 overflow = true;
279 }
280
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000281 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000282 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000283
284 return exponent;
285}
286
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000287static StringRef::iterator
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000288skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
289 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000290{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000291 StringRef::iterator p = begin;
292 *dot = end;
Nick Lewycky095b92e2014-09-06 01:16:42 +0000293 while (p != end && *p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000294 p++;
295
Nick Lewycky095b92e2014-09-06 01:16:42 +0000296 if (p != end && *p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000297 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000298
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000299 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000300
Nick Lewycky095b92e2014-09-06 01:16:42 +0000301 while (p != end && *p == '0')
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000302 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000303 }
304
Chris Lattner91702092009-03-12 23:59:55 +0000305 return p;
306}
Neil Booth4ed401b2007-10-14 10:16:12 +0000307
Chris Lattner91702092009-03-12 23:59:55 +0000308/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000309
Chris Lattner91702092009-03-12 23:59:55 +0000310 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000311
Chris Lattner91702092009-03-12 23:59:55 +0000312 where the decimal point and exponent are optional, fill out the
313 structure D. Exponent is appropriate if the significand is
314 treated as an integer, and normalizedExponent if the significand
315 is taken to have the decimal point after a single leading
316 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000317
Chris Lattner91702092009-03-12 23:59:55 +0000318 If the value is zero, V->firstSigDigit points to a non-digit, and
319 the return exponent is zero.
320*/
321struct decimalInfo {
322 const char *firstSigDigit;
323 const char *lastSigDigit;
324 int exponent;
325 int normalizedExponent;
326};
Neil Booth4ed401b2007-10-14 10:16:12 +0000327
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000328static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000329interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
330 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000331{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000332 StringRef::iterator dot = end;
333 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000334
Chris Lattner91702092009-03-12 23:59:55 +0000335 D->firstSigDigit = p;
336 D->exponent = 0;
337 D->normalizedExponent = 0;
338
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000339 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000340 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000341 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000342 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000343 if (p == end)
344 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000345 }
Chris Lattner91702092009-03-12 23:59:55 +0000346 if (decDigitValue(*p) >= 10U)
347 break;
Chris Lattner91702092009-03-12 23:59:55 +0000348 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000349
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000350 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000351 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
352 assert(p != begin && "Significand has no digits");
353 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000354
355 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000356 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000357
Chris Lattner91702092009-03-12 23:59:55 +0000358 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000359 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000360 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000361 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000362
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000363 /* If number is all zeroes accept any exponent. */
364 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000365 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000366 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000367 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000368 do
369 p--;
370 while (p != begin && *p == '0');
371 while (p != begin && *p == '.');
372 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000373
Chris Lattner91702092009-03-12 23:59:55 +0000374 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000375 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000376 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000377 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000378 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000379 }
380
Chris Lattner91702092009-03-12 23:59:55 +0000381 D->lastSigDigit = p;
382}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000383
Chris Lattner91702092009-03-12 23:59:55 +0000384/* Return the trailing fraction of a hexadecimal number.
385 DIGITVALUE is the first hex digit of the fraction, P points to
386 the next digit. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000387static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000388trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
389 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000390{
391 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000392
Chris Lattner91702092009-03-12 23:59:55 +0000393 /* If the first trailing digit isn't 0 or 8 we can work out the
394 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000395 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000396 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000397 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000398 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000399
Eli Friedmand2eb07a2013-07-17 22:17:29 +0000400 // Otherwise we need to find the first non-zero digit.
401 while (p != end && (*p == '0' || *p == '.'))
Chris Lattner91702092009-03-12 23:59:55 +0000402 p++;
403
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000404 assert(p != end && "Invalid trailing hexadecimal fraction!");
405
Chris Lattner91702092009-03-12 23:59:55 +0000406 hexDigit = hexDigitValue(*p);
407
408 /* If we ran off the end it is exactly zero or one-half, otherwise
409 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000410 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000411 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
412 else
413 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
414}
415
416/* Return the fraction lost were a bignum truncated losing the least
417 significant BITS bits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000418static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000419lostFractionThroughTruncation(const integerPart *parts,
420 unsigned int partCount,
421 unsigned int bits)
422{
423 unsigned int lsb;
424
425 lsb = APInt::tcLSB(parts, partCount);
426
427 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000428 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000429 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000430 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000431 return lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000432 if (bits <= partCount * integerPartWidth &&
433 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000434 return lfMoreThanHalf;
435
436 return lfLessThanHalf;
437}
438
439/* Shift DST right BITS bits noting lost fraction. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000440static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000441shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
442{
443 lostFraction lost_fraction;
444
445 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
446
447 APInt::tcShiftRight(dst, parts, bits);
448
449 return lost_fraction;
450}
451
452/* Combine the effect of two lost fractions. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000453static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000454combineLostFractions(lostFraction moreSignificant,
455 lostFraction lessSignificant)
456{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000457 if (lessSignificant != lfExactlyZero) {
458 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000459 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000460 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000461 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000462 }
463
Chris Lattner91702092009-03-12 23:59:55 +0000464 return moreSignificant;
465}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000466
Chris Lattner91702092009-03-12 23:59:55 +0000467/* The error from the true value, in half-ulps, on multiplying two
468 floating point numbers, which differ from the value they
469 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
470 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000471
Chris Lattner91702092009-03-12 23:59:55 +0000472 See "How to Read Floating Point Numbers Accurately" by William D
473 Clinger. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000474static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000475HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
476{
477 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000478
Chris Lattner91702092009-03-12 23:59:55 +0000479 if (HUerr1 + HUerr2 == 0)
480 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
481 else
482 return inexactMultiply + 2 * (HUerr1 + HUerr2);
483}
Neil Booth8f1946f2007-10-03 22:26:02 +0000484
Chris Lattner91702092009-03-12 23:59:55 +0000485/* The number of ulps from the boundary (zero, or half if ISNEAREST)
486 when the least significant BITS are truncated. BITS cannot be
487 zero. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000488static integerPart
Chris Lattner91702092009-03-12 23:59:55 +0000489ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
490{
491 unsigned int count, partBits;
492 integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000493
Evan Cheng67c90212009-10-27 21:35:42 +0000494 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000495
Chris Lattner91702092009-03-12 23:59:55 +0000496 bits--;
497 count = bits / integerPartWidth;
498 partBits = bits % integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000499
Chris Lattner91702092009-03-12 23:59:55 +0000500 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000501
Chris Lattner91702092009-03-12 23:59:55 +0000502 if (isNearest)
503 boundary = (integerPart) 1 << (partBits - 1);
504 else
505 boundary = 0;
506
507 if (count == 0) {
508 if (part - boundary <= boundary - part)
509 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000510 else
Chris Lattner91702092009-03-12 23:59:55 +0000511 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000512 }
513
Chris Lattner91702092009-03-12 23:59:55 +0000514 if (part == boundary) {
515 while (--count)
516 if (parts[count])
517 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000518
Chris Lattner91702092009-03-12 23:59:55 +0000519 return parts[0];
520 } else if (part == boundary - 1) {
521 while (--count)
522 if (~parts[count])
523 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000524
Chris Lattner91702092009-03-12 23:59:55 +0000525 return -parts[0];
526 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000527
Chris Lattner91702092009-03-12 23:59:55 +0000528 return ~(integerPart) 0; /* A lot. */
529}
Neil Boothb93d90e2007-10-12 16:02:31 +0000530
Chris Lattner91702092009-03-12 23:59:55 +0000531/* Place pow(5, power) in DST, and return the number of parts used.
532 DST must be at least one part larger than size of the answer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000533static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000534powerOf5(integerPart *dst, unsigned int power)
535{
536 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
537 15625, 78125 };
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000538 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
539 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000540
Chris Lattner0bf18692009-03-13 00:03:51 +0000541 unsigned int partsCount[16] = { 1 };
Chris Lattner91702092009-03-12 23:59:55 +0000542 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
543 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000544 assert(power <= maxExponent);
545
546 p1 = dst;
547 p2 = scratch;
548
549 *p1 = firstEightPowers[power & 7];
550 power >>= 3;
551
552 result = 1;
553 pow5 = pow5s;
554
555 for (unsigned int n = 0; power; power >>= 1, n++) {
556 unsigned int pc;
557
558 pc = partsCount[n];
559
560 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
561 if (pc == 0) {
562 pc = partsCount[n - 1];
563 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
564 pc *= 2;
565 if (pow5[pc - 1] == 0)
566 pc--;
567 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000568 }
569
Chris Lattner91702092009-03-12 23:59:55 +0000570 if (power & 1) {
571 integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000572
Chris Lattner91702092009-03-12 23:59:55 +0000573 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
574 result += pc;
575 if (p2[result - 1] == 0)
576 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000577
Chris Lattner91702092009-03-12 23:59:55 +0000578 /* Now result is in p1 with partsCount parts and p2 is scratch
579 space. */
Richard Trieu7a083812016-02-18 22:09:30 +0000580 tmp = p1;
581 p1 = p2;
582 p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000583 }
584
Chris Lattner91702092009-03-12 23:59:55 +0000585 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000586 }
587
Chris Lattner91702092009-03-12 23:59:55 +0000588 if (p1 != dst)
589 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000590
Chris Lattner91702092009-03-12 23:59:55 +0000591 return result;
592}
Neil Boothb93d90e2007-10-12 16:02:31 +0000593
Chris Lattner91702092009-03-12 23:59:55 +0000594/* Zero at the end to avoid modular arithmetic when adding one; used
595 when rounding up during hexadecimal output. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000596static const char hexDigitsLower[] = "0123456789abcdef0";
597static const char hexDigitsUpper[] = "0123456789ABCDEF0";
598static const char infinityL[] = "infinity";
599static const char infinityU[] = "INFINITY";
600static const char NaNL[] = "nan";
601static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000602
Chris Lattner91702092009-03-12 23:59:55 +0000603/* Write out an integerPart in hexadecimal, starting with the most
604 significant nibble. Write out exactly COUNT hexdigits, return
605 COUNT. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000606static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000607partAsHex (char *dst, integerPart part, unsigned int count,
608 const char *hexDigitChars)
609{
610 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000611
Evan Cheng67c90212009-10-27 21:35:42 +0000612 assert(count != 0 && count <= integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000613
Chris Lattner91702092009-03-12 23:59:55 +0000614 part >>= (integerPartWidth - 4 * count);
615 while (count--) {
616 dst[count] = hexDigitChars[part & 0xf];
617 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000618 }
619
Chris Lattner91702092009-03-12 23:59:55 +0000620 return result;
621}
Neil Booth8f1946f2007-10-03 22:26:02 +0000622
Chris Lattner91702092009-03-12 23:59:55 +0000623/* Write out an unsigned decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000624static char *
Chris Lattner91702092009-03-12 23:59:55 +0000625writeUnsignedDecimal (char *dst, unsigned int n)
626{
627 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000628
Chris Lattner91702092009-03-12 23:59:55 +0000629 p = buff;
630 do
631 *p++ = '0' + n % 10;
632 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000633
Chris Lattner91702092009-03-12 23:59:55 +0000634 do
635 *dst++ = *--p;
636 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000637
Chris Lattner91702092009-03-12 23:59:55 +0000638 return dst;
639}
Neil Booth8f1946f2007-10-03 22:26:02 +0000640
Chris Lattner91702092009-03-12 23:59:55 +0000641/* Write out a signed decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000642static char *
Chris Lattner91702092009-03-12 23:59:55 +0000643writeSignedDecimal (char *dst, int value)
644{
645 if (value < 0) {
646 *dst++ = '-';
647 dst = writeUnsignedDecimal(dst, -(unsigned) value);
648 } else
649 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000650
Chris Lattner91702092009-03-12 23:59:55 +0000651 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000652}
653
Tim Shen85de51d2016-10-25 19:55:59 +0000654namespace detail {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000655/* Constructors. */
Tim Shen85de51d2016-10-25 19:55:59 +0000656void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000657 unsigned int count;
658
659 semantics = ourSemantics;
660 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000661 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000662 significand.parts = new integerPart[count];
663}
664
Tim Shen85de51d2016-10-25 19:55:59 +0000665void IEEEFloat::freeSignificand() {
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000666 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000667 delete [] significand.parts;
668}
669
Tim Shen85de51d2016-10-25 19:55:59 +0000670void IEEEFloat::assign(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000671 assert(semantics == rhs.semantics);
672
673 sign = rhs.sign;
674 category = rhs.category;
675 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000676 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000677 copySignificand(rhs);
678}
679
Tim Shen85de51d2016-10-25 19:55:59 +0000680void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
Michael Gottesman8136c382013-06-26 23:17:28 +0000681 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000682 assert(rhs.partCount() >= partCount());
683
684 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000685 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000686}
687
Neil Booth5fe658b2007-10-14 10:39:51 +0000688/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000689 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000690 which may not be ideal. If float, this is QNaN(0). */
Tim Shen85de51d2016-10-25 19:55:59 +0000691void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
Neil Booth5fe658b2007-10-14 10:39:51 +0000692 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000693 sign = Negative;
694
John McCallc12b1332010-02-28 12:49:50 +0000695 integerPart *significand = significandParts();
696 unsigned numParts = partCount();
697
John McCalldcb9a7a2010-02-28 02:51:25 +0000698 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000699 if (!fill || fill->getNumWords() < numParts)
700 APInt::tcSet(significand, 0, numParts);
701 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000702 APInt::tcAssign(significand, fill->getRawData(),
703 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000704
705 // Zero out the excess bits of the significand.
706 unsigned bitsToPreserve = semantics->precision - 1;
707 unsigned part = bitsToPreserve / 64;
708 bitsToPreserve %= 64;
709 significand[part] &= ((1ULL << bitsToPreserve) - 1);
710 for (part++; part != numParts; ++part)
711 significand[part] = 0;
712 }
713
714 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000715
716 if (SNaN) {
717 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000718 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000719
720 // If there are no bits set in the payload, we have to set
721 // *something* to make it a NaN instead of an infinity;
722 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000723 if (APInt::tcIsZero(significand, numParts))
724 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000725 } else {
726 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000727 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000728 }
John McCallc12b1332010-02-28 12:49:50 +0000729
730 // For x87 extended precision, we want to make a NaN, not a
731 // pseudo-NaN. Maybe we should expose the ability to make
732 // pseudo-NaNs?
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000733 if (semantics == &semX87DoubleExtended)
John McCallc12b1332010-02-28 12:49:50 +0000734 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000735}
736
Tim Shen85de51d2016-10-25 19:55:59 +0000737IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000738 if (this != &rhs) {
739 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000740 freeSignificand();
741 initialize(rhs.semantics);
742 }
743 assign(rhs);
744 }
745
746 return *this;
747}
748
Tim Shen85de51d2016-10-25 19:55:59 +0000749IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000750 freeSignificand();
751
752 semantics = rhs.semantics;
753 significand = rhs.significand;
754 exponent = rhs.exponent;
755 category = rhs.category;
756 sign = rhs.sign;
757
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000758 rhs.semantics = &semBogus;
Benjamin Kramer06f47782014-03-04 20:26:51 +0000759 return *this;
760}
761
Tim Shen85de51d2016-10-25 19:55:59 +0000762bool IEEEFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000763 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Simon Pilgrima2849592017-03-20 13:53:59 +0000764 (APInt::tcExtractBit(significandParts(),
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000765 semantics->precision - 1) == 0);
766}
767
Tim Shen85de51d2016-10-25 19:55:59 +0000768bool IEEEFloat::isSmallest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000769 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000770 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000771 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000772 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000773 significandMSB() == 0;
774}
775
Tim Shen85de51d2016-10-25 19:55:59 +0000776bool IEEEFloat::isSignificandAllOnes() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000777 // Test if the significand excluding the integral bit is all ones. This allows
778 // us to test for binade boundaries.
779 const integerPart *Parts = significandParts();
780 const unsigned PartCount = partCount();
781 for (unsigned i = 0; i < PartCount - 1; i++)
782 if (~Parts[i])
783 return false;
784
785 // Set the unused high bits to all ones when we compare.
786 const unsigned NumHighBits =
787 PartCount*integerPartWidth - semantics->precision + 1;
788 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
789 "fill than integerPartWidth");
790 const integerPart HighBitFill =
791 ~integerPart(0) << (integerPartWidth - NumHighBits);
792 if (~(Parts[PartCount - 1] | HighBitFill))
793 return false;
794
795 return true;
796}
797
Tim Shen85de51d2016-10-25 19:55:59 +0000798bool IEEEFloat::isSignificandAllZeros() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000799 // Test if the significand excluding the integral bit is all zeros. This
800 // allows us to test for binade boundaries.
801 const integerPart *Parts = significandParts();
802 const unsigned PartCount = partCount();
803
804 for (unsigned i = 0; i < PartCount - 1; i++)
805 if (Parts[i])
806 return false;
807
808 const unsigned NumHighBits =
809 PartCount*integerPartWidth - semantics->precision + 1;
810 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
811 "clear than integerPartWidth");
812 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
813
814 if (Parts[PartCount - 1] & HighBitMask)
815 return false;
816
817 return true;
818}
819
Tim Shen85de51d2016-10-25 19:55:59 +0000820bool IEEEFloat::isLargest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000821 // The largest number by magnitude in our format will be the floating point
822 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000823 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000824 && isSignificandAllOnes();
825}
826
Tim Shen85de51d2016-10-25 19:55:59 +0000827bool IEEEFloat::isInteger() const {
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000828 // This could be made more efficient; I'm going for obviously correct.
829 if (!isFinite()) return false;
Tim Shen85de51d2016-10-25 19:55:59 +0000830 IEEEFloat truncated = *this;
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000831 truncated.roundToIntegral(rmTowardZero);
832 return compare(truncated) == cmpEqual;
833}
834
Tim Shen85de51d2016-10-25 19:55:59 +0000835bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000836 if (this == &rhs)
837 return true;
838 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000839 category != rhs.category ||
840 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000841 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000842 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000843 return true;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000844
845 if (isFiniteNonZero() && exponent != rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000846 return false;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000847
848 return std::equal(significandParts(), significandParts() + partCount(),
849 rhs.significandParts());
Dale Johannesena719a602007-08-24 00:56:33 +0000850}
851
Tim Shen85de51d2016-10-25 19:55:59 +0000852IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000853 initialize(&ourSemantics);
854 sign = 0;
Michael Gottesman30a90eb2013-07-27 21:49:21 +0000855 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000856 zeroSignificand();
857 exponent = ourSemantics.precision - 1;
858 significandParts()[0] = value;
859 normalize(rmNearestTiesToEven, lfExactlyZero);
860}
861
Tim Shen85de51d2016-10-25 19:55:59 +0000862IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000863 initialize(&ourSemantics);
864 category = fcZero;
865 sign = false;
866}
867
Tim Shenb49915482016-10-28 22:45:33 +0000868// Delegate to the previous constructor, because later copy constructor may
869// actually inspects category, which can't be garbage.
870IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
Tim Shen1bab9cf2016-10-29 00:51:41 +0000871 : IEEEFloat(ourSemantics) {}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000872
Tim Shen85de51d2016-10-25 19:55:59 +0000873IEEEFloat::IEEEFloat(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000874 initialize(rhs.semantics);
875 assign(rhs);
876}
877
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000878IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000879 *this = std::move(rhs);
880}
881
Tim Shen85de51d2016-10-25 19:55:59 +0000882IEEEFloat::~IEEEFloat() { freeSignificand(); }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000883
Tim Shen85de51d2016-10-25 19:55:59 +0000884unsigned int IEEEFloat::partCount() const {
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000885 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000886}
887
Tim Shen85de51d2016-10-25 19:55:59 +0000888const integerPart *IEEEFloat::significandParts() const {
889 return const_cast<IEEEFloat *>(this)->significandParts();
JF Bastiena1d3c242015-08-26 02:32:45 +0000890}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000891
Tim Shen85de51d2016-10-25 19:55:59 +0000892integerPart *IEEEFloat::significandParts() {
Evan Cheng67c90212009-10-27 21:35:42 +0000893 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000894 return significand.parts;
895 else
896 return &significand.part;
897}
898
Tim Shen85de51d2016-10-25 19:55:59 +0000899void IEEEFloat::zeroSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000900 APInt::tcSet(significandParts(), 0, partCount());
901}
902
903/* Increment an fcNormal floating point number's significand. */
Tim Shen85de51d2016-10-25 19:55:59 +0000904void IEEEFloat::incrementSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000905 integerPart carry;
906
907 carry = APInt::tcIncrement(significandParts(), partCount());
908
909 /* Our callers should never cause us to overflow. */
910 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000911 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000912}
913
914/* Add the significand of the RHS. Returns the carry flag. */
Tim Shen85de51d2016-10-25 19:55:59 +0000915integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000916 integerPart *parts;
917
918 parts = significandParts();
919
920 assert(semantics == rhs.semantics);
921 assert(exponent == rhs.exponent);
922
923 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
924}
925
926/* Subtract the significand of the RHS with a borrow flag. Returns
927 the borrow flag. */
Tim Shen85de51d2016-10-25 19:55:59 +0000928integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
929 integerPart borrow) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000930 integerPart *parts;
931
932 parts = significandParts();
933
934 assert(semantics == rhs.semantics);
935 assert(exponent == rhs.exponent);
936
937 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000938 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000939}
940
941/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
942 on to the full-precision result of the multiplication. Returns the
943 lost fraction. */
Tim Shen85de51d2016-10-25 19:55:59 +0000944lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
945 const IEEEFloat *addend) {
Neil Booth9acbf5a2007-09-26 21:33:42 +0000946 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000947 unsigned int partsCount, newPartsCount, precision;
948 integerPart *lhsSignificand;
949 integerPart scratch[4];
950 integerPart *fullSignificand;
951 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000952 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000953
954 assert(semantics == rhs.semantics);
955
956 precision = semantics->precision;
Lang Hames56c0eb22014-11-19 19:15:41 +0000957
958 // Allocate space for twice as many bits as the original significand, plus one
959 // extra bit for the addition to overflow into.
960 newPartsCount = partCountForBits(precision * 2 + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000961
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000962 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000963 fullSignificand = new integerPart[newPartsCount];
964 else
965 fullSignificand = scratch;
966
967 lhsSignificand = significandParts();
968 partsCount = partCount();
969
970 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000971 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000972
973 lost_fraction = lfExactlyZero;
974 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
975 exponent += rhs.exponent;
976
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000977 // Assume the operands involved in the multiplication are single-precision
978 // FP, and the two multiplicants are:
979 // *this = a23 . a22 ... a0 * 2^e1
980 // rhs = b23 . b22 ... b0 * 2^e2
981 // the result of multiplication is:
Lang Hames56c0eb22014-11-19 19:15:41 +0000982 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
Simon Pilgrima2849592017-03-20 13:53:59 +0000983 // Note that there are three significant bits at the left-hand side of the
Lang Hames56c0eb22014-11-19 19:15:41 +0000984 // radix point: two for the multiplication, and an overflow bit for the
985 // addition (that will always be zero at this point). Move the radix point
986 // toward left by two bits, and adjust exponent accordingly.
987 exponent += 2;
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000988
Hal Finkel171c2ec2014-10-14 19:23:07 +0000989 if (addend && addend->isNonZero()) {
Simon Pilgrima2849592017-03-20 13:53:59 +0000990 // The intermediate result of the multiplication has "2 * precision"
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000991 // signicant bit; adjust the addend to be consistent with mul result.
992 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000993 Significand savedSignificand = significand;
994 const fltSemantics *savedSemantics = semantics;
995 fltSemantics extendedSemantics;
996 opStatus status;
997 unsigned int extendedPrecision;
998
Lang Hames56c0eb22014-11-19 19:15:41 +0000999 // Normalize our MSB to one below the top bit to allow for overflow.
1000 extendedPrecision = 2 * precision + 1;
1001 if (omsb != extendedPrecision - 1) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001002 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001003 APInt::tcShiftLeft(fullSignificand, newPartsCount,
Lang Hames56c0eb22014-11-19 19:15:41 +00001004 (extendedPrecision - 1) - omsb);
1005 exponent -= (extendedPrecision - 1) - omsb;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001006 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001007
1008 /* Create new semantics. */
1009 extendedSemantics = *semantics;
1010 extendedSemantics.precision = extendedPrecision;
1011
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001012 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001013 significand.part = fullSignificand[0];
1014 else
1015 significand.parts = fullSignificand;
1016 semantics = &extendedSemantics;
1017
Tim Shen85de51d2016-10-25 19:55:59 +00001018 IEEEFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001019 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001020 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001021 (void)status;
Lang Hames56c0eb22014-11-19 19:15:41 +00001022
1023 // Shift the significand of the addend right by one bit. This guarantees
1024 // that the high bit of the significand is zero (same as fullSignificand),
1025 // so the addition will overflow (if it does overflow at all) into the top bit.
1026 lost_fraction = extendedAddend.shiftSignificandRight(1);
1027 assert(lost_fraction == lfExactlyZero &&
1028 "Lost precision while shifting addend for fused-multiply-add.");
1029
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001030 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1031
1032 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001033 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001034 fullSignificand[0] = significand.part;
1035 significand = savedSignificand;
1036 semantics = savedSemantics;
1037
1038 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1039 }
1040
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001041 // Convert the result having "2 * precision" significant-bits back to the one
Simon Pilgrima2849592017-03-20 13:53:59 +00001042 // having "precision" significant-bits. First, move the radix point from
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001043 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1044 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
Lang Hames56c0eb22014-11-19 19:15:41 +00001045 exponent -= precision + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001046
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001047 // In case MSB resides at the left-hand side of radix point, shift the
1048 // mantissa right by some amount to make sure the MSB reside right before
1049 // the radix point (i.e. "MSB . rest-significant-bits").
1050 //
1051 // Note that the result is not normalized when "omsb < precision". So, the
Tim Shen85de51d2016-10-25 19:55:59 +00001052 // caller needs to call IEEEFloat::normalize() if normalized value is
1053 // expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001054 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001055 unsigned int bits, significantParts;
1056 lostFraction lf;
1057
1058 bits = omsb - precision;
1059 significantParts = partCountForBits(omsb);
1060 lf = shiftRight(fullSignificand, significantParts, bits);
1061 lost_fraction = combineLostFractions(lf, lost_fraction);
1062 exponent += bits;
1063 }
1064
1065 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1066
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001067 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001068 delete [] fullSignificand;
1069
1070 return lost_fraction;
1071}
1072
1073/* Multiply the significands of LHS and RHS to DST. */
Tim Shen85de51d2016-10-25 19:55:59 +00001074lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001075 unsigned int bit, i, partsCount;
1076 const integerPart *rhsSignificand;
1077 integerPart *lhsSignificand, *dividend, *divisor;
1078 integerPart scratch[4];
1079 lostFraction lost_fraction;
1080
1081 assert(semantics == rhs.semantics);
1082
1083 lhsSignificand = significandParts();
1084 rhsSignificand = rhs.significandParts();
1085 partsCount = partCount();
1086
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001087 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001088 dividend = new integerPart[partsCount * 2];
1089 else
1090 dividend = scratch;
1091
1092 divisor = dividend + partsCount;
1093
1094 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001095 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001096 dividend[i] = lhsSignificand[i];
1097 divisor[i] = rhsSignificand[i];
1098 lhsSignificand[i] = 0;
1099 }
1100
1101 exponent -= rhs.exponent;
1102
1103 unsigned int precision = semantics->precision;
1104
1105 /* Normalize the divisor. */
1106 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001107 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001108 exponent += bit;
1109 APInt::tcShiftLeft(divisor, partsCount, bit);
1110 }
1111
1112 /* Normalize the dividend. */
1113 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001114 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001115 exponent -= bit;
1116 APInt::tcShiftLeft(dividend, partsCount, bit);
1117 }
1118
Neil Boothb93d90e2007-10-12 16:02:31 +00001119 /* Ensure the dividend >= divisor initially for the loop below.
1120 Incidentally, this means that the division loop below is
1121 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001122 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001123 exponent--;
1124 APInt::tcShiftLeft(dividend, partsCount, 1);
1125 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1126 }
1127
1128 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001129 for (bit = precision; bit; bit -= 1) {
1130 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001131 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1132 APInt::tcSetBit(lhsSignificand, bit - 1);
1133 }
1134
1135 APInt::tcShiftLeft(dividend, partsCount, 1);
1136 }
1137
1138 /* Figure out the lost fraction. */
1139 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1140
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001141 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001142 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001143 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001144 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001145 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001146 lost_fraction = lfExactlyZero;
1147 else
1148 lost_fraction = lfLessThanHalf;
1149
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001150 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001151 delete [] dividend;
1152
1153 return lost_fraction;
1154}
1155
Tim Shen85de51d2016-10-25 19:55:59 +00001156unsigned int IEEEFloat::significandMSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001157 return APInt::tcMSB(significandParts(), partCount());
1158}
1159
Tim Shen85de51d2016-10-25 19:55:59 +00001160unsigned int IEEEFloat::significandLSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001161 return APInt::tcLSB(significandParts(), partCount());
1162}
1163
1164/* Note that a zero result is NOT normalized to fcZero. */
Tim Shen85de51d2016-10-25 19:55:59 +00001165lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001166 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001167 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001168
1169 exponent += bits;
1170
1171 return shiftRight(significandParts(), partCount(), bits);
1172}
1173
1174/* Shift the significand left BITS bits, subtract BITS from its exponent. */
Tim Shen85de51d2016-10-25 19:55:59 +00001175void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001176 assert(bits < semantics->precision);
1177
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001178 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001179 unsigned int partsCount = partCount();
1180
1181 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1182 exponent -= bits;
1183
1184 assert(!APInt::tcIsZero(significandParts(), partsCount));
1185 }
1186}
1187
Tim Shen85de51d2016-10-25 19:55:59 +00001188IEEEFloat::cmpResult
1189IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001190 int compare;
1191
1192 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001193 assert(isFiniteNonZero());
1194 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001195
1196 compare = exponent - rhs.exponent;
1197
1198 /* If exponents are equal, do an unsigned bignum comparison of the
1199 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001200 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001201 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001202 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001203
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001204 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001205 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001206 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001207 return cmpLessThan;
1208 else
1209 return cmpEqual;
1210}
1211
1212/* Handle overflow. Sign is preserved. We either become infinity or
1213 the largest finite number. */
Tim Shen85de51d2016-10-25 19:55:59 +00001214IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001215 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001216 if (rounding_mode == rmNearestTiesToEven ||
1217 rounding_mode == rmNearestTiesToAway ||
1218 (rounding_mode == rmTowardPositive && !sign) ||
1219 (rounding_mode == rmTowardNegative && sign)) {
1220 category = fcInfinity;
1221 return (opStatus) (opOverflow | opInexact);
1222 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001223
1224 /* Otherwise we become the largest finite number. */
1225 category = fcNormal;
1226 exponent = semantics->maxExponent;
1227 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001228 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001229
1230 return opInexact;
1231}
1232
Neil Booth1ca1f802007-10-03 15:16:41 +00001233/* Returns TRUE if, when truncating the current number, with BIT the
1234 new LSB, with the given lost fraction and rounding mode, the result
1235 would need to be rounded away from zero (i.e., by increasing the
1236 signficand). This routine must work for fcZero of both signs, and
1237 fcNormal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001238bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1239 lostFraction lost_fraction,
1240 unsigned int bit) const {
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001241 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001242 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001243
Neil Booth1ca1f802007-10-03 15:16:41 +00001244 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001245 assert(lost_fraction != lfExactlyZero);
1246
Mike Stump889285d2009-05-13 23:23:20 +00001247 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001248 case rmNearestTiesToAway:
1249 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1250
1251 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001252 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001253 return true;
1254
1255 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001256 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001257 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001258
1259 return false;
1260
1261 case rmTowardZero:
1262 return false;
1263
1264 case rmTowardPositive:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001265 return !sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001266
1267 case rmTowardNegative:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001268 return sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001269 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001270 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001271}
1272
Tim Shen85de51d2016-10-25 19:55:59 +00001273IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1274 lostFraction lost_fraction) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001275 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001276 int exponentChange;
1277
Michael Gottesman8136c382013-06-26 23:17:28 +00001278 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001279 return opOK;
1280
1281 /* Before rounding normalize the exponent of fcNormal numbers. */
1282 omsb = significandMSB() + 1;
1283
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001284 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001285 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001286 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001287 the exponent. */
1288 exponentChange = omsb - semantics->precision;
1289
1290 /* If the resulting exponent is too high, overflow according to
1291 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001292 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001293 return handleOverflow(rounding_mode);
1294
1295 /* Subnormal numbers have exponent minExponent, and their MSB
1296 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001297 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001298 exponentChange = semantics->minExponent - exponent;
1299
1300 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001301 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001302 assert(lost_fraction == lfExactlyZero);
1303
1304 shiftSignificandLeft(-exponentChange);
1305
1306 return opOK;
1307 }
1308
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001309 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001310 lostFraction lf;
1311
1312 /* Shift right and capture any new lost fraction. */
1313 lf = shiftSignificandRight(exponentChange);
1314
1315 lost_fraction = combineLostFractions(lf, lost_fraction);
1316
1317 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001318 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001319 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001320 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001321 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001322 }
1323 }
1324
1325 /* Now round the number according to rounding_mode given the lost
1326 fraction. */
1327
1328 /* As specified in IEEE 754, since we do not trap we do not report
1329 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001330 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001331 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001332 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001333 category = fcZero;
1334
1335 return opOK;
1336 }
1337
1338 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001339 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1340 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001341 exponent = semantics->minExponent;
1342
1343 incrementSignificand();
1344 omsb = significandMSB() + 1;
1345
1346 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001347 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001348 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001349 significand right one. However if we already have the
1350 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001351 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001352 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001353
Neil Booth9acbf5a2007-09-26 21:33:42 +00001354 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001355 }
1356
1357 shiftSignificandRight(1);
1358
1359 return opInexact;
1360 }
1361 }
1362
1363 /* The normal case - we were and are not denormal, and any
1364 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001365 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001366 return opInexact;
1367
1368 /* We have a non-zero denormal. */
1369 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001370
1371 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001372 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001373 category = fcZero;
1374
1375 /* The fcZero case is a denormal that underflowed to zero. */
1376 return (opStatus) (opUnderflow | opInexact);
1377}
1378
Tim Shen85de51d2016-10-25 19:55:59 +00001379IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1380 bool subtract) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001381 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001382 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001383 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001384
Michael Gottesman9b877e12013-06-24 09:57:57 +00001385 case PackCategoriesIntoKey(fcNaN, fcZero):
1386 case PackCategoriesIntoKey(fcNaN, fcNormal):
1387 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1388 case PackCategoriesIntoKey(fcNaN, fcNaN):
1389 case PackCategoriesIntoKey(fcNormal, fcZero):
1390 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1391 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001392 return opOK;
1393
Michael Gottesman9b877e12013-06-24 09:57:57 +00001394 case PackCategoriesIntoKey(fcZero, fcNaN):
1395 case PackCategoriesIntoKey(fcNormal, fcNaN):
1396 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Stephen Canond3278282014-06-08 16:53:31 +00001397 // We need to be sure to flip the sign here for subtraction because we
1398 // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1399 sign = rhs.sign ^ subtract;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001400 category = fcNaN;
1401 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001402 return opOK;
1403
Michael Gottesman9b877e12013-06-24 09:57:57 +00001404 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1405 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001406 category = fcInfinity;
1407 sign = rhs.sign ^ subtract;
1408 return opOK;
1409
Michael Gottesman9b877e12013-06-24 09:57:57 +00001410 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001411 assign(rhs);
1412 sign = rhs.sign ^ subtract;
1413 return opOK;
1414
Michael Gottesman9b877e12013-06-24 09:57:57 +00001415 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001416 /* Sign depends on rounding mode; handled by caller. */
1417 return opOK;
1418
Michael Gottesman9b877e12013-06-24 09:57:57 +00001419 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001420 /* Differently signed infinities can only be validly
1421 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001422 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001423 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001424 return opInvalidOp;
1425 }
1426
1427 return opOK;
1428
Michael Gottesman9b877e12013-06-24 09:57:57 +00001429 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001430 return opDivByZero;
1431 }
1432}
1433
1434/* Add or subtract two normal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001435lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1436 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001437 integerPart carry;
1438 lostFraction lost_fraction;
1439 int bits;
1440
1441 /* Determine if the operation on the absolute values is effectively
1442 an addition or subtraction. */
Aaron Ballmand5cc45f2015-03-24 12:47:51 +00001443 subtract ^= static_cast<bool>(sign ^ rhs.sign);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001444
1445 /* Are we bigger exponent-wise than the RHS? */
1446 bits = exponent - rhs.exponent;
1447
1448 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001449 if (subtract) {
Tim Shen85de51d2016-10-25 19:55:59 +00001450 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001451 bool reverse;
1452
Chris Lattner3da18eb2007-08-24 03:02:34 +00001453 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001454 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1455 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001456 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001457 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1458 shiftSignificandLeft(1);
1459 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001460 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001461 lost_fraction = shiftSignificandRight(-bits - 1);
1462 temp_rhs.shiftSignificandLeft(1);
1463 reverse = true;
1464 }
1465
Chris Lattner3da18eb2007-08-24 03:02:34 +00001466 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001467 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001468 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001469 copySignificand(temp_rhs);
1470 sign = !sign;
1471 } else {
1472 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001473 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001474 }
1475
1476 /* Invert the lost fraction - it was on the RHS and
1477 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001478 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001479 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001480 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001481 lost_fraction = lfLessThanHalf;
1482
1483 /* The code above is intended to ensure that no borrow is
1484 necessary. */
1485 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001486 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001487 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001488 if (bits > 0) {
Tim Shen85de51d2016-10-25 19:55:59 +00001489 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001490
1491 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1492 carry = addSignificand(temp_rhs);
1493 } else {
1494 lost_fraction = shiftSignificandRight(-bits);
1495 carry = addSignificand(rhs);
1496 }
1497
1498 /* We have a guard bit; generating a carry cannot happen. */
1499 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001500 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001501 }
1502
1503 return lost_fraction;
1504}
1505
Tim Shen85de51d2016-10-25 19:55:59 +00001506IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001507 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001508 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001509 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001510
Michael Gottesman9b877e12013-06-24 09:57:57 +00001511 case PackCategoriesIntoKey(fcNaN, fcZero):
1512 case PackCategoriesIntoKey(fcNaN, fcNormal):
1513 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1514 case PackCategoriesIntoKey(fcNaN, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001515 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001516 return opOK;
1517
Michael Gottesman9b877e12013-06-24 09:57:57 +00001518 case PackCategoriesIntoKey(fcZero, fcNaN):
1519 case PackCategoriesIntoKey(fcNormal, fcNaN):
1520 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001521 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001522 category = fcNaN;
1523 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001524 return opOK;
1525
Michael Gottesman9b877e12013-06-24 09:57:57 +00001526 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1527 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1528 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001529 category = fcInfinity;
1530 return opOK;
1531
Michael Gottesman9b877e12013-06-24 09:57:57 +00001532 case PackCategoriesIntoKey(fcZero, fcNormal):
1533 case PackCategoriesIntoKey(fcNormal, fcZero):
1534 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001535 category = fcZero;
1536 return opOK;
1537
Michael Gottesman9b877e12013-06-24 09:57:57 +00001538 case PackCategoriesIntoKey(fcZero, fcInfinity):
1539 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001540 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001541 return opInvalidOp;
1542
Michael Gottesman9b877e12013-06-24 09:57:57 +00001543 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001544 return opOK;
1545 }
1546}
1547
Tim Shen85de51d2016-10-25 19:55:59 +00001548IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001549 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001550 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001551 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001552
Michael Gottesman9b877e12013-06-24 09:57:57 +00001553 case PackCategoriesIntoKey(fcZero, fcNaN):
1554 case PackCategoriesIntoKey(fcNormal, fcNaN):
1555 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001556 category = fcNaN;
1557 copySignificand(rhs);
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001558 case PackCategoriesIntoKey(fcNaN, fcZero):
1559 case PackCategoriesIntoKey(fcNaN, fcNormal):
1560 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1561 case PackCategoriesIntoKey(fcNaN, fcNaN):
1562 sign = false;
1563 case PackCategoriesIntoKey(fcInfinity, fcZero):
1564 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1565 case PackCategoriesIntoKey(fcZero, fcInfinity):
1566 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001567 return opOK;
1568
Michael Gottesman9b877e12013-06-24 09:57:57 +00001569 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001570 category = fcZero;
1571 return opOK;
1572
Michael Gottesman9b877e12013-06-24 09:57:57 +00001573 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001574 category = fcInfinity;
1575 return opDivByZero;
1576
Michael Gottesman9b877e12013-06-24 09:57:57 +00001577 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1578 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001579 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001580 return opInvalidOp;
1581
Michael Gottesman9b877e12013-06-24 09:57:57 +00001582 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001583 return opOK;
1584 }
1585}
1586
Tim Shen85de51d2016-10-25 19:55:59 +00001587IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001588 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001589 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001590 llvm_unreachable(nullptr);
Dale Johannesenb5721632009-01-21 00:35:19 +00001591
Michael Gottesman9b877e12013-06-24 09:57:57 +00001592 case PackCategoriesIntoKey(fcNaN, fcZero):
1593 case PackCategoriesIntoKey(fcNaN, fcNormal):
1594 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1595 case PackCategoriesIntoKey(fcNaN, fcNaN):
1596 case PackCategoriesIntoKey(fcZero, fcInfinity):
1597 case PackCategoriesIntoKey(fcZero, fcNormal):
1598 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001599 return opOK;
1600
Michael Gottesman9b877e12013-06-24 09:57:57 +00001601 case PackCategoriesIntoKey(fcZero, fcNaN):
1602 case PackCategoriesIntoKey(fcNormal, fcNaN):
1603 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001604 sign = false;
Dale Johannesenb5721632009-01-21 00:35:19 +00001605 category = fcNaN;
1606 copySignificand(rhs);
1607 return opOK;
1608
Michael Gottesman9b877e12013-06-24 09:57:57 +00001609 case PackCategoriesIntoKey(fcNormal, fcZero):
1610 case PackCategoriesIntoKey(fcInfinity, fcZero):
1611 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1612 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1613 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001614 makeNaN();
1615 return opInvalidOp;
1616
Michael Gottesman9b877e12013-06-24 09:57:57 +00001617 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001618 return opOK;
1619 }
1620}
1621
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001622/* Change sign. */
Tim Shen85de51d2016-10-25 19:55:59 +00001623void IEEEFloat::changeSign() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001624 /* Look mummy, this one's easy. */
1625 sign = !sign;
1626}
1627
1628/* Normalized addition or subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001629IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
1630 roundingMode rounding_mode,
1631 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001632 opStatus fs;
1633
1634 fs = addOrSubtractSpecials(rhs, subtract);
1635
1636 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001637 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001638 lostFraction lost_fraction;
1639
1640 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1641 fs = normalize(rounding_mode, lost_fraction);
1642
1643 /* Can only be zero if we lost no fraction. */
1644 assert(category != fcZero || lost_fraction == lfExactlyZero);
1645 }
1646
1647 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1648 positive zero unless rounding to minus infinity, except that
1649 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001650 if (category == fcZero) {
1651 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001652 sign = (rounding_mode == rmTowardNegative);
1653 }
1654
1655 return fs;
1656}
1657
1658/* Normalized addition. */
Tim Shen85de51d2016-10-25 19:55:59 +00001659IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs,
1660 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001661 return addOrSubtract(rhs, rounding_mode, false);
1662}
1663
1664/* Normalized subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001665IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs,
1666 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001667 return addOrSubtract(rhs, rounding_mode, true);
1668}
1669
1670/* Normalized multiply. */
Tim Shen85de51d2016-10-25 19:55:59 +00001671IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs,
1672 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001673 opStatus fs;
1674
1675 sign ^= rhs.sign;
1676 fs = multiplySpecials(rhs);
1677
Michael Gottesman8136c382013-06-26 23:17:28 +00001678 if (isFiniteNonZero()) {
Craig Topperc10719f2014-04-07 04:17:22 +00001679 lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001680 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001681 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001682 fs = (opStatus) (fs | opInexact);
1683 }
1684
1685 return fs;
1686}
1687
1688/* Normalized divide. */
Tim Shen85de51d2016-10-25 19:55:59 +00001689IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs,
1690 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001691 opStatus fs;
1692
1693 sign ^= rhs.sign;
1694 fs = divideSpecials(rhs);
1695
Michael Gottesman8136c382013-06-26 23:17:28 +00001696 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001697 lostFraction lost_fraction = divideSignificand(rhs);
1698 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001699 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001700 fs = (opStatus) (fs | opInexact);
1701 }
1702
1703 return fs;
1704}
1705
Dale Johannesenfe750172009-01-20 18:35:05 +00001706/* Normalized remainder. This is not currently correct in all cases. */
Tim Shen85de51d2016-10-25 19:55:59 +00001707IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) {
Dale Johannesenfe750172009-01-20 18:35:05 +00001708 opStatus fs;
Tim Shen85de51d2016-10-25 19:55:59 +00001709 IEEEFloat V = *this;
Dale Johannesenfe750172009-01-20 18:35:05 +00001710 unsigned int origSign = sign;
1711
Dale Johannesenfe750172009-01-20 18:35:05 +00001712 fs = V.divide(rhs, rmNearestTiesToEven);
1713 if (fs == opDivByZero)
1714 return fs;
1715
1716 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001717 integerPart *x = new integerPart[parts];
Dale Johannesenfe750172009-01-20 18:35:05 +00001718 bool ignored;
Simon Pilgrim00b34992017-03-20 14:40:12 +00001719 fs = V.convertToInteger(makeMutableArrayRef(x, parts),
1720 parts * integerPartWidth, true, rmNearestTiesToEven,
1721 &ignored);
1722 if (fs == opInvalidOp) {
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001723 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001724 return fs;
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001725 }
Dale Johannesenfe750172009-01-20 18:35:05 +00001726
1727 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1728 rmNearestTiesToEven);
1729 assert(fs==opOK); // should always work
1730
1731 fs = V.multiply(rhs, rmNearestTiesToEven);
1732 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1733
1734 fs = subtract(V, rmNearestTiesToEven);
1735 assert(fs==opOK || fs==opInexact); // likewise
1736
1737 if (isZero())
1738 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001739 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001740 return fs;
1741}
1742
Stephen Canon157c8692017-03-31 20:31:33 +00001743/* Normalized llvm frem (C fmod). */
Tim Shen85de51d2016-10-25 19:55:59 +00001744IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) {
Dale Johannesen689d17d2007-08-31 23:35:31 +00001745 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001746 fs = modSpecials(rhs);
Dale Johannesen689d17d2007-08-31 23:35:31 +00001747
Stephen Canon157c8692017-03-31 20:31:33 +00001748 while (isFiniteNonZero() && rhs.isFiniteNonZero() &&
1749 compareAbsoluteValue(rhs) != cmpLessThan) {
1750 IEEEFloat V = scalbn(rhs, ilogb(*this) - ilogb(rhs), rmNearestTiesToEven);
1751 if (compareAbsoluteValue(V) == cmpLessThan)
1752 V = scalbn(V, -1, rmNearestTiesToEven);
1753 V.sign = sign;
1754
Stephen Canonb12db0e2015-09-21 19:29:25 +00001755 fs = subtract(V, rmNearestTiesToEven);
Stephen Canon157c8692017-03-31 20:31:33 +00001756 assert(fs==opOK);
Dale Johannesenb5721632009-01-21 00:35:19 +00001757 }
Dale Johannesen689d17d2007-08-31 23:35:31 +00001758 return fs;
1759}
1760
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001761/* Normalized fused-multiply-add. */
Tim Shen85de51d2016-10-25 19:55:59 +00001762IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand,
1763 const IEEEFloat &addend,
1764 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001765 opStatus fs;
1766
1767 /* Post-multiplication sign, before addition. */
1768 sign ^= multiplicand.sign;
1769
1770 /* If and only if all arguments are normal do we need to do an
1771 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001772 if (isFiniteNonZero() &&
1773 multiplicand.isFiniteNonZero() &&
Hal Finkel171c2ec2014-10-14 19:23:07 +00001774 addend.isFinite()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001775 lostFraction lost_fraction;
1776
1777 lost_fraction = multiplySignificand(multiplicand, &addend);
1778 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001779 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001780 fs = (opStatus) (fs | opInexact);
1781
1782 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1783 positive zero unless rounding to minus infinity, except that
1784 adding two like-signed zeroes gives that zero. */
Lang Hames12b12e82015-01-04 01:20:55 +00001785 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001786 sign = (rounding_mode == rmTowardNegative);
1787 } else {
1788 fs = multiplySpecials(multiplicand);
1789
1790 /* FS can only be opOK or opInvalidOp. There is no more work
1791 to do in the latter case. The IEEE-754R standard says it is
1792 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001793 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001794
1795 If we need to do the addition we can do so with normal
1796 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001797 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001798 fs = addOrSubtract(addend, rounding_mode, false);
1799 }
1800
1801 return fs;
1802}
1803
Owen Andersona40319b2012-08-13 23:32:49 +00001804/* Rounding-mode corrrect round to integral value. */
Tim Shen85de51d2016-10-25 19:55:59 +00001805IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) {
Owen Andersona40319b2012-08-13 23:32:49 +00001806 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001807
Owen Anderson352dfff2012-08-15 18:28:45 +00001808 // If the exponent is large enough, we know that this value is already
1809 // integral, and the arithmetic below would potentially cause it to saturate
1810 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001811 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001812 return opOK;
1813
Owen Andersona40319b2012-08-13 23:32:49 +00001814 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1815 // precision of our format, and then subtract it back off again. The choice
1816 // of rounding modes for the addition/subtraction determines the rounding mode
1817 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001818 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001819 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001820 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1821 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Tim Shen85de51d2016-10-25 19:55:59 +00001822 IEEEFloat MagicConstant(*semantics);
Owen Andersona40319b2012-08-13 23:32:49 +00001823 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1824 rmNearestTiesToEven);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00001825 MagicConstant.sign = sign;
Owen Anderson1ff74b02012-08-15 05:39:46 +00001826
Owen Andersona40319b2012-08-13 23:32:49 +00001827 if (fs != opOK)
1828 return fs;
1829
Owen Anderson1ff74b02012-08-15 05:39:46 +00001830 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1831 bool inputSign = isNegative();
1832
Owen Andersona40319b2012-08-13 23:32:49 +00001833 fs = add(MagicConstant, rounding_mode);
1834 if (fs != opOK && fs != opInexact)
1835 return fs;
1836
1837 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001838
1839 // Restore the input sign.
1840 if (inputSign != isNegative())
1841 changeSign();
1842
Owen Andersona40319b2012-08-13 23:32:49 +00001843 return fs;
1844}
1845
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001846
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001847/* Comparison requires normalized numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001848IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001849 cmpResult result;
1850
1851 assert(semantics == rhs.semantics);
1852
Michael Gottesman9b877e12013-06-24 09:57:57 +00001853 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001854 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001855 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001856
Michael Gottesman9b877e12013-06-24 09:57:57 +00001857 case PackCategoriesIntoKey(fcNaN, fcZero):
1858 case PackCategoriesIntoKey(fcNaN, fcNormal):
1859 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1860 case PackCategoriesIntoKey(fcNaN, fcNaN):
1861 case PackCategoriesIntoKey(fcZero, fcNaN):
1862 case PackCategoriesIntoKey(fcNormal, fcNaN):
1863 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001864 return cmpUnordered;
1865
Michael Gottesman9b877e12013-06-24 09:57:57 +00001866 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1867 case PackCategoriesIntoKey(fcInfinity, fcZero):
1868 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001869 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001870 return cmpLessThan;
1871 else
1872 return cmpGreaterThan;
1873
Michael Gottesman9b877e12013-06-24 09:57:57 +00001874 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1875 case PackCategoriesIntoKey(fcZero, fcInfinity):
1876 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001877 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001878 return cmpGreaterThan;
1879 else
1880 return cmpLessThan;
1881
Michael Gottesman9b877e12013-06-24 09:57:57 +00001882 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001883 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001884 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001885 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001886 return cmpLessThan;
1887 else
1888 return cmpGreaterThan;
1889
Michael Gottesman9b877e12013-06-24 09:57:57 +00001890 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001891 return cmpEqual;
1892
Michael Gottesman9b877e12013-06-24 09:57:57 +00001893 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001894 break;
1895 }
1896
1897 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001898 if (sign != rhs.sign) {
1899 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001900 result = cmpLessThan;
1901 else
1902 result = cmpGreaterThan;
1903 } else {
1904 /* Compare absolute values; invert result if negative. */
1905 result = compareAbsoluteValue(rhs);
1906
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001907 if (sign) {
1908 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001909 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001910 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001911 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001912 }
1913 }
1914
1915 return result;
1916}
1917
Tim Shen85de51d2016-10-25 19:55:59 +00001918/// IEEEFloat::convert - convert a value of one floating point type to another.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001919/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1920/// records whether the transformation lost information, i.e. whether
1921/// converting the result back to the original type will produce the
1922/// original value (this is almost the same as return value==fsOK, but there
1923/// are edge cases where this is not so).
1924
Tim Shen85de51d2016-10-25 19:55:59 +00001925IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics,
1926 roundingMode rounding_mode,
1927 bool *losesInfo) {
Neil Bootha8d72692007-09-22 02:56:19 +00001928 lostFraction lostFraction;
1929 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001930 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001931 int shift;
1932 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001933
Neil Bootha8d72692007-09-22 02:56:19 +00001934 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001935 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001936 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001937 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001938
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001939 bool X86SpecialNan = false;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001940 if (&fromSemantics == &semX87DoubleExtended &&
1941 &toSemantics != &semX87DoubleExtended && category == fcNaN &&
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001942 (!(*significandParts() & 0x8000000000000000ULL) ||
1943 !(*significandParts() & 0x4000000000000000ULL))) {
1944 // x86 has some unusual NaNs which cannot be represented in any other
1945 // format; note them here.
1946 X86SpecialNan = true;
1947 }
1948
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00001949 // If this is a truncation of a denormal number, and the target semantics
1950 // has larger exponent range than the source semantics (this can happen
1951 // when truncating from PowerPC double-double to double format), the
1952 // right shift could lose result mantissa bits. Adjust exponent instead
1953 // of performing excessive shift.
1954 if (shift < 0 && isFiniteNonZero()) {
1955 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1956 if (exponent + exponentChange < toSemantics.minExponent)
1957 exponentChange = toSemantics.minExponent - exponent;
1958 if (exponentChange < shift)
1959 exponentChange = shift;
1960 if (exponentChange < 0) {
1961 shift -= exponentChange;
1962 exponent += exponentChange;
1963 }
1964 }
1965
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001966 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00001967 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001968 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1969
1970 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00001971 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001972 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001973 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001974 newParts = new integerPart[newPartCount];
1975 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00001976 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001977 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001978 freeSignificand();
1979 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001980 } else if (newPartCount == 1 && oldPartCount != 1) {
1981 // Switch to built-in storage for a single part.
1982 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00001983 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001984 newPart = significandParts()[0];
1985 freeSignificand();
1986 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001987 }
1988
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001989 // Now that we have the right storage, switch the semantics.
1990 semantics = &toSemantics;
1991
1992 // If this is an extension, perform the shift now that the storage is
1993 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00001994 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001995 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1996
Michael Gottesman8136c382013-06-26 23:17:28 +00001997 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00001998 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001999 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002000 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002001 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002002
2003 // For x87 extended precision, we want to make a NaN, not a special NaN if
2004 // the input wasn't special either.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002005 if (!X86SpecialNan && semantics == &semX87DoubleExtended)
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002006 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2007
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002008 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2009 // does not give you back the same bits. This is dubious, and we
2010 // don't currently do it. You're really supposed to get
2011 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002012 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002013 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002014 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002015 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002016 }
2017
2018 return fs;
2019}
2020
2021/* Convert a floating point number to an integer according to the
2022 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002023 returns an invalid operation exception and the contents of the
2024 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002025 range but the floating point number is not the exact integer, the C
2026 standard doesn't require an inexact exception to be raised. IEEE
2027 854 does require it so we do that.
2028
2029 Note that for conversions to integer type the C standard requires
2030 round-to-zero to always be used. */
Tim Shen85de51d2016-10-25 19:55:59 +00002031IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
Simon Pilgrim00b34992017-03-20 14:40:12 +00002032 MutableArrayRef<integerPart> parts, unsigned int width, bool isSigned,
Tim Shen85de51d2016-10-25 19:55:59 +00002033 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002034 lostFraction lost_fraction;
2035 const integerPart *src;
2036 unsigned int dstPartsCount, truncatedBits;
2037
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002038 *isExact = false;
2039
Neil Booth618d0fc2007-11-01 22:43:37 +00002040 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002041 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002042 return opInvalidOp;
2043
2044 dstPartsCount = partCountForBits(width);
Simon Pilgrim00b34992017-03-20 14:40:12 +00002045 assert(dstPartsCount <= parts.size() && "Integer too big");
Neil Booth618d0fc2007-11-01 22:43:37 +00002046
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002047 if (category == fcZero) {
Simon Pilgrim00b34992017-03-20 14:40:12 +00002048 APInt::tcSet(parts.data(), 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002049 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002050 *isExact = !sign;
2051 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002052 }
2053
2054 src = significandParts();
2055
2056 /* Step 1: place our absolute value, with any fraction truncated, in
2057 the destination. */
2058 if (exponent < 0) {
2059 /* Our absolute value is less than one; truncate everything. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002060 APInt::tcSet(parts.data(), 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002061 /* For exponent -1 the integer bit represents .5, look at that.
2062 For smaller exponents leftmost truncated bit is 0. */
2063 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002064 } else {
2065 /* We want the most significant (exponent + 1) bits; the rest are
2066 truncated. */
2067 unsigned int bits = exponent + 1U;
2068
2069 /* Hopelessly large in magnitude? */
2070 if (bits > width)
2071 return opInvalidOp;
2072
2073 if (bits < semantics->precision) {
2074 /* We truncate (semantics->precision - bits) bits. */
2075 truncatedBits = semantics->precision - bits;
Simon Pilgrim00b34992017-03-20 14:40:12 +00002076 APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits);
Neil Booth618d0fc2007-11-01 22:43:37 +00002077 } else {
2078 /* We want at least as many bits as are available. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002079 APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision,
2080 0);
2081 APInt::tcShiftLeft(parts.data(), dstPartsCount,
2082 bits - semantics->precision);
Neil Booth618d0fc2007-11-01 22:43:37 +00002083 truncatedBits = 0;
2084 }
2085 }
2086
2087 /* Step 2: work out any lost fraction, and increment the absolute
2088 value if we would round away from zero. */
2089 if (truncatedBits) {
2090 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2091 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002092 if (lost_fraction != lfExactlyZero &&
2093 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Simon Pilgrim00b34992017-03-20 14:40:12 +00002094 if (APInt::tcIncrement(parts.data(), dstPartsCount))
Neil Booth618d0fc2007-11-01 22:43:37 +00002095 return opInvalidOp; /* Overflow. */
2096 }
2097 } else {
2098 lost_fraction = lfExactlyZero;
2099 }
2100
2101 /* Step 3: check if we fit in the destination. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002102 unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1;
Neil Booth618d0fc2007-11-01 22:43:37 +00002103
2104 if (sign) {
2105 if (!isSigned) {
2106 /* Negative numbers cannot be represented as unsigned. */
2107 if (omsb != 0)
2108 return opInvalidOp;
2109 } else {
2110 /* It takes omsb bits to represent the unsigned integer value.
2111 We lose a bit for the sign, but care is needed as the
2112 maximally negative integer is a special case. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002113 if (omsb == width &&
2114 APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb)
Neil Booth618d0fc2007-11-01 22:43:37 +00002115 return opInvalidOp;
2116
2117 /* This case can happen because of rounding. */
2118 if (omsb > width)
2119 return opInvalidOp;
2120 }
2121
Simon Pilgrim00b34992017-03-20 14:40:12 +00002122 APInt::tcNegate (parts.data(), dstPartsCount);
Neil Booth618d0fc2007-11-01 22:43:37 +00002123 } else {
2124 if (omsb >= width + !isSigned)
2125 return opInvalidOp;
2126 }
2127
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002128 if (lost_fraction == lfExactlyZero) {
2129 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002130 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002131 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002132 return opInexact;
2133}
2134
2135/* Same as convertToSignExtendedInteger, except we provide
2136 deterministic values in case of an invalid operation exception,
2137 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002138 for underflow or overflow.
2139 The *isExact output tells whether the result is exact, in the sense
2140 that converting it back to the original floating point type produces
2141 the original value. This is almost equivalent to result==opOK,
2142 except for negative zeroes.
2143*/
Simon Pilgrim00b34992017-03-20 14:40:12 +00002144IEEEFloat::opStatus
2145IEEEFloat::convertToInteger(MutableArrayRef<integerPart> parts,
2146 unsigned int width, bool isSigned,
2147 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002148 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002149
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002150 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002151 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002152
Neil Booth618d0fc2007-11-01 22:43:37 +00002153 if (fs == opInvalidOp) {
2154 unsigned int bits, dstPartsCount;
2155
2156 dstPartsCount = partCountForBits(width);
Simon Pilgrim00b34992017-03-20 14:40:12 +00002157 assert(dstPartsCount <= parts.size() && "Integer too big");
Neil Booth618d0fc2007-11-01 22:43:37 +00002158
2159 if (category == fcNaN)
2160 bits = 0;
2161 else if (sign)
2162 bits = isSigned;
2163 else
2164 bits = width - isSigned;
2165
Simon Pilgrim00b34992017-03-20 14:40:12 +00002166 APInt::tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits);
Neil Booth618d0fc2007-11-01 22:43:37 +00002167 if (sign && isSigned)
Simon Pilgrim00b34992017-03-20 14:40:12 +00002168 APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002169 }
2170
Neil Booth618d0fc2007-11-01 22:43:37 +00002171 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002172}
2173
Neil Booth6c1c8582007-10-07 12:07:53 +00002174/* Convert an unsigned integer SRC to a floating point number,
2175 rounding according to ROUNDING_MODE. The sign of the floating
2176 point number is not modified. */
Tim Shen85de51d2016-10-25 19:55:59 +00002177IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2178 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
Neil Booth49c6aab2007-10-08 14:39:42 +00002179 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002180 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002181 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002182
2183 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002184 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002185 dst = significandParts();
2186 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002187 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002188
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002189 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002190 be that many; extract what we can. */
2191 if (precision <= omsb) {
2192 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002193 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002194 omsb - precision);
2195 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2196 } else {
2197 exponent = precision - 1;
2198 lost_fraction = lfExactlyZero;
2199 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002200 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002201
2202 return normalize(rounding_mode, lost_fraction);
2203}
2204
Tim Shen85de51d2016-10-25 19:55:59 +00002205IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned,
2206 roundingMode rounding_mode) {
Dan Gohman35723eb2008-02-29 01:26:11 +00002207 unsigned int partCount = Val.getNumWords();
2208 APInt api = Val;
2209
2210 sign = false;
2211 if (isSigned && api.isNegative()) {
2212 sign = true;
2213 api = -api;
2214 }
2215
2216 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2217}
2218
Neil Booth03f58ab2007-10-07 12:15:41 +00002219/* Convert a two's complement integer SRC to a floating point number,
2220 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2221 integer is signed, in which case it must be sign-extended. */
Tim Shen85de51d2016-10-25 19:55:59 +00002222IEEEFloat::opStatus
2223IEEEFloat::convertFromSignExtendedInteger(const integerPart *src,
2224 unsigned int srcCount, bool isSigned,
2225 roundingMode rounding_mode) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002226 opStatus status;
2227
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002228 if (isSigned &&
2229 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002230 integerPart *copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002231
2232 /* If we're signed and negative negate a copy. */
2233 sign = true;
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002234 copy = new integerPart[srcCount];
Neil Booth03f58ab2007-10-07 12:15:41 +00002235 APInt::tcAssign(copy, src, srcCount);
2236 APInt::tcNegate(copy, srcCount);
2237 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002238 delete [] copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002239 } else {
2240 sign = false;
2241 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2242 }
2243
2244 return status;
2245}
2246
Neil Booth5f009732007-10-07 11:45:55 +00002247/* FIXME: should this just take a const APInt reference? */
Tim Shen85de51d2016-10-25 19:55:59 +00002248IEEEFloat::opStatus
2249IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2250 unsigned int width, bool isSigned,
2251 roundingMode rounding_mode) {
Dale Johannesen42305122007-09-21 22:09:37 +00002252 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002253 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002254
2255 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002256 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002257 sign = true;
2258 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002259 }
2260
Neil Boothba205222007-10-07 12:10:57 +00002261 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002262}
2263
Tim Shen85de51d2016-10-25 19:55:59 +00002264IEEEFloat::opStatus
2265IEEEFloat::convertFromHexadecimalString(StringRef s,
2266 roundingMode rounding_mode) {
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002267 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002268
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002269 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002270 zeroSignificand();
2271 exponent = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002272
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002273 integerPart *significand = significandParts();
2274 unsigned partsCount = partCount();
2275 unsigned bitPos = partsCount * integerPartWidth;
2276 bool computedTrailingFraction = false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002277
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002278 // Skip leading zeroes and any (hexa)decimal point.
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002279 StringRef::iterator begin = s.begin();
2280 StringRef::iterator end = s.end();
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002281 StringRef::iterator dot;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002282 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002283 StringRef::iterator firstSignificantDigit = p;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002284
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002285 while (p != end) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002286 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002287
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002288 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002289 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002290 dot = p++;
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002291 continue;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002292 }
2293
2294 hex_value = hexDigitValue(*p);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002295 if (hex_value == -1U)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002296 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002297
2298 p++;
2299
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002300 // Store the number while we have space.
2301 if (bitPos) {
2302 bitPos -= 4;
2303 hex_value <<= bitPos % integerPartWidth;
2304 significand[bitPos / integerPartWidth] |= hex_value;
2305 } else if (!computedTrailingFraction) {
2306 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2307 computedTrailingFraction = true;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002308 }
2309 }
2310
2311 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002312 assert(p != end && "Hex strings require an exponent");
2313 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2314 assert(p != begin && "Significand has no digits");
2315 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002316
2317 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002318 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002319 int expAdjustment;
2320
2321 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002322 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002323 dot = p;
2324
2325 /* Calculate the exponent adjustment implicit in the number of
2326 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002327 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002328 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002329 expAdjustment++;
2330 expAdjustment = expAdjustment * 4 - 1;
2331
2332 /* Adjust for writing the significand starting at the most
2333 significant nibble. */
2334 expAdjustment += semantics->precision;
2335 expAdjustment -= partsCount * integerPartWidth;
2336
2337 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002338 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002339 }
2340
2341 return normalize(rounding_mode, lost_fraction);
2342}
2343
Tim Shen85de51d2016-10-25 19:55:59 +00002344IEEEFloat::opStatus
2345IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2346 unsigned sigPartCount, int exp,
2347 roundingMode rounding_mode) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002348 unsigned int parts, pow5PartCount;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00002349 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002350 integerPart pow5Parts[maxPowerOfFiveParts];
2351 bool isNearest;
2352
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002353 isNearest = (rounding_mode == rmNearestTiesToEven ||
2354 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002355
2356 parts = partCountForBits(semantics->precision + 11);
2357
2358 /* Calculate pow(5, abs(exp)). */
2359 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2360
2361 for (;; parts *= 2) {
2362 opStatus sigStatus, powStatus;
2363 unsigned int excessPrecision, truncatedBits;
2364
2365 calcSemantics.precision = parts * integerPartWidth - 1;
2366 excessPrecision = calcSemantics.precision - semantics->precision;
2367 truncatedBits = excessPrecision;
2368
Tim Shen139a58f2016-10-27 22:52:40 +00002369 IEEEFloat decSig(calcSemantics, uninitialized);
2370 decSig.makeZero(sign);
Tim Shen85de51d2016-10-25 19:55:59 +00002371 IEEEFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002372
2373 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2374 rmNearestTiesToEven);
2375 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2376 rmNearestTiesToEven);
2377 /* Add exp, as 10^n = 5^n * 2^n. */
2378 decSig.exponent += exp;
2379
2380 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002381 integerPart HUerr, HUdistance;
2382 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002383
2384 if (exp >= 0) {
2385 /* multiplySignificand leaves the precision-th bit set to 1. */
Craig Topperc10719f2014-04-07 04:17:22 +00002386 calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
Neil Boothb93d90e2007-10-12 16:02:31 +00002387 powHUerr = powStatus != opOK;
2388 } else {
2389 calcLostFraction = decSig.divideSignificand(pow5);
2390 /* Denormal numbers have less precision. */
2391 if (decSig.exponent < semantics->minExponent) {
2392 excessPrecision += (semantics->minExponent - decSig.exponent);
2393 truncatedBits = excessPrecision;
2394 if (excessPrecision > calcSemantics.precision)
2395 excessPrecision = calcSemantics.precision;
2396 }
2397 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002398 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002399 }
2400
2401 /* Both multiplySignificand and divideSignificand return the
2402 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002403 assert(APInt::tcExtractBit
2404 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002405
2406 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2407 powHUerr);
2408 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2409 excessPrecision, isNearest);
2410
2411 /* Are we guaranteed to round correctly if we truncate? */
2412 if (HUdistance >= HUerr) {
2413 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2414 calcSemantics.precision - excessPrecision,
2415 excessPrecision);
2416 /* Take the exponent of decSig. If we tcExtract-ed less bits
2417 above we must adjust our exponent to compensate for the
2418 implicit right shift. */
2419 exponent = (decSig.exponent + semantics->precision
2420 - (calcSemantics.precision - excessPrecision));
2421 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2422 decSig.partCount(),
2423 truncatedBits);
2424 return normalize(rounding_mode, calcLostFraction);
2425 }
2426 }
2427}
2428
Tim Shen85de51d2016-10-25 19:55:59 +00002429IEEEFloat::opStatus
2430IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
Neil Booth4ed401b2007-10-14 10:16:12 +00002431 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002432 opStatus fs;
2433
Neil Booth4ed401b2007-10-14 10:16:12 +00002434 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002435 StringRef::iterator p = str.begin();
2436 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002437
Neil Booth91305512007-10-15 15:00:55 +00002438 /* Handle the quick cases. First the case of no significant digits,
2439 i.e. zero, and then exponents that are obviously too large or too
2440 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2441 definitely overflows if
2442
2443 (exp - 1) * L >= maxExponent
2444
2445 and definitely underflows to zero where
2446
2447 (exp + 1) * L <= minExponent - precision
2448
2449 With integer arithmetic the tightest bounds for L are
2450
2451 93/28 < L < 196/59 [ numerator <= 256 ]
2452 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2453 */
2454
Michael Gottesman228156c2013-07-01 23:54:08 +00002455 // Test if we have a zero number allowing for strings with no null terminators
2456 // and zero decimals with non-zero exponents.
Simon Pilgrima2849592017-03-20 13:53:59 +00002457 //
Michael Gottesman228156c2013-07-01 23:54:08 +00002458 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2459 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2460 // be at most one dot. On the other hand, if we have a zero with a non-zero
2461 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002462 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002463 category = fcZero;
2464 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002465
2466 /* Check whether the normalized exponent is high enough to overflow
2467 max during the log-rebasing in the max-exponent check below. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002468 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
John McCallb42cc682010-02-26 22:20:41 +00002469 fs = handleOverflow(rounding_mode);
2470
2471 /* If it wasn't, then it also wasn't high enough to overflow max
2472 during the log-rebasing in the min-exponent check. Check that it
2473 won't overflow min in either check, then perform the min-exponent
2474 check. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002475 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
John McCallb42cc682010-02-26 22:20:41 +00002476 (D.normalizedExponent + 1) * 28738 <=
2477 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002478 /* Underflow to zero and round. */
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002479 category = fcNormal;
Neil Booth91305512007-10-15 15:00:55 +00002480 zeroSignificand();
2481 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002482
2483 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002484 } else if ((D.normalizedExponent - 1) * 42039
2485 >= 12655 * semantics->maxExponent) {
2486 /* Overflow and round. */
2487 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002488 } else {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002489 integerPart *decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002490 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002491
Neil Booth4ed401b2007-10-14 10:16:12 +00002492 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002493 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002494 to hold the full significand, and an extra part required by
2495 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002496 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002497 partCount = partCountForBits(1 + 196 * partCount / 59);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002498 decSignificand = new integerPart[partCount + 1];
Neil Booth4ed401b2007-10-14 10:16:12 +00002499 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002500
Neil Booth4ed401b2007-10-14 10:16:12 +00002501 /* Convert to binary efficiently - we do almost all multiplication
2502 in an integerPart. When this would overflow do we do a single
2503 bignum multiplication, and then revert again to multiplication
2504 in an integerPart. */
2505 do {
2506 integerPart decValue, val, multiplier;
2507
2508 val = 0;
2509 multiplier = 1;
2510
2511 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002512 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002513 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002514 if (p == str.end()) {
2515 break;
2516 }
2517 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002518 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002519 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002520 multiplier *= 10;
2521 val = val * 10 + decValue;
2522 /* The maximum number that can be multiplied by ten with any
2523 digit added without overflowing an integerPart. */
2524 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2525
2526 /* Multiply out the current part. */
2527 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2528 partCount, partCount + 1, false);
2529
2530 /* If we used another part (likely but not guaranteed), increase
2531 the count. */
2532 if (decSignificand[partCount])
2533 partCount++;
2534 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002535
Neil Boothae077d22007-11-01 22:51:07 +00002536 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002537 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002538 D.exponent, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002539
2540 delete [] decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002541 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002542
2543 return fs;
2544}
2545
Tim Shen85de51d2016-10-25 19:55:59 +00002546bool IEEEFloat::convertFromStringSpecials(StringRef str) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002547 if (str.equals("inf") || str.equals("INFINITY")) {
2548 makeInf(false);
2549 return true;
2550 }
2551
2552 if (str.equals("-inf") || str.equals("-INFINITY")) {
2553 makeInf(true);
2554 return true;
2555 }
2556
2557 if (str.equals("nan") || str.equals("NaN")) {
2558 makeNaN(false, false);
2559 return true;
2560 }
2561
2562 if (str.equals("-nan") || str.equals("-NaN")) {
2563 makeNaN(false, true);
2564 return true;
2565 }
2566
2567 return false;
2568}
2569
Tim Shen85de51d2016-10-25 19:55:59 +00002570IEEEFloat::opStatus IEEEFloat::convertFromString(StringRef str,
2571 roundingMode rounding_mode) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002572 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002573
Michael Gottesman40e8a182013-06-24 09:58:05 +00002574 // Handle special cases.
2575 if (convertFromStringSpecials(str))
2576 return opOK;
2577
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002578 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002579 StringRef::iterator p = str.begin();
2580 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002581 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002582 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002583 p++;
2584 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002585 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002586 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002587
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002588 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002589 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002590 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002591 rounding_mode);
2592 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002593
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002594 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002595}
Dale Johannesena719a602007-08-24 00:56:33 +00002596
Neil Booth8f1946f2007-10-03 22:26:02 +00002597/* Write out a hexadecimal representation of the floating point value
2598 to DST, which must be of sufficient size, in the C99 form
2599 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2600 excluding the terminating NUL.
2601
2602 If UPPERCASE, the output is in upper case, otherwise in lower case.
2603
2604 HEXDIGITS digits appear altogether, rounding the value if
2605 necessary. If HEXDIGITS is 0, the minimal precision to display the
2606 number precisely is used instead. If nothing would appear after
2607 the decimal point it is suppressed.
2608
2609 The decimal exponent is always printed and has at least one digit.
2610 Zero values display an exponent of zero. Infinities and NaNs
2611 appear as "infinity" or "nan" respectively.
2612
2613 The above rules are as specified by C99. There is ambiguity about
2614 what the leading hexadecimal digit should be. This implementation
2615 uses whatever is necessary so that the exponent is displayed as
2616 stored. This implies the exponent will fall within the IEEE format
2617 range, and the leading hexadecimal digit will be 0 (for denormals),
2618 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2619 any other digits zero).
2620*/
Tim Shen85de51d2016-10-25 19:55:59 +00002621unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
2622 bool upperCase,
2623 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002624 char *p;
2625
2626 p = dst;
2627 if (sign)
2628 *dst++ = '-';
2629
2630 switch (category) {
2631 case fcInfinity:
2632 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2633 dst += sizeof infinityL - 1;
2634 break;
2635
2636 case fcNaN:
2637 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2638 dst += sizeof NaNU - 1;
2639 break;
2640
2641 case fcZero:
2642 *dst++ = '0';
2643 *dst++ = upperCase ? 'X': 'x';
2644 *dst++ = '0';
2645 if (hexDigits > 1) {
2646 *dst++ = '.';
2647 memset (dst, '0', hexDigits - 1);
2648 dst += hexDigits - 1;
2649 }
2650 *dst++ = upperCase ? 'P': 'p';
2651 *dst++ = '0';
2652 break;
2653
2654 case fcNormal:
2655 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2656 break;
2657 }
2658
2659 *dst = 0;
2660
Evan Cheng82b9e962008-05-02 21:15:08 +00002661 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002662}
2663
2664/* Does the hard work of outputting the correctly rounded hexadecimal
2665 form of a normal floating point number with the specified number of
2666 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2667 digits necessary to print the value precisely is output. */
Tim Shen85de51d2016-10-25 19:55:59 +00002668char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2669 bool upperCase,
2670 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002671 unsigned int count, valueBits, shift, partsCount, outputDigits;
2672 const char *hexDigitChars;
2673 const integerPart *significand;
2674 char *p;
2675 bool roundUp;
2676
2677 *dst++ = '0';
2678 *dst++ = upperCase ? 'X': 'x';
2679
2680 roundUp = false;
2681 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2682
2683 significand = significandParts();
2684 partsCount = partCount();
2685
2686 /* +3 because the first digit only uses the single integer bit, so
2687 we have 3 virtual zero most-significant-bits. */
2688 valueBits = semantics->precision + 3;
2689 shift = integerPartWidth - valueBits % integerPartWidth;
2690
2691 /* The natural number of digits required ignoring trailing
2692 insignificant zeroes. */
2693 outputDigits = (valueBits - significandLSB () + 3) / 4;
2694
2695 /* hexDigits of zero means use the required number for the
2696 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002697 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002698 if (hexDigits) {
2699 if (hexDigits < outputDigits) {
2700 /* We are dropping non-zero bits, so need to check how to round.
2701 "bits" is the number of dropped bits. */
2702 unsigned int bits;
2703 lostFraction fraction;
2704
2705 bits = valueBits - hexDigits * 4;
2706 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2707 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2708 }
2709 outputDigits = hexDigits;
2710 }
2711
2712 /* Write the digits consecutively, and start writing in the location
2713 of the hexadecimal point. We move the most significant digit
2714 left and add the hexadecimal point later. */
2715 p = ++dst;
2716
2717 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2718
2719 while (outputDigits && count) {
2720 integerPart part;
2721
2722 /* Put the most significant integerPartWidth bits in "part". */
2723 if (--count == partsCount)
2724 part = 0; /* An imaginary higher zero part. */
2725 else
2726 part = significand[count] << shift;
2727
2728 if (count && shift)
2729 part |= significand[count - 1] >> (integerPartWidth - shift);
2730
2731 /* Convert as much of "part" to hexdigits as we can. */
2732 unsigned int curDigits = integerPartWidth / 4;
2733
2734 if (curDigits > outputDigits)
2735 curDigits = outputDigits;
2736 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2737 outputDigits -= curDigits;
2738 }
2739
2740 if (roundUp) {
2741 char *q = dst;
2742
2743 /* Note that hexDigitChars has a trailing '0'. */
2744 do {
2745 q--;
2746 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002747 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002748 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002749 } else {
2750 /* Add trailing zeroes. */
2751 memset (dst, '0', outputDigits);
2752 dst += outputDigits;
2753 }
2754
2755 /* Move the most significant digit to before the point, and if there
2756 is something after the decimal point add it. This must come
2757 after rounding above. */
2758 p[-1] = p[0];
2759 if (dst -1 == p)
2760 dst--;
2761 else
2762 p[0] = '.';
2763
2764 /* Finally output the exponent. */
2765 *dst++ = upperCase ? 'P': 'p';
2766
Neil Booth32897f52007-10-06 07:29:25 +00002767 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002768}
2769
Tim Shen85de51d2016-10-25 19:55:59 +00002770hash_code hash_value(const IEEEFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002771 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002772 return hash_combine((uint8_t)Arg.category,
2773 // NaN has no sign, fix it at zero.
2774 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2775 Arg.semantics->precision);
2776
2777 // Normal floats need their exponent and significand hashed.
2778 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2779 Arg.semantics->precision, Arg.exponent,
2780 hash_combine_range(
2781 Arg.significandParts(),
2782 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002783}
2784
2785// Conversion from APFloat to/from host float/double. It may eventually be
2786// possible to eliminate these and have everybody deal with APFloats, but that
2787// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002788// Current implementation requires integerPartWidth==64, which is correct at
2789// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002790
Dale Johannesen728687c2007-09-05 20:39:49 +00002791// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002792// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002793
Tim Shen85de51d2016-10-25 19:55:59 +00002794APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002795 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002796 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002797
2798 uint64_t myexponent, mysignificand;
2799
Michael Gottesman8136c382013-06-26 23:17:28 +00002800 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002801 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002802 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002803 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2804 myexponent = 0; // denormal
2805 } else if (category==fcZero) {
2806 myexponent = 0;
2807 mysignificand = 0;
2808 } else if (category==fcInfinity) {
2809 myexponent = 0x7fff;
2810 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002811 } else {
2812 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002813 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002814 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002815 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002816
2817 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002818 words[0] = mysignificand;
2819 words[1] = ((uint64_t)(sign & 1) << 15) |
2820 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002821 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002822}
2823
Tim Shen85de51d2016-10-25 19:55:59 +00002824APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00002825 assert(semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy);
Evan Cheng67c90212009-10-27 21:35:42 +00002826 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002827
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002828 uint64_t words[2];
2829 opStatus fs;
2830 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002831
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002832 // Convert number to double. To avoid spurious underflows, we re-
2833 // normalize against the "double" minExponent first, and only *then*
2834 // truncate the mantissa. The result of that second conversion
2835 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002836 // Declare fltSemantics before APFloat that uses it (and
2837 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002838 fltSemantics extendedSemantics = *semantics;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002839 extendedSemantics.minExponent = semIEEEdouble.minExponent;
Tim Shen85de51d2016-10-25 19:55:59 +00002840 IEEEFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002841 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2842 assert(fs == opOK && !losesInfo);
2843 (void)fs;
2844
Tim Shen85de51d2016-10-25 19:55:59 +00002845 IEEEFloat u(extended);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002846 fs = u.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002847 assert(fs == opOK || fs == opInexact);
2848 (void)fs;
2849 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2850
2851 // If conversion was exact or resulted in a special case, we're done;
2852 // just set the second double to zero. Otherwise, re-convert back to
2853 // the extended format and compute the difference. This now should
2854 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002855 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002856 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2857 assert(fs == opOK && !losesInfo);
2858 (void)fs;
2859
Tim Shen85de51d2016-10-25 19:55:59 +00002860 IEEEFloat v(extended);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002861 v.subtract(u, rmNearestTiesToEven);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002862 fs = v.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002863 assert(fs == opOK && !losesInfo);
2864 (void)fs;
2865 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002866 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002867 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002868 }
2869
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002870 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002871}
2872
Tim Shen85de51d2016-10-25 19:55:59 +00002873APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002874 assert(semantics == (const llvm::fltSemantics*)&semIEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002875 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002876
2877 uint64_t myexponent, mysignificand, mysignificand2;
2878
Michael Gottesman8136c382013-06-26 23:17:28 +00002879 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002880 myexponent = exponent+16383; //bias
2881 mysignificand = significandParts()[0];
2882 mysignificand2 = significandParts()[1];
2883 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2884 myexponent = 0; // denormal
2885 } else if (category==fcZero) {
2886 myexponent = 0;
2887 mysignificand = mysignificand2 = 0;
2888 } else if (category==fcInfinity) {
2889 myexponent = 0x7fff;
2890 mysignificand = mysignificand2 = 0;
2891 } else {
2892 assert(category == fcNaN && "Unknown category!");
2893 myexponent = 0x7fff;
2894 mysignificand = significandParts()[0];
2895 mysignificand2 = significandParts()[1];
2896 }
2897
2898 uint64_t words[2];
2899 words[0] = mysignificand;
2900 words[1] = ((uint64_t)(sign & 1) << 63) |
2901 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002902 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002903
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002904 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002905}
2906
Tim Shen85de51d2016-10-25 19:55:59 +00002907APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002908 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002909 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002910
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002911 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002912
Michael Gottesman8136c382013-06-26 23:17:28 +00002913 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002914 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002915 mysignificand = *significandParts();
2916 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2917 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002918 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002919 myexponent = 0;
2920 mysignificand = 0;
2921 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002922 myexponent = 0x7ff;
2923 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002924 } else {
2925 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002926 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002927 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002928 }
Dale Johannesena719a602007-08-24 00:56:33 +00002929
Evan Cheng82b9e962008-05-02 21:15:08 +00002930 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002931 ((myexponent & 0x7ff) << 52) |
2932 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002933}
2934
Tim Shen85de51d2016-10-25 19:55:59 +00002935APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002936 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002937 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002938
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002939 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002940
Michael Gottesman8136c382013-06-26 23:17:28 +00002941 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002942 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00002943 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00002944 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00002945 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002946 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002947 myexponent = 0;
2948 mysignificand = 0;
2949 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002950 myexponent = 0xff;
2951 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002952 } else {
2953 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00002954 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00002955 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002956 }
Dale Johannesena719a602007-08-24 00:56:33 +00002957
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002958 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2959 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00002960}
2961
Tim Shen85de51d2016-10-25 19:55:59 +00002962APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002963 assert(semantics == (const llvm::fltSemantics*)&semIEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00002964 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00002965
2966 uint32_t myexponent, mysignificand;
2967
Michael Gottesman8136c382013-06-26 23:17:28 +00002968 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00002969 myexponent = exponent+15; //bias
2970 mysignificand = (uint32_t)*significandParts();
2971 if (myexponent == 1 && !(mysignificand & 0x400))
2972 myexponent = 0; // denormal
2973 } else if (category==fcZero) {
2974 myexponent = 0;
2975 mysignificand = 0;
2976 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00002977 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002978 mysignificand = 0;
2979 } else {
2980 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00002981 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002982 mysignificand = (uint32_t)*significandParts();
2983 }
2984
2985 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2986 (mysignificand & 0x3ff)));
2987}
2988
Dale Johannesen007aa372007-10-11 18:07:22 +00002989// This function creates an APInt that is just a bit map of the floating
2990// point constant as it would appear in memory. It is not a conversion,
2991// and treating the result as a normal integer is unlikely to be useful.
2992
Tim Shen85de51d2016-10-25 19:55:59 +00002993APInt IEEEFloat::bitcastToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002994 if (semantics == (const llvm::fltSemantics*)&semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00002995 return convertHalfAPFloatToAPInt();
2996
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002997 if (semantics == (const llvm::fltSemantics*)&semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00002998 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002999
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003000 if (semantics == (const llvm::fltSemantics*)&semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003001 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003002
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003003 if (semantics == (const llvm::fltSemantics*)&semIEEEquad)
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003004 return convertQuadrupleAPFloatToAPInt();
3005
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003006 if (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy)
Dale Johannesen007aa372007-10-11 18:07:22 +00003007 return convertPPCDoubleDoubleAPFloatToAPInt();
3008
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003009 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003010 "unknown format!");
3011 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003012}
3013
Tim Shen85de51d2016-10-25 19:55:59 +00003014float IEEEFloat::convertToFloat() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003015 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle &&
Chris Lattner688f9912009-09-24 21:44:20 +00003016 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003017 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003018 return api.bitsToFloat();
3019}
3020
Tim Shen85de51d2016-10-25 19:55:59 +00003021double IEEEFloat::convertToDouble() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003022 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble &&
Chris Lattner688f9912009-09-24 21:44:20 +00003023 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003024 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003025 return api.bitsToDouble();
3026}
3027
Dale Johannesenfff29952008-10-06 18:22:29 +00003028/// Integer bit is explicit in this format. Intel hardware (387 and later)
3029/// does not support these bit patterns:
3030/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3031/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3032/// exponent = 0, integer bit 1 ("pseudodenormal")
3033/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3034/// At the moment, the first two are treated as NaNs, the second two as Normal.
Tim Shen85de51d2016-10-25 19:55:59 +00003035void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003036 assert(api.getBitWidth()==80);
3037 uint64_t i1 = api.getRawData()[0];
3038 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003039 uint64_t myexponent = (i2 & 0x7fff);
3040 uint64_t mysignificand = i1;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003041
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003042 initialize(&semX87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003043 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003044
Dale Johannesen93eefa02009-03-23 21:16:53 +00003045 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003046 if (myexponent==0 && mysignificand==0) {
3047 // exponent, significand meaningless
3048 category = fcZero;
3049 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3050 // exponent, significand meaningless
3051 category = fcInfinity;
3052 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3053 // exponent meaningless
3054 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003055 significandParts()[0] = mysignificand;
3056 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003057 } else {
3058 category = fcNormal;
3059 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003060 significandParts()[0] = mysignificand;
3061 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003062 if (myexponent==0) // denormal
3063 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003064 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003065}
3066
Tim Shen85de51d2016-10-25 19:55:59 +00003067void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) {
Dale Johannesen007aa372007-10-11 18:07:22 +00003068 assert(api.getBitWidth()==128);
3069 uint64_t i1 = api.getRawData()[0];
3070 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003071 opStatus fs;
3072 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003073
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003074 // Get the first double and convert to our format.
3075 initFromDoubleAPInt(APInt(64, i1));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003076 fs = convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003077 assert(fs == opOK && !losesInfo);
3078 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003079
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003080 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003081 if (isFiniteNonZero()) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003082 IEEEFloat v(semIEEEdouble, APInt(64, i2));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003083 fs = v.convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003084 assert(fs == opOK && !losesInfo);
3085 (void)fs;
3086
3087 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003088 }
3089}
3090
Tim Shen85de51d2016-10-25 19:55:59 +00003091void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003092 assert(api.getBitWidth()==128);
3093 uint64_t i1 = api.getRawData()[0];
3094 uint64_t i2 = api.getRawData()[1];
3095 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3096 uint64_t mysignificand = i1;
3097 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3098
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003099 initialize(&semIEEEquad);
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003100 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003101
3102 sign = static_cast<unsigned int>(i2>>63);
3103 if (myexponent==0 &&
3104 (mysignificand==0 && mysignificand2==0)) {
3105 // exponent, significand meaningless
3106 category = fcZero;
3107 } else if (myexponent==0x7fff &&
3108 (mysignificand==0 && mysignificand2==0)) {
3109 // exponent, significand meaningless
3110 category = fcInfinity;
3111 } else if (myexponent==0x7fff &&
3112 (mysignificand!=0 || mysignificand2 !=0)) {
3113 // exponent meaningless
3114 category = fcNaN;
3115 significandParts()[0] = mysignificand;
3116 significandParts()[1] = mysignificand2;
3117 } else {
3118 category = fcNormal;
3119 exponent = myexponent - 16383;
3120 significandParts()[0] = mysignificand;
3121 significandParts()[1] = mysignificand2;
3122 if (myexponent==0) // denormal
3123 exponent = -16382;
3124 else
3125 significandParts()[1] |= 0x1000000000000LL; // integer bit
3126 }
3127}
3128
Tim Shen85de51d2016-10-25 19:55:59 +00003129void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003130 assert(api.getBitWidth()==64);
3131 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003132 uint64_t myexponent = (i >> 52) & 0x7ff;
3133 uint64_t mysignificand = i & 0xfffffffffffffLL;
3134
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003135 initialize(&semIEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003136 assert(partCount()==1);
3137
Evan Cheng82b9e962008-05-02 21:15:08 +00003138 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003139 if (myexponent==0 && mysignificand==0) {
3140 // exponent, significand meaningless
3141 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003142 } else if (myexponent==0x7ff && mysignificand==0) {
3143 // exponent, significand meaningless
3144 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003145 } else if (myexponent==0x7ff && mysignificand!=0) {
3146 // exponent meaningless
3147 category = fcNaN;
3148 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003149 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003150 category = fcNormal;
3151 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003152 *significandParts() = mysignificand;
3153 if (myexponent==0) // denormal
3154 exponent = -1022;
3155 else
3156 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003157 }
Dale Johannesena719a602007-08-24 00:56:33 +00003158}
3159
Tim Shen85de51d2016-10-25 19:55:59 +00003160void IEEEFloat::initFromFloatAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003161 assert(api.getBitWidth()==32);
3162 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003163 uint32_t myexponent = (i >> 23) & 0xff;
3164 uint32_t mysignificand = i & 0x7fffff;
3165
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003166 initialize(&semIEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003167 assert(partCount()==1);
3168
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003169 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003170 if (myexponent==0 && mysignificand==0) {
3171 // exponent, significand meaningless
3172 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003173 } else if (myexponent==0xff && mysignificand==0) {
3174 // exponent, significand meaningless
3175 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003176 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003177 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003178 category = fcNaN;
3179 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003180 } else {
3181 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003182 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003183 *significandParts() = mysignificand;
3184 if (myexponent==0) // denormal
3185 exponent = -126;
3186 else
3187 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003188 }
3189}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003190
Tim Shen85de51d2016-10-25 19:55:59 +00003191void IEEEFloat::initFromHalfAPInt(const APInt &api) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003192 assert(api.getBitWidth()==16);
3193 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003194 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003195 uint32_t mysignificand = i & 0x3ff;
3196
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003197 initialize(&semIEEEhalf);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003198 assert(partCount()==1);
3199
3200 sign = i >> 15;
3201 if (myexponent==0 && mysignificand==0) {
3202 // exponent, significand meaningless
3203 category = fcZero;
3204 } else if (myexponent==0x1f && mysignificand==0) {
3205 // exponent, significand meaningless
3206 category = fcInfinity;
3207 } else if (myexponent==0x1f && mysignificand!=0) {
3208 // sign, exponent, significand meaningless
3209 category = fcNaN;
3210 *significandParts() = mysignificand;
3211 } else {
3212 category = fcNormal;
3213 exponent = myexponent - 15; //bias
3214 *significandParts() = mysignificand;
3215 if (myexponent==0) // denormal
3216 exponent = -14;
3217 else
3218 *significandParts() |= 0x400; // integer bit
3219 }
3220}
3221
Dale Johannesen245dceb2007-09-11 18:32:33 +00003222/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003223/// we infer the floating point type from the size of the APInt. The
3224/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3225/// when the size is anything else).
Tim Shen85de51d2016-10-25 19:55:59 +00003226void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003227 if (Sem == &semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003228 return initFromHalfAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003229 if (Sem == &semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003230 return initFromFloatAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003231 if (Sem == &semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003232 return initFromDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003233 if (Sem == &semX87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003234 return initFromF80LongDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003235 if (Sem == &semIEEEquad)
Tim Northover29178a32013-01-22 09:46:31 +00003236 return initFromQuadrupleAPInt(api);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003237 if (Sem == &semPPCDoubleDoubleLegacy)
Tim Northover29178a32013-01-22 09:46:31 +00003238 return initFromPPCDoubleDoubleAPInt(api);
3239
Craig Topper2617dcc2014-04-15 06:32:26 +00003240 llvm_unreachable(nullptr);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003241}
3242
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003243/// Make this number the largest magnitude normal number in the given
3244/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003245void IEEEFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003246 // We want (in interchange format):
3247 // sign = {Negative}
3248 // exponent = 1..10
3249 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003250 category = fcNormal;
3251 sign = Negative;
3252 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003253
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003254 // Use memset to set all but the highest integerPart to all ones.
3255 integerPart *significand = significandParts();
3256 unsigned PartCount = partCount();
3257 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003258
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003259 // Set the high integerPart especially setting all unused top bits for
3260 // internal consistency.
3261 const unsigned NumUnusedHighBits =
3262 PartCount*integerPartWidth - semantics->precision;
Alexey Samsonovba1ecbc2014-09-06 00:41:19 +00003263 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3264 ? (~integerPart(0) >> NumUnusedHighBits)
3265 : 0;
John McCall29b5c282009-12-24 08:56:26 +00003266}
3267
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003268/// Make this number the smallest magnitude denormal number in the given
3269/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003270void IEEEFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003271 // We want (in interchange format):
3272 // sign = {Negative}
3273 // exponent = 0..0
3274 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003275 category = fcNormal;
3276 sign = Negative;
3277 exponent = semantics->minExponent;
3278 APInt::tcSet(significandParts(), 1, partCount());
3279}
John McCall29b5c282009-12-24 08:56:26 +00003280
Tim Shen139a58f2016-10-27 22:52:40 +00003281void IEEEFloat::makeSmallestNormalized(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003282 // We want (in interchange format):
3283 // sign = {Negative}
3284 // exponent = 0..0
3285 // significand = 10..0
3286
Tim Shen139a58f2016-10-27 22:52:40 +00003287 category = fcNormal;
3288 zeroSignificand();
3289 sign = Negative;
3290 exponent = semantics->minExponent;
3291 significandParts()[partCountForBits(semantics->precision) - 1] |=
3292 (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003293}
3294
Tim Shen85de51d2016-10-25 19:55:59 +00003295IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
Tim Northover29178a32013-01-22 09:46:31 +00003296 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003297}
3298
Tim Shen85de51d2016-10-25 19:55:59 +00003299IEEEFloat::IEEEFloat(float f) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003300 initFromAPInt(&semIEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003301}
3302
Tim Shen85de51d2016-10-25 19:55:59 +00003303IEEEFloat::IEEEFloat(double d) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003304 initFromAPInt(&semIEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003305}
John McCall29b5c282009-12-24 08:56:26 +00003306
3307namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003308 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3309 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003310 }
3311
John McCalle6212ace2009-12-24 12:16:56 +00003312 /// Removes data from the given significand until it is no more
3313 /// precise than is required for the desired precision.
3314 void AdjustToPrecision(APInt &significand,
3315 int &exp, unsigned FormatPrecision) {
3316 unsigned bits = significand.getActiveBits();
3317
3318 // 196/59 is a very slight overestimate of lg_2(10).
3319 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3320
3321 if (bits <= bitsRequired) return;
3322
3323 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3324 if (!tensRemovable) return;
3325
3326 exp += tensRemovable;
3327
3328 APInt divisor(significand.getBitWidth(), 1);
3329 APInt powten(significand.getBitWidth(), 10);
3330 while (true) {
3331 if (tensRemovable & 1)
3332 divisor *= powten;
3333 tensRemovable >>= 1;
3334 if (!tensRemovable) break;
3335 powten *= powten;
3336 }
3337
3338 significand = significand.udiv(divisor);
3339
Hao Liube99cc32013-03-20 01:46:36 +00003340 // Truncate the significand down to its active bit count.
3341 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003342 }
3343
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003344
John McCall29b5c282009-12-24 08:56:26 +00003345 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3346 int &exp, unsigned FormatPrecision) {
3347 unsigned N = buffer.size();
3348 if (N <= FormatPrecision) return;
3349
3350 // The most significant figures are the last ones in the buffer.
3351 unsigned FirstSignificant = N - FormatPrecision;
3352
3353 // Round.
3354 // FIXME: this probably shouldn't use 'round half up'.
3355
3356 // Rounding down is just a truncation, except we also want to drop
3357 // trailing zeros from the new result.
3358 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003359 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003360 FirstSignificant++;
3361
3362 exp += FirstSignificant;
3363 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3364 return;
3365 }
3366
3367 // Rounding up requires a decimal add-with-carry. If we continue
3368 // the carry, the newly-introduced zeros will just be truncated.
3369 for (unsigned I = FirstSignificant; I != N; ++I) {
3370 if (buffer[I] == '9') {
3371 FirstSignificant++;
3372 } else {
3373 buffer[I]++;
3374 break;
3375 }
3376 }
3377
3378 // If we carried through, we have exactly one digit of precision.
3379 if (FirstSignificant == N) {
3380 exp += FirstSignificant;
3381 buffer.clear();
3382 buffer.push_back('1');
3383 return;
3384 }
3385
3386 exp += FirstSignificant;
3387 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3388 }
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003389}
John McCall29b5c282009-12-24 08:56:26 +00003390
Tim Shen85de51d2016-10-25 19:55:59 +00003391void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
3392 unsigned FormatMaxPadding) const {
John McCall29b5c282009-12-24 08:56:26 +00003393 switch (category) {
3394 case fcInfinity:
3395 if (isNegative())
3396 return append(Str, "-Inf");
3397 else
3398 return append(Str, "+Inf");
3399
3400 case fcNaN: return append(Str, "NaN");
3401
3402 case fcZero:
3403 if (isNegative())
3404 Str.push_back('-');
3405
3406 if (!FormatMaxPadding)
3407 append(Str, "0.0E+0");
3408 else
3409 Str.push_back('0');
3410 return;
3411
3412 case fcNormal:
3413 break;
3414 }
3415
3416 if (isNegative())
3417 Str.push_back('-');
3418
3419 // Decompose the number into an APInt and an exponent.
3420 int exp = exponent - ((int) semantics->precision - 1);
3421 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003422 makeArrayRef(significandParts(),
3423 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003424
John McCalldd5044a2009-12-24 23:18:09 +00003425 // Set FormatPrecision if zero. We want to do this before we
3426 // truncate trailing zeros, as those are part of the precision.
3427 if (!FormatPrecision) {
Eli Friedmane72f1322013-08-29 23:44:34 +00003428 // We use enough digits so the number can be round-tripped back to an
3429 // APFloat. The formula comes from "How to Print Floating-Point Numbers
3430 // Accurately" by Steele and White.
3431 // FIXME: Using a formula based purely on the precision is conservative;
3432 // we can print fewer digits depending on the actual value being printed.
John McCalldd5044a2009-12-24 23:18:09 +00003433
Eli Friedmane72f1322013-08-29 23:44:34 +00003434 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3435 FormatPrecision = 2 + semantics->precision * 59 / 196;
John McCalldd5044a2009-12-24 23:18:09 +00003436 }
3437
John McCall29b5c282009-12-24 08:56:26 +00003438 // Ignore trailing binary zeros.
3439 int trailingZeros = significand.countTrailingZeros();
3440 exp += trailingZeros;
3441 significand = significand.lshr(trailingZeros);
3442
3443 // Change the exponent from 2^e to 10^e.
3444 if (exp == 0) {
3445 // Nothing to do.
3446 } else if (exp > 0) {
3447 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003448 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003449 significand <<= exp;
3450 exp = 0;
3451 } else { /* exp < 0 */
3452 int texp = -exp;
3453
3454 // We transform this using the identity:
3455 // (N)(2^-e) == (N)(5^e)(10^-e)
3456 // This means we have to multiply N (the significand) by 5^e.
3457 // To avoid overflow, we have to operate on numbers large
3458 // enough to store N * 5^e:
3459 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003460 // <= semantics->precision + e * 137 / 59
3461 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003462
Eli Friedman19546412011-10-07 23:40:49 +00003463 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003464
3465 // Multiply significand by 5^e.
3466 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003467 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003468 APInt five_to_the_i(precision, 5);
3469 while (true) {
3470 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003471
John McCall29b5c282009-12-24 08:56:26 +00003472 texp >>= 1;
3473 if (!texp) break;
3474 five_to_the_i *= five_to_the_i;
3475 }
3476 }
3477
John McCalle6212ace2009-12-24 12:16:56 +00003478 AdjustToPrecision(significand, exp, FormatPrecision);
3479
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003480 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003481
3482 // Fill the buffer.
3483 unsigned precision = significand.getBitWidth();
3484 APInt ten(precision, 10);
3485 APInt digit(precision, 0);
3486
3487 bool inTrail = true;
3488 while (significand != 0) {
3489 // digit <- significand % 10
3490 // significand <- significand / 10
3491 APInt::udivrem(significand, ten, significand, digit);
3492
3493 unsigned d = digit.getZExtValue();
3494
3495 // Drop trailing zeros.
3496 if (inTrail && !d) exp++;
3497 else {
3498 buffer.push_back((char) ('0' + d));
3499 inTrail = false;
3500 }
3501 }
3502
3503 assert(!buffer.empty() && "no characters in buffer!");
3504
3505 // Drop down to FormatPrecision.
3506 // TODO: don't do more precise calculations above than are required.
3507 AdjustToPrecision(buffer, exp, FormatPrecision);
3508
3509 unsigned NDigits = buffer.size();
3510
John McCalldd5044a2009-12-24 23:18:09 +00003511 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003512 bool FormatScientific;
3513 if (!FormatMaxPadding)
3514 FormatScientific = true;
3515 else {
John McCall29b5c282009-12-24 08:56:26 +00003516 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003517 // 765e3 --> 765000
3518 // ^^^
3519 // But we shouldn't make the number look more precise than it is.
3520 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3521 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003522 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003523 // Power of the most significant digit.
3524 int MSD = exp + (int) (NDigits - 1);
3525 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003526 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003527 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003528 } else {
3529 // 765e-5 == 0.00765
3530 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003531 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003532 }
3533 }
John McCall29b5c282009-12-24 08:56:26 +00003534 }
3535
3536 // Scientific formatting is pretty straightforward.
3537 if (FormatScientific) {
3538 exp += (NDigits - 1);
3539
3540 Str.push_back(buffer[NDigits-1]);
3541 Str.push_back('.');
3542 if (NDigits == 1)
3543 Str.push_back('0');
3544 else
3545 for (unsigned I = 1; I != NDigits; ++I)
3546 Str.push_back(buffer[NDigits-1-I]);
3547 Str.push_back('E');
3548
3549 Str.push_back(exp >= 0 ? '+' : '-');
3550 if (exp < 0) exp = -exp;
3551 SmallVector<char, 6> expbuf;
3552 do {
3553 expbuf.push_back((char) ('0' + (exp % 10)));
3554 exp /= 10;
3555 } while (exp);
3556 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3557 Str.push_back(expbuf[E-1-I]);
3558 return;
3559 }
3560
3561 // Non-scientific, positive exponents.
3562 if (exp >= 0) {
3563 for (unsigned I = 0; I != NDigits; ++I)
3564 Str.push_back(buffer[NDigits-1-I]);
3565 for (unsigned I = 0; I != (unsigned) exp; ++I)
3566 Str.push_back('0');
3567 return;
3568 }
3569
3570 // Non-scientific, negative exponents.
3571
3572 // The number of digits to the left of the decimal point.
3573 int NWholeDigits = exp + (int) NDigits;
3574
3575 unsigned I = 0;
3576 if (NWholeDigits > 0) {
3577 for (; I != (unsigned) NWholeDigits; ++I)
3578 Str.push_back(buffer[NDigits-I-1]);
3579 Str.push_back('.');
3580 } else {
3581 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3582
3583 Str.push_back('0');
3584 Str.push_back('.');
3585 for (unsigned Z = 1; Z != NZeros; ++Z)
3586 Str.push_back('0');
3587 }
3588
3589 for (; I != NDigits; ++I)
3590 Str.push_back(buffer[NDigits-I-1]);
3591}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003592
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003593bool IEEEFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003594 // Special floats and denormals have no exact inverse.
Michael Gottesman8136c382013-06-26 23:17:28 +00003595 if (!isFiniteNonZero())
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003596 return false;
3597
3598 // Check that the number is a power of two by making sure that only the
3599 // integer bit is set in the significand.
3600 if (significandLSB() != semantics->precision - 1)
3601 return false;
3602
3603 // Get the inverse.
Tim Shen85de51d2016-10-25 19:55:59 +00003604 IEEEFloat reciprocal(*semantics, 1ULL);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003605 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3606 return false;
3607
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003608 // Avoid multiplication with a denormal, it is not safe on all platforms and
3609 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003610 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003611 return false;
3612
Michael Gottesman8136c382013-06-26 23:17:28 +00003613 assert(reciprocal.isFiniteNonZero() &&
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003614 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3615
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003616 if (inv)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003617 *inv = APFloat(reciprocal, *semantics);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003618
3619 return true;
3620}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003621
Tim Shen85de51d2016-10-25 19:55:59 +00003622bool IEEEFloat::isSignaling() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003623 if (!isNaN())
3624 return false;
3625
3626 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3627 // first bit of the trailing significand being 0.
3628 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3629}
3630
3631/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3632///
3633/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3634/// appropriate sign switching before/after the computation.
Tim Shen85de51d2016-10-25 19:55:59 +00003635IEEEFloat::opStatus IEEEFloat::next(bool nextDown) {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003636 // If we are performing nextDown, swap sign so we have -x.
3637 if (nextDown)
3638 changeSign();
3639
3640 // Compute nextUp(x)
3641 opStatus result = opOK;
3642
3643 // Handle each float category separately.
3644 switch (category) {
3645 case fcInfinity:
3646 // nextUp(+inf) = +inf
3647 if (!isNegative())
3648 break;
3649 // nextUp(-inf) = -getLargest()
3650 makeLargest(true);
3651 break;
3652 case fcNaN:
3653 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3654 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3655 // change the payload.
3656 if (isSignaling()) {
3657 result = opInvalidOp;
Alp Tokercb402912014-01-24 17:20:08 +00003658 // For consistency, propagate the sign of the sNaN to the qNaN.
Craig Topperc10719f2014-04-07 04:17:22 +00003659 makeNaN(false, isNegative(), nullptr);
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003660 }
3661 break;
3662 case fcZero:
3663 // nextUp(pm 0) = +getSmallest()
3664 makeSmallest(false);
3665 break;
3666 case fcNormal:
3667 // nextUp(-getSmallest()) = -0
3668 if (isSmallest() && isNegative()) {
3669 APInt::tcSet(significandParts(), 0, partCount());
3670 category = fcZero;
3671 exponent = 0;
3672 break;
3673 }
3674
3675 // nextUp(getLargest()) == INFINITY
3676 if (isLargest() && !isNegative()) {
3677 APInt::tcSet(significandParts(), 0, partCount());
3678 category = fcInfinity;
3679 exponent = semantics->maxExponent + 1;
3680 break;
3681 }
3682
3683 // nextUp(normal) == normal + inc.
3684 if (isNegative()) {
3685 // If we are negative, we need to decrement the significand.
3686
3687 // We only cross a binade boundary that requires adjusting the exponent
3688 // if:
3689 // 1. exponent != semantics->minExponent. This implies we are not in the
3690 // smallest binade or are dealing with denormals.
3691 // 2. Our significand excluding the integral bit is all zeros.
3692 bool WillCrossBinadeBoundary =
3693 exponent != semantics->minExponent && isSignificandAllZeros();
3694
3695 // Decrement the significand.
3696 //
3697 // We always do this since:
Alp Tokerf907b892013-12-05 05:44:44 +00003698 // 1. If we are dealing with a non-binade decrement, by definition we
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003699 // just decrement the significand.
3700 // 2. If we are dealing with a normal -> normal binade decrement, since
3701 // we have an explicit integral bit the fact that all bits but the
3702 // integral bit are zero implies that subtracting one will yield a
3703 // significand with 0 integral bit and 1 in all other spots. Thus we
3704 // must just adjust the exponent and set the integral bit to 1.
3705 // 3. If we are dealing with a normal -> denormal binade decrement,
3706 // since we set the integral bit to 0 when we represent denormals, we
3707 // just decrement the significand.
3708 integerPart *Parts = significandParts();
3709 APInt::tcDecrement(Parts, partCount());
3710
3711 if (WillCrossBinadeBoundary) {
3712 // Our result is a normal number. Do the following:
3713 // 1. Set the integral bit to 1.
3714 // 2. Decrement the exponent.
3715 APInt::tcSetBit(Parts, semantics->precision - 1);
3716 exponent--;
3717 }
3718 } else {
3719 // If we are positive, we need to increment the significand.
3720
3721 // We only cross a binade boundary that requires adjusting the exponent if
3722 // the input is not a denormal and all of said input's significand bits
3723 // are set. If all of said conditions are true: clear the significand, set
3724 // the integral bit to 1, and increment the exponent. If we have a
3725 // denormal always increment since moving denormals and the numbers in the
3726 // smallest normal binade have the same exponent in our representation.
3727 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3728
3729 if (WillCrossBinadeBoundary) {
3730 integerPart *Parts = significandParts();
3731 APInt::tcSet(Parts, 0, partCount());
3732 APInt::tcSetBit(Parts, semantics->precision - 1);
3733 assert(exponent != semantics->maxExponent &&
3734 "We can not increment an exponent beyond the maxExponent allowed"
3735 " by the given floating point semantics.");
3736 exponent++;
3737 } else {
3738 incrementSignificand();
3739 }
3740 }
3741 break;
3742 }
3743
3744 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3745 if (nextDown)
3746 changeSign();
3747
3748 return result;
3749}
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003750
Tim Shen85de51d2016-10-25 19:55:59 +00003751void IEEEFloat::makeInf(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003752 category = fcInfinity;
3753 sign = Negative;
3754 exponent = semantics->maxExponent + 1;
3755 APInt::tcSet(significandParts(), 0, partCount());
3756}
3757
Tim Shen85de51d2016-10-25 19:55:59 +00003758void IEEEFloat::makeZero(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003759 category = fcZero;
3760 sign = Negative;
3761 exponent = semantics->minExponent-1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003762 APInt::tcSet(significandParts(), 0, partCount());
3763}
3764
Tim Shen85de51d2016-10-25 19:55:59 +00003765void IEEEFloat::makeQuiet() {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003766 assert(isNaN());
3767 APInt::tcSetBit(significandParts(), semantics->precision - 2);
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003768}
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003769
Tim Shen85de51d2016-10-25 19:55:59 +00003770int ilogb(const IEEEFloat &Arg) {
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003771 if (Arg.isNaN())
Tim Shen85de51d2016-10-25 19:55:59 +00003772 return IEEEFloat::IEK_NaN;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003773 if (Arg.isZero())
Tim Shen85de51d2016-10-25 19:55:59 +00003774 return IEEEFloat::IEK_Zero;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003775 if (Arg.isInfinity())
Tim Shen85de51d2016-10-25 19:55:59 +00003776 return IEEEFloat::IEK_Inf;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003777 if (!Arg.isDenormal())
3778 return Arg.exponent;
3779
Tim Shen85de51d2016-10-25 19:55:59 +00003780 IEEEFloat Normalized(Arg);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003781 int SignificandBits = Arg.getSemantics().precision - 1;
3782
3783 Normalized.exponent += SignificandBits;
Tim Shen85de51d2016-10-25 19:55:59 +00003784 Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003785 return Normalized.exponent - SignificandBits;
3786}
3787
Tim Shen85de51d2016-10-25 19:55:59 +00003788IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) {
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003789 auto MaxExp = X.getSemantics().maxExponent;
3790 auto MinExp = X.getSemantics().minExponent;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003791
Matt Arsenaultafa31cf2016-03-13 05:11:51 +00003792 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
3793 // overflow; clamp it to a safe range before adding, but ensure that the range
3794 // is large enough that the clamp does not change the result. The range we
3795 // need to support is the difference between the largest possible exponent and
3796 // the normalized exponent of half the smallest denormal.
3797
3798 int SignificandBits = X.getSemantics().precision - 1;
3799 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
3800
3801 // Clamp to one past the range ends to let normalize handle overlflow.
3802 X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement);
3803 X.normalize(RoundingMode, lfExactlyZero);
Matt Arsenaultea00b492016-03-23 23:51:45 +00003804 if (X.isNaN())
3805 X.makeQuiet();
Richard Trieu6ae37962015-04-30 23:07:00 +00003806 return X;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003807}
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003808
Tim Shen85de51d2016-10-25 19:55:59 +00003809IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003810 Exp = ilogb(Val);
3811
3812 // Quiet signalling nans.
Tim Shen85de51d2016-10-25 19:55:59 +00003813 if (Exp == IEEEFloat::IEK_NaN) {
3814 IEEEFloat Quiet(Val);
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003815 Quiet.makeQuiet();
3816 return Quiet;
3817 }
3818
Tim Shen85de51d2016-10-25 19:55:59 +00003819 if (Exp == IEEEFloat::IEK_Inf)
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003820 return Val;
3821
3822 // 1 is added because frexp is defined to return a normalized fraction in
3823 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
Tim Shen85de51d2016-10-25 19:55:59 +00003824 Exp = Exp == IEEEFloat::IEK_Zero ? 0 : Exp + 1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003825 return scalbn(Val, -Exp, RM);
3826}
Tim Shen85de51d2016-10-25 19:55:59 +00003827
Tim Shen139a58f2016-10-27 22:52:40 +00003828DoubleAPFloat::DoubleAPFloat(const fltSemantics &S)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003829 : Semantics(&S),
3830 Floats(new APFloat[2]{APFloat(semIEEEdouble), APFloat(semIEEEdouble)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003831 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003832}
3833
3834DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag)
3835 : Semantics(&S),
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003836 Floats(new APFloat[2]{APFloat(semIEEEdouble, uninitialized),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003837 APFloat(semIEEEdouble, uninitialized)}) {
3838 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003839}
3840
3841DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003842 : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble, I),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003843 APFloat(semIEEEdouble)}) {
3844 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003845}
3846
3847DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003848 : Semantics(&S),
3849 Floats(new APFloat[2]{
3850 APFloat(semIEEEdouble, APInt(64, I.getRawData()[0])),
3851 APFloat(semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003852 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003853}
3854
3855DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First,
3856 APFloat &&Second)
3857 : Semantics(&S),
3858 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003859 assert(Semantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003860 assert(&Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003861 assert(&Floats[1].getSemantics() == &semIEEEdouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003862}
3863
3864DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS)
3865 : Semantics(RHS.Semantics),
Tim Shenb49915482016-10-28 22:45:33 +00003866 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
3867 APFloat(RHS.Floats[1])}
3868 : nullptr) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003869 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003870}
3871
3872DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS)
3873 : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003874 RHS.Semantics = &semBogus;
3875 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003876}
3877
3878DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) {
Tim Shenb49915482016-10-28 22:45:33 +00003879 if (Semantics == RHS.Semantics && RHS.Floats) {
Tim Shen139a58f2016-10-27 22:52:40 +00003880 Floats[0] = RHS.Floats[0];
3881 Floats[1] = RHS.Floats[1];
3882 } else if (this != &RHS) {
3883 this->~DoubleAPFloat();
3884 new (this) DoubleAPFloat(RHS);
3885 }
3886 return *this;
3887}
3888
Tim Shen7f127622017-01-24 00:19:45 +00003889// Implement addition, subtraction, multiplication and division based on:
Tim Shen44bde892016-12-12 21:59:30 +00003890// "Software for Doubled-Precision Floating-Point Computations",
3891// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
3892APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
3893 const APFloat &c, const APFloat &cc,
3894 roundingMode RM) {
3895 int Status = opOK;
3896 APFloat z = a;
3897 Status |= z.add(c, RM);
3898 if (!z.isFinite()) {
3899 if (!z.isInfinity()) {
3900 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003901 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003902 return (opStatus)Status;
3903 }
3904 Status = opOK;
3905 auto AComparedToC = a.compareAbsoluteValue(c);
3906 z = cc;
3907 Status |= z.add(aa, RM);
3908 if (AComparedToC == APFloat::cmpGreaterThan) {
3909 // z = cc + aa + c + a;
3910 Status |= z.add(c, RM);
3911 Status |= z.add(a, RM);
3912 } else {
3913 // z = cc + aa + a + c;
3914 Status |= z.add(a, RM);
3915 Status |= z.add(c, RM);
3916 }
3917 if (!z.isFinite()) {
3918 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003919 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003920 return (opStatus)Status;
3921 }
3922 Floats[0] = z;
3923 APFloat zz = aa;
3924 Status |= zz.add(cc, RM);
3925 if (AComparedToC == APFloat::cmpGreaterThan) {
3926 // Floats[1] = a - z + c + zz;
3927 Floats[1] = a;
3928 Status |= Floats[1].subtract(z, RM);
3929 Status |= Floats[1].add(c, RM);
3930 Status |= Floats[1].add(zz, RM);
3931 } else {
3932 // Floats[1] = c - z + a + zz;
3933 Floats[1] = c;
3934 Status |= Floats[1].subtract(z, RM);
3935 Status |= Floats[1].add(a, RM);
3936 Status |= Floats[1].add(zz, RM);
3937 }
3938 } else {
3939 // q = a - z;
3940 APFloat q = a;
3941 Status |= q.subtract(z, RM);
3942
3943 // zz = q + c + (a - (q + z)) + aa + cc;
3944 // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
3945 auto zz = q;
3946 Status |= zz.add(c, RM);
3947 Status |= q.add(z, RM);
3948 Status |= q.subtract(a, RM);
3949 q.changeSign();
3950 Status |= zz.add(q, RM);
3951 Status |= zz.add(aa, RM);
3952 Status |= zz.add(cc, RM);
3953 if (zz.isZero() && !zz.isNegative()) {
3954 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003955 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003956 return opOK;
3957 }
3958 Floats[0] = z;
3959 Status |= Floats[0].add(zz, RM);
3960 if (!Floats[0].isFinite()) {
Tim Shen7117e692017-01-26 00:11:07 +00003961 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003962 return (opStatus)Status;
3963 }
3964 Floats[1] = std::move(z);
3965 Status |= Floats[1].subtract(Floats[0], RM);
3966 Status |= Floats[1].add(zz, RM);
3967 }
3968 return (opStatus)Status;
3969}
3970
3971APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
3972 const DoubleAPFloat &RHS,
3973 DoubleAPFloat &Out,
3974 roundingMode RM) {
3975 if (LHS.getCategory() == fcNaN) {
3976 Out = LHS;
3977 return opOK;
3978 }
3979 if (RHS.getCategory() == fcNaN) {
3980 Out = RHS;
3981 return opOK;
3982 }
3983 if (LHS.getCategory() == fcZero) {
3984 Out = RHS;
3985 return opOK;
3986 }
3987 if (RHS.getCategory() == fcZero) {
3988 Out = LHS;
3989 return opOK;
3990 }
3991 if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity &&
3992 LHS.isNegative() != RHS.isNegative()) {
3993 Out.makeNaN(false, Out.isNegative(), nullptr);
3994 return opInvalidOp;
3995 }
3996 if (LHS.getCategory() == fcInfinity) {
3997 Out = LHS;
3998 return opOK;
3999 }
4000 if (RHS.getCategory() == fcInfinity) {
4001 Out = RHS;
4002 return opOK;
4003 }
4004 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
4005
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004006 APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
Tim Shen44bde892016-12-12 21:59:30 +00004007 CC(RHS.Floats[1]);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004008 assert(&A.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004009 assert(&AA.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004010 assert(&C.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004011 assert(&CC.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004012 assert(&Out.Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004013 assert(&Out.Floats[1].getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004014 return Out.addImpl(A, AA, C, CC, RM);
Tim Shen44bde892016-12-12 21:59:30 +00004015}
4016
4017APFloat::opStatus DoubleAPFloat::add(const DoubleAPFloat &RHS,
4018 roundingMode RM) {
4019 return addWithSpecial(*this, RHS, *this, RM);
4020}
4021
4022APFloat::opStatus DoubleAPFloat::subtract(const DoubleAPFloat &RHS,
4023 roundingMode RM) {
4024 changeSign();
4025 auto Ret = add(RHS, RM);
4026 changeSign();
4027 return Ret;
4028}
4029
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004030APFloat::opStatus DoubleAPFloat::multiply(const DoubleAPFloat &RHS,
4031 APFloat::roundingMode RM) {
Tim Shen7f127622017-01-24 00:19:45 +00004032 const auto &LHS = *this;
4033 auto &Out = *this;
4034 /* Interesting observation: For special categories, finding the lowest
4035 common ancestor of the following layered graph gives the correct
4036 return category:
4037
4038 NaN
4039 / \
4040 Zero Inf
4041 \ /
4042 Normal
4043
4044 e.g. NaN * NaN = NaN
4045 Zero * Inf = NaN
4046 Normal * Zero = Zero
4047 Normal * Inf = Inf
4048 */
4049 if (LHS.getCategory() == fcNaN) {
4050 Out = LHS;
4051 return opOK;
4052 }
4053 if (RHS.getCategory() == fcNaN) {
4054 Out = RHS;
4055 return opOK;
4056 }
4057 if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) ||
4058 (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) {
4059 Out.makeNaN(false, false, nullptr);
4060 return opOK;
4061 }
4062 if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) {
4063 Out = LHS;
4064 return opOK;
4065 }
4066 if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) {
4067 Out = RHS;
4068 return opOK;
4069 }
4070 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
4071 "Special cases not handled exhaustively");
4072
4073 int Status = opOK;
4074 APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
4075 // t = a * c
4076 APFloat T = A;
4077 Status |= T.multiply(C, RM);
4078 if (!T.isFiniteNonZero()) {
4079 Floats[0] = T;
Tim Shen7117e692017-01-26 00:11:07 +00004080 Floats[1].makeZero(/* Neg = */ false);
Tim Shen7f127622017-01-24 00:19:45 +00004081 return (opStatus)Status;
4082 }
4083
4084 // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
4085 APFloat Tau = A;
4086 T.changeSign();
4087 Status |= Tau.fusedMultiplyAdd(C, T, RM);
4088 T.changeSign();
4089 {
4090 // v = a * d
4091 APFloat V = A;
4092 Status |= V.multiply(D, RM);
4093 // w = b * c
4094 APFloat W = B;
4095 Status |= W.multiply(C, RM);
4096 Status |= V.add(W, RM);
4097 // tau += v + w
4098 Status |= Tau.add(V, RM);
4099 }
4100 // u = t + tau
4101 APFloat U = T;
4102 Status |= U.add(Tau, RM);
4103
4104 Floats[0] = U;
4105 if (!U.isFinite()) {
Tim Shen7117e692017-01-26 00:11:07 +00004106 Floats[1].makeZero(/* Neg = */ false);
Tim Shen7f127622017-01-24 00:19:45 +00004107 } else {
4108 // Floats[1] = (t - u) + tau
4109 Status |= T.subtract(U, RM);
4110 Status |= T.add(Tau, RM);
4111 Floats[1] = T;
4112 }
4113 return (opStatus)Status;
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004114}
4115
4116APFloat::opStatus DoubleAPFloat::divide(const DoubleAPFloat &RHS,
4117 APFloat::roundingMode RM) {
4118 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4119 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4120 auto Ret =
4121 Tmp.divide(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
4122 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4123 return Ret;
4124}
4125
4126APFloat::opStatus DoubleAPFloat::remainder(const DoubleAPFloat &RHS) {
4127 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4128 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4129 auto Ret =
4130 Tmp.remainder(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4131 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4132 return Ret;
4133}
4134
4135APFloat::opStatus DoubleAPFloat::mod(const DoubleAPFloat &RHS) {
4136 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4137 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4138 auto Ret = Tmp.mod(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4139 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4140 return Ret;
4141}
4142
4143APFloat::opStatus
4144DoubleAPFloat::fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
4145 const DoubleAPFloat &Addend,
4146 APFloat::roundingMode RM) {
4147 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4148 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4149 auto Ret = Tmp.fusedMultiplyAdd(
4150 APFloat(semPPCDoubleDoubleLegacy, Multiplicand.bitcastToAPInt()),
4151 APFloat(semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()), RM);
4152 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4153 return Ret;
4154}
4155
4156APFloat::opStatus DoubleAPFloat::roundToIntegral(APFloat::roundingMode RM) {
4157 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4158 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4159 auto Ret = Tmp.roundToIntegral(RM);
4160 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4161 return Ret;
4162}
4163
Tim Shen44bde892016-12-12 21:59:30 +00004164void DoubleAPFloat::changeSign() {
4165 Floats[0].changeSign();
4166 Floats[1].changeSign();
4167}
4168
4169APFloat::cmpResult
4170DoubleAPFloat::compareAbsoluteValue(const DoubleAPFloat &RHS) const {
4171 auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
4172 if (Result != cmpEqual)
4173 return Result;
4174 Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
4175 if (Result == cmpLessThan || Result == cmpGreaterThan) {
4176 auto Against = Floats[0].isNegative() ^ Floats[1].isNegative();
4177 auto RHSAgainst = RHS.Floats[0].isNegative() ^ RHS.Floats[1].isNegative();
4178 if (Against && !RHSAgainst)
4179 return cmpLessThan;
4180 if (!Against && RHSAgainst)
4181 return cmpGreaterThan;
4182 if (!Against && !RHSAgainst)
4183 return Result;
4184 if (Against && RHSAgainst)
4185 return (cmpResult)(cmpLessThan + cmpGreaterThan - Result);
4186 }
4187 return Result;
4188}
4189
4190APFloat::fltCategory DoubleAPFloat::getCategory() const {
4191 return Floats[0].getCategory();
4192}
4193
4194bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
4195
4196void DoubleAPFloat::makeInf(bool Neg) {
4197 Floats[0].makeInf(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004198 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004199}
4200
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004201void DoubleAPFloat::makeZero(bool Neg) {
4202 Floats[0].makeZero(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004203 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004204}
4205
4206void DoubleAPFloat::makeLargest(bool Neg) {
4207 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4208 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
4209 Floats[1] = APFloat(semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
4210 if (Neg)
4211 changeSign();
4212}
4213
4214void DoubleAPFloat::makeSmallest(bool Neg) {
4215 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4216 Floats[0].makeSmallest(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004217 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004218}
4219
4220void DoubleAPFloat::makeSmallestNormalized(bool Neg) {
4221 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4222 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x0360000000000000ull));
4223 if (Neg)
4224 Floats[0].changeSign();
Tim Shen7117e692017-01-26 00:11:07 +00004225 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004226}
4227
Tim Shen44bde892016-12-12 21:59:30 +00004228void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
4229 Floats[0].makeNaN(SNaN, Neg, fill);
Tim Shen7117e692017-01-26 00:11:07 +00004230 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004231}
4232
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004233APFloat::cmpResult DoubleAPFloat::compare(const DoubleAPFloat &RHS) const {
4234 auto Result = Floats[0].compare(RHS.Floats[0]);
Tim Shen7117e692017-01-26 00:11:07 +00004235 // |Float[0]| > |Float[1]|
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004236 if (Result == APFloat::cmpEqual)
4237 return Floats[1].compare(RHS.Floats[1]);
4238 return Result;
4239}
4240
4241bool DoubleAPFloat::bitwiseIsEqual(const DoubleAPFloat &RHS) const {
4242 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
4243 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
4244}
4245
4246hash_code hash_value(const DoubleAPFloat &Arg) {
4247 if (Arg.Floats)
4248 return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
4249 return hash_combine(Arg.Semantics);
4250}
4251
4252APInt DoubleAPFloat::bitcastToAPInt() const {
4253 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4254 uint64_t Data[] = {
4255 Floats[0].bitcastToAPInt().getRawData()[0],
4256 Floats[1].bitcastToAPInt().getRawData()[0],
4257 };
4258 return APInt(128, 2, Data);
4259}
4260
4261APFloat::opStatus DoubleAPFloat::convertFromString(StringRef S,
4262 roundingMode RM) {
4263 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4264 APFloat Tmp(semPPCDoubleDoubleLegacy);
4265 auto Ret = Tmp.convertFromString(S, RM);
4266 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4267 return Ret;
4268}
4269
4270APFloat::opStatus DoubleAPFloat::next(bool nextDown) {
4271 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4272 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4273 auto Ret = Tmp.next(nextDown);
4274 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4275 return Ret;
4276}
4277
Simon Pilgrim00b34992017-03-20 14:40:12 +00004278APFloat::opStatus
4279DoubleAPFloat::convertToInteger(MutableArrayRef<integerPart> Input,
4280 unsigned int Width, bool IsSigned,
4281 roundingMode RM, bool *IsExact) const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004282 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4283 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4284 .convertToInteger(Input, Width, IsSigned, RM, IsExact);
4285}
4286
4287APFloat::opStatus DoubleAPFloat::convertFromAPInt(const APInt &Input,
4288 bool IsSigned,
4289 roundingMode RM) {
4290 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4291 APFloat Tmp(semPPCDoubleDoubleLegacy);
4292 auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM);
4293 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4294 return Ret;
4295}
4296
4297APFloat::opStatus
4298DoubleAPFloat::convertFromSignExtendedInteger(const integerPart *Input,
4299 unsigned int InputSize,
4300 bool IsSigned, roundingMode RM) {
4301 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4302 APFloat Tmp(semPPCDoubleDoubleLegacy);
4303 auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM);
4304 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4305 return Ret;
4306}
4307
4308APFloat::opStatus
4309DoubleAPFloat::convertFromZeroExtendedInteger(const integerPart *Input,
4310 unsigned int InputSize,
4311 bool IsSigned, roundingMode RM) {
4312 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4313 APFloat Tmp(semPPCDoubleDoubleLegacy);
4314 auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM);
4315 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4316 return Ret;
4317}
4318
4319unsigned int DoubleAPFloat::convertToHexString(char *DST,
4320 unsigned int HexDigits,
4321 bool UpperCase,
4322 roundingMode RM) const {
4323 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4324 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4325 .convertToHexString(DST, HexDigits, UpperCase, RM);
4326}
4327
4328bool DoubleAPFloat::isDenormal() const {
4329 return getCategory() == fcNormal &&
4330 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
Tim Shen7117e692017-01-26 00:11:07 +00004331 // (double)(Hi + Lo) == Hi defines a normal number.
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004332 Floats[0].compare(Floats[0] + Floats[1]) != cmpEqual);
4333}
4334
4335bool DoubleAPFloat::isSmallest() const {
4336 if (getCategory() != fcNormal)
4337 return false;
4338 DoubleAPFloat Tmp(*this);
4339 Tmp.makeSmallest(this->isNegative());
4340 return Tmp.compare(*this) == cmpEqual;
4341}
4342
4343bool DoubleAPFloat::isLargest() const {
4344 if (getCategory() != fcNormal)
4345 return false;
4346 DoubleAPFloat Tmp(*this);
4347 Tmp.makeLargest(this->isNegative());
4348 return Tmp.compare(*this) == cmpEqual;
4349}
4350
4351bool DoubleAPFloat::isInteger() const {
4352 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4353 APFloat Tmp(semPPCDoubleDoubleLegacy);
4354 (void)Tmp.add(Floats[0], rmNearestTiesToEven);
4355 (void)Tmp.add(Floats[1], rmNearestTiesToEven);
4356 return Tmp.isInteger();
4357}
4358
4359void DoubleAPFloat::toString(SmallVectorImpl<char> &Str,
4360 unsigned FormatPrecision,
4361 unsigned FormatMaxPadding) const {
4362 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4363 APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4364 .toString(Str, FormatPrecision, FormatMaxPadding);
4365}
4366
4367bool DoubleAPFloat::getExactInverse(APFloat *inv) const {
4368 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4369 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4370 if (!inv)
4371 return Tmp.getExactInverse(nullptr);
4372 APFloat Inv(semPPCDoubleDoubleLegacy);
4373 auto Ret = Tmp.getExactInverse(&Inv);
4374 *inv = APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt());
4375 return Ret;
4376}
4377
4378DoubleAPFloat scalbn(DoubleAPFloat Arg, int Exp, APFloat::roundingMode RM) {
4379 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4380 return DoubleAPFloat(semPPCDoubleDouble, scalbn(Arg.Floats[0], Exp, RM),
4381 scalbn(Arg.Floats[1], Exp, RM));
4382}
4383
4384DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
4385 APFloat::roundingMode RM) {
4386 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4387 APFloat First = frexp(Arg.Floats[0], Exp, RM);
4388 APFloat Second = Arg.Floats[1];
4389 if (Arg.getCategory() == APFloat::fcNormal)
4390 Second = scalbn(Second, -Exp, RM);
4391 return DoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second));
4392}
4393
Tim Shen85de51d2016-10-25 19:55:59 +00004394} // End detail namespace
4395
Tim Shen398f90f2016-11-06 07:38:37 +00004396APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
4397 if (usesLayout<IEEEFloat>(Semantics)) {
4398 new (&IEEE) IEEEFloat(std::move(F));
Tim Shen7b57ac42016-12-21 02:39:21 +00004399 return;
4400 }
4401 if (usesLayout<DoubleAPFloat>(Semantics)) {
Tim Shen398f90f2016-11-06 07:38:37 +00004402 new (&Double)
4403 DoubleAPFloat(Semantics, APFloat(std::move(F), F.getSemantics()),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004404 APFloat(semIEEEdouble));
Tim Shen7b57ac42016-12-21 02:39:21 +00004405 return;
Tim Shen398f90f2016-11-06 07:38:37 +00004406 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004407 llvm_unreachable("Unexpected semantics");
Tim Shen398f90f2016-11-06 07:38:37 +00004408}
4409
Tim Shen85de51d2016-10-25 19:55:59 +00004410APFloat::opStatus APFloat::convertFromString(StringRef Str, roundingMode RM) {
Tim Shen601ba8c2017-01-27 02:11:07 +00004411 APFLOAT_DISPATCH_ON_SEMANTICS(convertFromString(Str, RM));
Tim Shen85de51d2016-10-25 19:55:59 +00004412}
4413
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004414hash_code hash_value(const APFloat &Arg) {
4415 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
4416 return hash_value(Arg.U.IEEE);
4417 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
4418 return hash_value(Arg.U.Double);
4419 llvm_unreachable("Unexpected semantics");
4420}
Tim Shen85de51d2016-10-25 19:55:59 +00004421
4422APFloat::APFloat(const fltSemantics &Semantics, StringRef S)
Tim Shen139a58f2016-10-27 22:52:40 +00004423 : APFloat(Semantics) {
4424 convertFromString(S, rmNearestTiesToEven);
4425}
4426
4427APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics,
4428 roundingMode RM, bool *losesInfo) {
4429 if (&getSemantics() == &ToSemantics)
4430 return opOK;
4431 if (usesLayout<IEEEFloat>(getSemantics()) &&
Tim Shen7b57ac42016-12-21 02:39:21 +00004432 usesLayout<IEEEFloat>(ToSemantics))
Tim Shen139a58f2016-10-27 22:52:40 +00004433 return U.IEEE.convert(ToSemantics, RM, losesInfo);
Tim Shen7b57ac42016-12-21 02:39:21 +00004434 if (usesLayout<IEEEFloat>(getSemantics()) &&
4435 usesLayout<DoubleAPFloat>(ToSemantics)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004436 assert(&ToSemantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004437 auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo);
4438 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
Tim Shen139a58f2016-10-27 22:52:40 +00004439 return Ret;
Tim Shen7b57ac42016-12-21 02:39:21 +00004440 }
4441 if (usesLayout<DoubleAPFloat>(getSemantics()) &&
4442 usesLayout<IEEEFloat>(ToSemantics)) {
Tim Shen139a58f2016-10-27 22:52:40 +00004443 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
Tim Shen398f90f2016-11-06 07:38:37 +00004444 *this = APFloat(std::move(getIEEE()), ToSemantics);
Tim Shen139a58f2016-10-27 22:52:40 +00004445 return Ret;
Tim Shen139a58f2016-10-27 22:52:40 +00004446 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004447 llvm_unreachable("Unexpected semantics");
Tim Shen139a58f2016-10-27 22:52:40 +00004448}
Tim Shen85de51d2016-10-25 19:55:59 +00004449
Tim Shen398f90f2016-11-06 07:38:37 +00004450APFloat APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE) {
4451 if (isIEEE) {
4452 switch (BitWidth) {
4453 case 16:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004454 return APFloat(semIEEEhalf, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004455 case 32:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004456 return APFloat(semIEEEsingle, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004457 case 64:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004458 return APFloat(semIEEEdouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004459 case 80:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004460 return APFloat(semX87DoubleExtended, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004461 case 128:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004462 return APFloat(semIEEEquad, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004463 default:
4464 llvm_unreachable("Unknown floating bit width");
4465 }
4466 } else {
4467 assert(BitWidth == 128);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004468 return APFloat(semPPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004469 }
4470}
4471
Tim Shen44bde892016-12-12 21:59:30 +00004472void APFloat::print(raw_ostream &OS) const {
4473 SmallVector<char, 16> Buffer;
4474 toString(Buffer);
4475 OS << Buffer << "\n";
4476}
4477
Matthias Braun8c209aa2017-01-28 02:02:38 +00004478#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4479LLVM_DUMP_METHOD void APFloat::dump() const { print(dbgs()); }
4480#endif
Tim Shen44bde892016-12-12 21:59:30 +00004481
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004482void APFloat::Profile(FoldingSetNodeID &NID) const {
4483 NID.Add(bitcastToAPInt());
4484}
4485
4486/* Same as convertToInteger(integerPart*, ...), except the result is returned in
4487 an APSInt, whose initial bit-width and signed-ness are used to determine the
4488 precision of the conversion.
4489 */
4490APFloat::opStatus APFloat::convertToInteger(APSInt &result,
4491 roundingMode rounding_mode,
4492 bool *isExact) const {
4493 unsigned bitWidth = result.getBitWidth();
4494 SmallVector<uint64_t, 4> parts(result.getNumWords());
Simon Pilgrim00b34992017-03-20 14:40:12 +00004495 opStatus status = convertToInteger(parts, bitWidth, result.isSigned(),
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004496 rounding_mode, isExact);
4497 // Keeps the original signed-ness.
4498 result = APInt(bitWidth, parts);
4499 return status;
4500}
4501
Tim Shen85de51d2016-10-25 19:55:59 +00004502} // End llvm namespace
Tim Shen601ba8c2017-01-27 02:11:07 +00004503
4504#undef APFLOAT_DISPATCH_ON_SEMANTICS