blob: f9fe09541dbe22c73eeafaab9441052863740f9f [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"
Ted Kremenek6f30a072008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
Jordan Rosee1f76582013-01-18 21:45:30 +000019#include "llvm/ADT/StringExtras.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000020#include "llvm/ADT/StringRef.h"
Torok Edwin56d06592009-07-11 20:10:48 +000021#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000022#include "llvm/Support/MathExtras.h"
Chris Lattner17f71652008-08-17 07:19:36 +000023#include <cstring>
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include <limits.h>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000025
26using namespace llvm;
27
Michael Gottesman9b877e12013-06-24 09:57:57 +000028/// A macro used to combine two fcCategory enums into one key which can be used
29/// in a switch statement to classify how the interaction of two APFloat's
30/// categories affects an operation.
31///
32/// TODO: If clang source code is ever allowed to use constexpr in its own
33/// codebase, change this into a static inline function.
34#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000035
Neil Booth8f1946f2007-10-03 22:26:02 +000036/* Assumed in hexadecimal significand parsing, and conversion to
37 hexadecimal strings. */
Chris Lattner8fcea672008-08-17 04:58:58 +000038#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000039COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
40
41namespace llvm {
42
43 /* Represents floating point arithmetic semantics. */
44 struct fltSemantics {
45 /* The largest E such that 2^E is representable; this matches the
46 definition of IEEE 754. */
Michael Gottesman9dc98332013-06-24 04:06:23 +000047 APFloat::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000048
49 /* The smallest E such that 2^E is a normalized number; this
50 matches the definition of IEEE 754. */
Michael Gottesman9dc98332013-06-24 04:06:23 +000051 APFloat::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000052
53 /* Number of bits in the significand. This includes the integer
54 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000055 unsigned int precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000056 };
57
Ulrich Weigand908c9362012-10-29 18:18:44 +000058 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11 };
59 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24 };
60 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53 };
61 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113 };
62 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64 };
63 const fltSemantics APFloat::Bogus = { 0, 0, 0 };
Dale Johannesen007aa372007-10-11 18:07:22 +000064
Ulrich Weigandd9f7e252012-10-29 18:09:01 +000065 /* The PowerPC format consists of two doubles. It does not map cleanly
66 onto the usual format above. It is approximated using twice the
67 mantissa bits. Note that for exponents near the double minimum,
68 we no longer can represent the full 106 mantissa bits, so those
69 will be treated as denormal numbers.
70
71 FIXME: While this approximation is equivalent to what GCC uses for
72 compile-time arithmetic on PPC double-double numbers, it is not able
73 to represent all possible values held by a PPC double-double number,
74 for example: (long double) 1.0 + (long double) 0x1p-106
75 Should this be replaced by a full emulation of PPC double-double? */
Ulrich Weigand908c9362012-10-29 18:18:44 +000076 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022 + 53, 53 + 53 };
Neil Boothb93d90e2007-10-12 16:02:31 +000077
78 /* A tight upper bound on number of parts required to hold the value
79 pow(5, power) is
80
Neil Booth91305512007-10-15 15:00:55 +000081 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +000082
Neil Boothb93d90e2007-10-12 16:02:31 +000083 However, whilst the result may require only this many parts,
84 because we are multiplying two values to get it, the
85 multiplication may require an extra part with the excess part
86 being zero (consider the trivial case of 1 * 1, tcFullMultiply
87 requires two parts to hold the single-part result). So we add an
88 extra one to guarantee enough space whilst multiplying. */
89 const unsigned int maxExponent = 16383;
90 const unsigned int maxPrecision = 113;
91 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth91305512007-10-15 15:00:55 +000092 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
93 / (351 * integerPartWidth));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000094}
95
Chris Lattner91702092009-03-12 23:59:55 +000096/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000097
Chris Lattner91702092009-03-12 23:59:55 +000098static inline unsigned int
99partCountForBits(unsigned int bits)
100{
101 return ((bits) + integerPartWidth - 1) / integerPartWidth;
102}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000103
Chris Lattner91702092009-03-12 23:59:55 +0000104/* Returns 0U-9U. Return values >= 10U are not digits. */
105static inline unsigned int
106decDigitValue(unsigned int c)
107{
108 return c - '0';
109}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000110
Chris Lattner91702092009-03-12 23:59:55 +0000111/* Return the value of a decimal exponent of the form
112 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000113
Chris Lattner91702092009-03-12 23:59:55 +0000114 If the exponent overflows, returns a large exponent with the
115 appropriate sign. */
116static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000117readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000118{
119 bool isNegative;
120 unsigned int absExponent;
121 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000122 StringRef::iterator p = begin;
123
124 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000125
Chris Lattner91702092009-03-12 23:59:55 +0000126 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000127 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000128 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000129 assert(p != end && "Exponent has no digits");
130 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000131
Chris Lattner91702092009-03-12 23:59:55 +0000132 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000133 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000134
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000135 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000136 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000137
Chris Lattner91702092009-03-12 23:59:55 +0000138 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000139 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000140
Chris Lattner91702092009-03-12 23:59:55 +0000141 value += absExponent * 10;
142 if (absExponent >= overlargeExponent) {
143 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000144 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000145 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000146 }
Chris Lattner91702092009-03-12 23:59:55 +0000147 absExponent = value;
148 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000149
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000150 assert(p == end && "Invalid exponent in exponent");
151
Chris Lattner91702092009-03-12 23:59:55 +0000152 if (isNegative)
153 return -(int) absExponent;
154 else
155 return (int) absExponent;
156}
157
158/* This is ugly and needs cleaning up, but I don't immediately see
159 how whilst remaining safe. */
160static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000161totalExponent(StringRef::iterator p, StringRef::iterator end,
162 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000163{
164 int unsignedExponent;
165 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000166 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000167
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000168 assert(p != end && "Exponent has no digits");
169
Chris Lattner91702092009-03-12 23:59:55 +0000170 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000171 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000172 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000173 assert(p != end && "Exponent has no digits");
174 }
Chris Lattner91702092009-03-12 23:59:55 +0000175
176 unsignedExponent = 0;
177 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000178 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000179 unsigned int value;
180
181 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000182 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000183
Chris Lattner91702092009-03-12 23:59:55 +0000184 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000185 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000186 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000187 break;
188 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000189 }
190
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000191 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000192 overflow = true;
193
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000194 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000195 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000196 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000197 exponent = -exponent;
198 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000199 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000200 overflow = true;
201 }
202
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000203 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000204 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000205
206 return exponent;
207}
208
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000209static StringRef::iterator
210skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
211 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000212{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000213 StringRef::iterator p = begin;
214 *dot = end;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000215 while (*p == '0' && p != end)
Chris Lattner91702092009-03-12 23:59:55 +0000216 p++;
217
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000218 if (*p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000219 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000220
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000221 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000222
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000223 while (*p == '0' && p != end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000224 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000225 }
226
Chris Lattner91702092009-03-12 23:59:55 +0000227 return p;
228}
Neil Booth4ed401b2007-10-14 10:16:12 +0000229
Chris Lattner91702092009-03-12 23:59:55 +0000230/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000231
Chris Lattner91702092009-03-12 23:59:55 +0000232 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000233
Chris Lattner91702092009-03-12 23:59:55 +0000234 where the decimal point and exponent are optional, fill out the
235 structure D. Exponent is appropriate if the significand is
236 treated as an integer, and normalizedExponent if the significand
237 is taken to have the decimal point after a single leading
238 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000239
Chris Lattner91702092009-03-12 23:59:55 +0000240 If the value is zero, V->firstSigDigit points to a non-digit, and
241 the return exponent is zero.
242*/
243struct decimalInfo {
244 const char *firstSigDigit;
245 const char *lastSigDigit;
246 int exponent;
247 int normalizedExponent;
248};
Neil Booth4ed401b2007-10-14 10:16:12 +0000249
Chris Lattner91702092009-03-12 23:59:55 +0000250static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000251interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
252 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000253{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000254 StringRef::iterator dot = end;
255 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000256
Chris Lattner91702092009-03-12 23:59:55 +0000257 D->firstSigDigit = p;
258 D->exponent = 0;
259 D->normalizedExponent = 0;
260
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000261 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000262 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000263 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000264 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000265 if (p == end)
266 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000267 }
Chris Lattner91702092009-03-12 23:59:55 +0000268 if (decDigitValue(*p) >= 10U)
269 break;
Chris Lattner91702092009-03-12 23:59:55 +0000270 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000271
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000272 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000273 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
274 assert(p != begin && "Significand has no digits");
275 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000276
277 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000278 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000279
Chris Lattner91702092009-03-12 23:59:55 +0000280 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000281 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000282 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000283 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000284
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000285 /* If number is all zeroes accept any exponent. */
286 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000287 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000288 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000289 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000290 do
291 p--;
292 while (p != begin && *p == '0');
293 while (p != begin && *p == '.');
294 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000295
Chris Lattner91702092009-03-12 23:59:55 +0000296 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000297 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000298 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000299 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000300 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000301 }
302
Chris Lattner91702092009-03-12 23:59:55 +0000303 D->lastSigDigit = p;
304}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000305
Chris Lattner91702092009-03-12 23:59:55 +0000306/* Return the trailing fraction of a hexadecimal number.
307 DIGITVALUE is the first hex digit of the fraction, P points to
308 the next digit. */
309static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000310trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
311 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000312{
313 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000314
Chris Lattner91702092009-03-12 23:59:55 +0000315 /* If the first trailing digit isn't 0 or 8 we can work out the
316 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000317 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000318 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000319 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000320 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000321
Eli Friedmand2eb07a2013-07-17 22:17:29 +0000322 // Otherwise we need to find the first non-zero digit.
323 while (p != end && (*p == '0' || *p == '.'))
Chris Lattner91702092009-03-12 23:59:55 +0000324 p++;
325
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000326 assert(p != end && "Invalid trailing hexadecimal fraction!");
327
Chris Lattner91702092009-03-12 23:59:55 +0000328 hexDigit = hexDigitValue(*p);
329
330 /* If we ran off the end it is exactly zero or one-half, otherwise
331 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000332 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000333 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
334 else
335 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
336}
337
338/* Return the fraction lost were a bignum truncated losing the least
339 significant BITS bits. */
340static lostFraction
341lostFractionThroughTruncation(const integerPart *parts,
342 unsigned int partCount,
343 unsigned int bits)
344{
345 unsigned int lsb;
346
347 lsb = APInt::tcLSB(parts, partCount);
348
349 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000350 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000351 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000352 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000353 return lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000354 if (bits <= partCount * integerPartWidth &&
355 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000356 return lfMoreThanHalf;
357
358 return lfLessThanHalf;
359}
360
361/* Shift DST right BITS bits noting lost fraction. */
362static lostFraction
363shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
364{
365 lostFraction lost_fraction;
366
367 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
368
369 APInt::tcShiftRight(dst, parts, bits);
370
371 return lost_fraction;
372}
373
374/* Combine the effect of two lost fractions. */
375static lostFraction
376combineLostFractions(lostFraction moreSignificant,
377 lostFraction lessSignificant)
378{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000379 if (lessSignificant != lfExactlyZero) {
380 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000381 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000382 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000383 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000384 }
385
Chris Lattner91702092009-03-12 23:59:55 +0000386 return moreSignificant;
387}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000388
Chris Lattner91702092009-03-12 23:59:55 +0000389/* The error from the true value, in half-ulps, on multiplying two
390 floating point numbers, which differ from the value they
391 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
392 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000393
Chris Lattner91702092009-03-12 23:59:55 +0000394 See "How to Read Floating Point Numbers Accurately" by William D
395 Clinger. */
396static unsigned int
397HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
398{
399 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000400
Chris Lattner91702092009-03-12 23:59:55 +0000401 if (HUerr1 + HUerr2 == 0)
402 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
403 else
404 return inexactMultiply + 2 * (HUerr1 + HUerr2);
405}
Neil Booth8f1946f2007-10-03 22:26:02 +0000406
Chris Lattner91702092009-03-12 23:59:55 +0000407/* The number of ulps from the boundary (zero, or half if ISNEAREST)
408 when the least significant BITS are truncated. BITS cannot be
409 zero. */
410static integerPart
411ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
412{
413 unsigned int count, partBits;
414 integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000415
Evan Cheng67c90212009-10-27 21:35:42 +0000416 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000417
Chris Lattner91702092009-03-12 23:59:55 +0000418 bits--;
419 count = bits / integerPartWidth;
420 partBits = bits % integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000421
Chris Lattner91702092009-03-12 23:59:55 +0000422 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000423
Chris Lattner91702092009-03-12 23:59:55 +0000424 if (isNearest)
425 boundary = (integerPart) 1 << (partBits - 1);
426 else
427 boundary = 0;
428
429 if (count == 0) {
430 if (part - boundary <= boundary - part)
431 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000432 else
Chris Lattner91702092009-03-12 23:59:55 +0000433 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000434 }
435
Chris Lattner91702092009-03-12 23:59:55 +0000436 if (part == boundary) {
437 while (--count)
438 if (parts[count])
439 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000440
Chris Lattner91702092009-03-12 23:59:55 +0000441 return parts[0];
442 } else if (part == boundary - 1) {
443 while (--count)
444 if (~parts[count])
445 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000446
Chris Lattner91702092009-03-12 23:59:55 +0000447 return -parts[0];
448 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000449
Chris Lattner91702092009-03-12 23:59:55 +0000450 return ~(integerPart) 0; /* A lot. */
451}
Neil Boothb93d90e2007-10-12 16:02:31 +0000452
Chris Lattner91702092009-03-12 23:59:55 +0000453/* Place pow(5, power) in DST, and return the number of parts used.
454 DST must be at least one part larger than size of the answer. */
455static unsigned int
456powerOf5(integerPart *dst, unsigned int power)
457{
458 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
459 15625, 78125 };
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000460 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
461 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000462
Chris Lattner0bf18692009-03-13 00:03:51 +0000463 unsigned int partsCount[16] = { 1 };
Chris Lattner91702092009-03-12 23:59:55 +0000464 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
465 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000466 assert(power <= maxExponent);
467
468 p1 = dst;
469 p2 = scratch;
470
471 *p1 = firstEightPowers[power & 7];
472 power >>= 3;
473
474 result = 1;
475 pow5 = pow5s;
476
477 for (unsigned int n = 0; power; power >>= 1, n++) {
478 unsigned int pc;
479
480 pc = partsCount[n];
481
482 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
483 if (pc == 0) {
484 pc = partsCount[n - 1];
485 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
486 pc *= 2;
487 if (pow5[pc - 1] == 0)
488 pc--;
489 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000490 }
491
Chris Lattner91702092009-03-12 23:59:55 +0000492 if (power & 1) {
493 integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000494
Chris Lattner91702092009-03-12 23:59:55 +0000495 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
496 result += pc;
497 if (p2[result - 1] == 0)
498 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000499
Chris Lattner91702092009-03-12 23:59:55 +0000500 /* Now result is in p1 with partsCount parts and p2 is scratch
501 space. */
502 tmp = p1, p1 = p2, p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000503 }
504
Chris Lattner91702092009-03-12 23:59:55 +0000505 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000506 }
507
Chris Lattner91702092009-03-12 23:59:55 +0000508 if (p1 != dst)
509 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000510
Chris Lattner91702092009-03-12 23:59:55 +0000511 return result;
512}
Neil Boothb93d90e2007-10-12 16:02:31 +0000513
Chris Lattner91702092009-03-12 23:59:55 +0000514/* Zero at the end to avoid modular arithmetic when adding one; used
515 when rounding up during hexadecimal output. */
516static const char hexDigitsLower[] = "0123456789abcdef0";
517static const char hexDigitsUpper[] = "0123456789ABCDEF0";
518static const char infinityL[] = "infinity";
519static const char infinityU[] = "INFINITY";
520static const char NaNL[] = "nan";
521static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000522
Chris Lattner91702092009-03-12 23:59:55 +0000523/* Write out an integerPart in hexadecimal, starting with the most
524 significant nibble. Write out exactly COUNT hexdigits, return
525 COUNT. */
526static unsigned int
527partAsHex (char *dst, integerPart part, unsigned int count,
528 const char *hexDigitChars)
529{
530 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000531
Evan Cheng67c90212009-10-27 21:35:42 +0000532 assert(count != 0 && count <= integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000533
Chris Lattner91702092009-03-12 23:59:55 +0000534 part >>= (integerPartWidth - 4 * count);
535 while (count--) {
536 dst[count] = hexDigitChars[part & 0xf];
537 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000538 }
539
Chris Lattner91702092009-03-12 23:59:55 +0000540 return result;
541}
Neil Booth8f1946f2007-10-03 22:26:02 +0000542
Chris Lattner91702092009-03-12 23:59:55 +0000543/* Write out an unsigned decimal integer. */
544static char *
545writeUnsignedDecimal (char *dst, unsigned int n)
546{
547 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000548
Chris Lattner91702092009-03-12 23:59:55 +0000549 p = buff;
550 do
551 *p++ = '0' + n % 10;
552 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000553
Chris Lattner91702092009-03-12 23:59:55 +0000554 do
555 *dst++ = *--p;
556 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000557
Chris Lattner91702092009-03-12 23:59:55 +0000558 return dst;
559}
Neil Booth8f1946f2007-10-03 22:26:02 +0000560
Chris Lattner91702092009-03-12 23:59:55 +0000561/* Write out a signed decimal integer. */
562static char *
563writeSignedDecimal (char *dst, int value)
564{
565 if (value < 0) {
566 *dst++ = '-';
567 dst = writeUnsignedDecimal(dst, -(unsigned) value);
568 } else
569 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000570
Chris Lattner91702092009-03-12 23:59:55 +0000571 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000572}
573
574/* Constructors. */
575void
576APFloat::initialize(const fltSemantics *ourSemantics)
577{
578 unsigned int count;
579
580 semantics = ourSemantics;
581 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000582 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000583 significand.parts = new integerPart[count];
584}
585
586void
587APFloat::freeSignificand()
588{
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000589 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000590 delete [] significand.parts;
591}
592
593void
594APFloat::assign(const APFloat &rhs)
595{
596 assert(semantics == rhs.semantics);
597
598 sign = rhs.sign;
599 category = rhs.category;
600 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000601 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000602 copySignificand(rhs);
603}
604
605void
606APFloat::copySignificand(const APFloat &rhs)
607{
Michael Gottesman8136c382013-06-26 23:17:28 +0000608 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000609 assert(rhs.partCount() >= partCount());
610
611 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000612 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000613}
614
Neil Booth5fe658b2007-10-14 10:39:51 +0000615/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000616 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000617 which may not be ideal. If float, this is QNaN(0). */
John McCalldcb9a7a2010-02-28 02:51:25 +0000618void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Booth5fe658b2007-10-14 10:39:51 +0000619{
620 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000621 sign = Negative;
622
John McCallc12b1332010-02-28 12:49:50 +0000623 integerPart *significand = significandParts();
624 unsigned numParts = partCount();
625
John McCalldcb9a7a2010-02-28 02:51:25 +0000626 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000627 if (!fill || fill->getNumWords() < numParts)
628 APInt::tcSet(significand, 0, numParts);
629 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000630 APInt::tcAssign(significand, fill->getRawData(),
631 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000632
633 // Zero out the excess bits of the significand.
634 unsigned bitsToPreserve = semantics->precision - 1;
635 unsigned part = bitsToPreserve / 64;
636 bitsToPreserve %= 64;
637 significand[part] &= ((1ULL << bitsToPreserve) - 1);
638 for (part++; part != numParts; ++part)
639 significand[part] = 0;
640 }
641
642 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000643
644 if (SNaN) {
645 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000646 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000647
648 // If there are no bits set in the payload, we have to set
649 // *something* to make it a NaN instead of an infinity;
650 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000651 if (APInt::tcIsZero(significand, numParts))
652 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000653 } else {
654 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000655 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000656 }
John McCallc12b1332010-02-28 12:49:50 +0000657
658 // For x87 extended precision, we want to make a NaN, not a
659 // pseudo-NaN. Maybe we should expose the ability to make
660 // pseudo-NaNs?
661 if (semantics == &APFloat::x87DoubleExtended)
662 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000663}
664
665APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
666 const APInt *fill) {
667 APFloat value(Sem, uninitialized);
668 value.makeNaN(SNaN, Negative, fill);
669 return value;
Neil Booth5fe658b2007-10-14 10:39:51 +0000670}
671
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000672APFloat &
673APFloat::operator=(const APFloat &rhs)
674{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000675 if (this != &rhs) {
676 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000677 freeSignificand();
678 initialize(rhs.semantics);
679 }
680 assign(rhs);
681 }
682
683 return *this;
684}
685
Benjamin Kramer06f47782014-03-04 20:26:51 +0000686APFloat &
687APFloat::operator=(APFloat &&rhs) {
688 freeSignificand();
689
690 semantics = rhs.semantics;
691 significand = rhs.significand;
692 exponent = rhs.exponent;
693 category = rhs.category;
694 sign = rhs.sign;
695
696 rhs.semantics = &Bogus;
697 return *this;
698}
699
Dale Johannesena719a602007-08-24 00:56:33 +0000700bool
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000701APFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000702 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000703 (APInt::tcExtractBit(significandParts(),
704 semantics->precision - 1) == 0);
705}
706
707bool
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000708APFloat::isSmallest() const {
709 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000710 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000711 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000712 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000713 significandMSB() == 0;
714}
715
716bool APFloat::isSignificandAllOnes() const {
717 // Test if the significand excluding the integral bit is all ones. This allows
718 // us to test for binade boundaries.
719 const integerPart *Parts = significandParts();
720 const unsigned PartCount = partCount();
721 for (unsigned i = 0; i < PartCount - 1; i++)
722 if (~Parts[i])
723 return false;
724
725 // Set the unused high bits to all ones when we compare.
726 const unsigned NumHighBits =
727 PartCount*integerPartWidth - semantics->precision + 1;
728 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
729 "fill than integerPartWidth");
730 const integerPart HighBitFill =
731 ~integerPart(0) << (integerPartWidth - NumHighBits);
732 if (~(Parts[PartCount - 1] | HighBitFill))
733 return false;
734
735 return true;
736}
737
738bool APFloat::isSignificandAllZeros() const {
739 // Test if the significand excluding the integral bit is all zeros. This
740 // allows us to test for binade boundaries.
741 const integerPart *Parts = significandParts();
742 const unsigned PartCount = partCount();
743
744 for (unsigned i = 0; i < PartCount - 1; i++)
745 if (Parts[i])
746 return false;
747
748 const unsigned NumHighBits =
749 PartCount*integerPartWidth - semantics->precision + 1;
750 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
751 "clear than integerPartWidth");
752 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
753
754 if (Parts[PartCount - 1] & HighBitMask)
755 return false;
756
757 return true;
758}
759
760bool
761APFloat::isLargest() const {
762 // The largest number by magnitude in our format will be the floating point
763 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000764 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000765 && isSignificandAllOnes();
766}
767
768bool
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000769APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000770 if (this == &rhs)
771 return true;
772 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000773 category != rhs.category ||
774 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000775 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000776 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000777 return true;
Michael Gottesman8136c382013-06-26 23:17:28 +0000778 else if (isFiniteNonZero() && exponent!=rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000779 return false;
Dale Johannesena719a602007-08-24 00:56:33 +0000780 else {
Dale Johannesena719a602007-08-24 00:56:33 +0000781 int i= partCount();
782 const integerPart* p=significandParts();
783 const integerPart* q=rhs.significandParts();
784 for (; i>0; i--, p++, q++) {
785 if (*p != *q)
786 return false;
787 }
788 return true;
789 }
790}
791
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000792APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000793 initialize(&ourSemantics);
794 sign = 0;
Michael Gottesman30a90eb2013-07-27 21:49:21 +0000795 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000796 zeroSignificand();
797 exponent = ourSemantics.precision - 1;
798 significandParts()[0] = value;
799 normalize(rmNearestTiesToEven, lfExactlyZero);
800}
801
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000802APFloat::APFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000803 initialize(&ourSemantics);
804 category = fcZero;
805 sign = false;
806}
807
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000808APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
John McCalldcb9a7a2010-02-28 02:51:25 +0000809 // Allocates storage if necessary but does not initialize it.
810 initialize(&ourSemantics);
811}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000812
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000813APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000814 initialize(&ourSemantics);
815 convertFromString(text, rmNearestTiesToEven);
816}
817
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000818APFloat::APFloat(const APFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000819 initialize(rhs.semantics);
820 assign(rhs);
821}
822
Benjamin Kramer06f47782014-03-04 20:26:51 +0000823APFloat::APFloat(APFloat &&rhs) : semantics(&Bogus) {
824 *this = std::move(rhs);
825}
826
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000827APFloat::~APFloat()
828{
829 freeSignificand();
830}
831
Ted Kremenek6f30a072008-02-11 17:24:50 +0000832// Profile - This method 'profiles' an APFloat for use with FoldingSet.
833void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen54306fe2008-10-09 18:53:47 +0000834 ID.Add(bitcastToAPInt());
Ted Kremenek6f30a072008-02-11 17:24:50 +0000835}
836
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000837unsigned int
838APFloat::partCount() const
839{
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000840 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000841}
842
843unsigned int
844APFloat::semanticsPrecision(const fltSemantics &semantics)
845{
846 return semantics.precision;
847}
848
849const integerPart *
850APFloat::significandParts() const
851{
852 return const_cast<APFloat *>(this)->significandParts();
853}
854
855integerPart *
856APFloat::significandParts()
857{
Evan Cheng67c90212009-10-27 21:35:42 +0000858 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000859 return significand.parts;
860 else
861 return &significand.part;
862}
863
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000864void
865APFloat::zeroSignificand()
866{
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000867 APInt::tcSet(significandParts(), 0, partCount());
868}
869
870/* Increment an fcNormal floating point number's significand. */
871void
872APFloat::incrementSignificand()
873{
874 integerPart carry;
875
876 carry = APInt::tcIncrement(significandParts(), partCount());
877
878 /* Our callers should never cause us to overflow. */
879 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000880 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000881}
882
883/* Add the significand of the RHS. Returns the carry flag. */
884integerPart
885APFloat::addSignificand(const APFloat &rhs)
886{
887 integerPart *parts;
888
889 parts = significandParts();
890
891 assert(semantics == rhs.semantics);
892 assert(exponent == rhs.exponent);
893
894 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
895}
896
897/* Subtract the significand of the RHS with a borrow flag. Returns
898 the borrow flag. */
899integerPart
900APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
901{
902 integerPart *parts;
903
904 parts = significandParts();
905
906 assert(semantics == rhs.semantics);
907 assert(exponent == rhs.exponent);
908
909 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000910 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000911}
912
913/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
914 on to the full-precision result of the multiplication. Returns the
915 lost fraction. */
916lostFraction
917APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
918{
Neil Booth9acbf5a2007-09-26 21:33:42 +0000919 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000920 unsigned int partsCount, newPartsCount, precision;
921 integerPart *lhsSignificand;
922 integerPart scratch[4];
923 integerPart *fullSignificand;
924 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000925 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000926
927 assert(semantics == rhs.semantics);
928
929 precision = semantics->precision;
930 newPartsCount = partCountForBits(precision * 2);
931
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000932 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000933 fullSignificand = new integerPart[newPartsCount];
934 else
935 fullSignificand = scratch;
936
937 lhsSignificand = significandParts();
938 partsCount = partCount();
939
940 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000941 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000942
943 lost_fraction = lfExactlyZero;
944 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
945 exponent += rhs.exponent;
946
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000947 // Assume the operands involved in the multiplication are single-precision
948 // FP, and the two multiplicants are:
949 // *this = a23 . a22 ... a0 * 2^e1
950 // rhs = b23 . b22 ... b0 * 2^e2
951 // the result of multiplication is:
952 // *this = c47 c46 . c45 ... c0 * 2^(e1+e2)
953 // Note that there are two significant bits at the left-hand side of the
954 // radix point. Move the radix point toward left by one bit, and adjust
955 // exponent accordingly.
956 exponent += 1;
957
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000958 if (addend) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000959 // The intermediate result of the multiplication has "2 * precision"
960 // signicant bit; adjust the addend to be consistent with mul result.
961 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000962 Significand savedSignificand = significand;
963 const fltSemantics *savedSemantics = semantics;
964 fltSemantics extendedSemantics;
965 opStatus status;
966 unsigned int extendedPrecision;
967
968 /* Normalize our MSB. */
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000969 extendedPrecision = 2 * precision;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000970 if (omsb != extendedPrecision) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000971 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000972 APInt::tcShiftLeft(fullSignificand, newPartsCount,
973 extendedPrecision - omsb);
974 exponent -= extendedPrecision - omsb;
975 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000976
977 /* Create new semantics. */
978 extendedSemantics = *semantics;
979 extendedSemantics.precision = extendedPrecision;
980
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000981 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000982 significand.part = fullSignificand[0];
983 else
984 significand.parts = fullSignificand;
985 semantics = &extendedSemantics;
986
987 APFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000988 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000989 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000990 (void)status;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000991 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
992
993 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000994 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000995 fullSignificand[0] = significand.part;
996 significand = savedSignificand;
997 semantics = savedSemantics;
998
999 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1000 }
1001
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001002 // Convert the result having "2 * precision" significant-bits back to the one
1003 // having "precision" significant-bits. First, move the radix point from
1004 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1005 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
1006 exponent -= precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001007
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001008 // In case MSB resides at the left-hand side of radix point, shift the
1009 // mantissa right by some amount to make sure the MSB reside right before
1010 // the radix point (i.e. "MSB . rest-significant-bits").
1011 //
1012 // Note that the result is not normalized when "omsb < precision". So, the
1013 // caller needs to call APFloat::normalize() if normalized value is expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001014 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001015 unsigned int bits, significantParts;
1016 lostFraction lf;
1017
1018 bits = omsb - precision;
1019 significantParts = partCountForBits(omsb);
1020 lf = shiftRight(fullSignificand, significantParts, bits);
1021 lost_fraction = combineLostFractions(lf, lost_fraction);
1022 exponent += bits;
1023 }
1024
1025 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1026
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001027 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001028 delete [] fullSignificand;
1029
1030 return lost_fraction;
1031}
1032
1033/* Multiply the significands of LHS and RHS to DST. */
1034lostFraction
1035APFloat::divideSignificand(const APFloat &rhs)
1036{
1037 unsigned int bit, i, partsCount;
1038 const integerPart *rhsSignificand;
1039 integerPart *lhsSignificand, *dividend, *divisor;
1040 integerPart scratch[4];
1041 lostFraction lost_fraction;
1042
1043 assert(semantics == rhs.semantics);
1044
1045 lhsSignificand = significandParts();
1046 rhsSignificand = rhs.significandParts();
1047 partsCount = partCount();
1048
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001049 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001050 dividend = new integerPart[partsCount * 2];
1051 else
1052 dividend = scratch;
1053
1054 divisor = dividend + partsCount;
1055
1056 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001057 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001058 dividend[i] = lhsSignificand[i];
1059 divisor[i] = rhsSignificand[i];
1060 lhsSignificand[i] = 0;
1061 }
1062
1063 exponent -= rhs.exponent;
1064
1065 unsigned int precision = semantics->precision;
1066
1067 /* Normalize the divisor. */
1068 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001069 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001070 exponent += bit;
1071 APInt::tcShiftLeft(divisor, partsCount, bit);
1072 }
1073
1074 /* Normalize the dividend. */
1075 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001076 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001077 exponent -= bit;
1078 APInt::tcShiftLeft(dividend, partsCount, bit);
1079 }
1080
Neil Boothb93d90e2007-10-12 16:02:31 +00001081 /* Ensure the dividend >= divisor initially for the loop below.
1082 Incidentally, this means that the division loop below is
1083 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001084 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001085 exponent--;
1086 APInt::tcShiftLeft(dividend, partsCount, 1);
1087 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1088 }
1089
1090 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001091 for (bit = precision; bit; bit -= 1) {
1092 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001093 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1094 APInt::tcSetBit(lhsSignificand, bit - 1);
1095 }
1096
1097 APInt::tcShiftLeft(dividend, partsCount, 1);
1098 }
1099
1100 /* Figure out the lost fraction. */
1101 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1102
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001103 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001104 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001105 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001106 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001107 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001108 lost_fraction = lfExactlyZero;
1109 else
1110 lost_fraction = lfLessThanHalf;
1111
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001112 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001113 delete [] dividend;
1114
1115 return lost_fraction;
1116}
1117
1118unsigned int
1119APFloat::significandMSB() const
1120{
1121 return APInt::tcMSB(significandParts(), partCount());
1122}
1123
1124unsigned int
1125APFloat::significandLSB() const
1126{
1127 return APInt::tcLSB(significandParts(), partCount());
1128}
1129
1130/* Note that a zero result is NOT normalized to fcZero. */
1131lostFraction
1132APFloat::shiftSignificandRight(unsigned int bits)
1133{
1134 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001135 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001136
1137 exponent += bits;
1138
1139 return shiftRight(significandParts(), partCount(), bits);
1140}
1141
1142/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1143void
1144APFloat::shiftSignificandLeft(unsigned int bits)
1145{
1146 assert(bits < semantics->precision);
1147
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001148 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001149 unsigned int partsCount = partCount();
1150
1151 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1152 exponent -= bits;
1153
1154 assert(!APInt::tcIsZero(significandParts(), partsCount));
1155 }
1156}
1157
1158APFloat::cmpResult
1159APFloat::compareAbsoluteValue(const APFloat &rhs) const
1160{
1161 int compare;
1162
1163 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001164 assert(isFiniteNonZero());
1165 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001166
1167 compare = exponent - rhs.exponent;
1168
1169 /* If exponents are equal, do an unsigned bignum comparison of the
1170 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001171 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001172 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001173 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001174
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001175 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001176 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001177 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001178 return cmpLessThan;
1179 else
1180 return cmpEqual;
1181}
1182
1183/* Handle overflow. Sign is preserved. We either become infinity or
1184 the largest finite number. */
1185APFloat::opStatus
1186APFloat::handleOverflow(roundingMode rounding_mode)
1187{
1188 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001189 if (rounding_mode == rmNearestTiesToEven ||
1190 rounding_mode == rmNearestTiesToAway ||
1191 (rounding_mode == rmTowardPositive && !sign) ||
1192 (rounding_mode == rmTowardNegative && sign)) {
1193 category = fcInfinity;
1194 return (opStatus) (opOverflow | opInexact);
1195 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001196
1197 /* Otherwise we become the largest finite number. */
1198 category = fcNormal;
1199 exponent = semantics->maxExponent;
1200 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001201 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001202
1203 return opInexact;
1204}
1205
Neil Booth1ca1f802007-10-03 15:16:41 +00001206/* Returns TRUE if, when truncating the current number, with BIT the
1207 new LSB, with the given lost fraction and rounding mode, the result
1208 would need to be rounded away from zero (i.e., by increasing the
1209 signficand). This routine must work for fcZero of both signs, and
1210 fcNormal numbers. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001211bool
1212APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Booth1ca1f802007-10-03 15:16:41 +00001213 lostFraction lost_fraction,
1214 unsigned int bit) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001215{
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001216 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001217 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001218
Neil Booth1ca1f802007-10-03 15:16:41 +00001219 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001220 assert(lost_fraction != lfExactlyZero);
1221
Mike Stump889285d2009-05-13 23:23:20 +00001222 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001223 case rmNearestTiesToAway:
1224 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1225
1226 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001227 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001228 return true;
1229
1230 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001231 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001232 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001233
1234 return false;
1235
1236 case rmTowardZero:
1237 return false;
1238
1239 case rmTowardPositive:
1240 return sign == false;
1241
1242 case rmTowardNegative:
1243 return sign == true;
1244 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001245 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001246}
1247
1248APFloat::opStatus
1249APFloat::normalize(roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001250 lostFraction lost_fraction)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001251{
Neil Booth9acbf5a2007-09-26 21:33:42 +00001252 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001253 int exponentChange;
1254
Michael Gottesman8136c382013-06-26 23:17:28 +00001255 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001256 return opOK;
1257
1258 /* Before rounding normalize the exponent of fcNormal numbers. */
1259 omsb = significandMSB() + 1;
1260
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001261 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001262 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001263 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001264 the exponent. */
1265 exponentChange = omsb - semantics->precision;
1266
1267 /* If the resulting exponent is too high, overflow according to
1268 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001269 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001270 return handleOverflow(rounding_mode);
1271
1272 /* Subnormal numbers have exponent minExponent, and their MSB
1273 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001274 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001275 exponentChange = semantics->minExponent - exponent;
1276
1277 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001278 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001279 assert(lost_fraction == lfExactlyZero);
1280
1281 shiftSignificandLeft(-exponentChange);
1282
1283 return opOK;
1284 }
1285
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001286 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001287 lostFraction lf;
1288
1289 /* Shift right and capture any new lost fraction. */
1290 lf = shiftSignificandRight(exponentChange);
1291
1292 lost_fraction = combineLostFractions(lf, lost_fraction);
1293
1294 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001295 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001296 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001297 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001298 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001299 }
1300 }
1301
1302 /* Now round the number according to rounding_mode given the lost
1303 fraction. */
1304
1305 /* As specified in IEEE 754, since we do not trap we do not report
1306 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001307 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001308 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001309 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001310 category = fcZero;
1311
1312 return opOK;
1313 }
1314
1315 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001316 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1317 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001318 exponent = semantics->minExponent;
1319
1320 incrementSignificand();
1321 omsb = significandMSB() + 1;
1322
1323 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001324 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001325 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001326 significand right one. However if we already have the
1327 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001328 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001329 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001330
Neil Booth9acbf5a2007-09-26 21:33:42 +00001331 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001332 }
1333
1334 shiftSignificandRight(1);
1335
1336 return opInexact;
1337 }
1338 }
1339
1340 /* The normal case - we were and are not denormal, and any
1341 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001342 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001343 return opInexact;
1344
1345 /* We have a non-zero denormal. */
1346 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001347
1348 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001349 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001350 category = fcZero;
1351
1352 /* The fcZero case is a denormal that underflowed to zero. */
1353 return (opStatus) (opUnderflow | opInexact);
1354}
1355
1356APFloat::opStatus
1357APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1358{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001359 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001360 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001361 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001362
Michael Gottesman9b877e12013-06-24 09:57:57 +00001363 case PackCategoriesIntoKey(fcNaN, fcZero):
1364 case PackCategoriesIntoKey(fcNaN, fcNormal):
1365 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1366 case PackCategoriesIntoKey(fcNaN, fcNaN):
1367 case PackCategoriesIntoKey(fcNormal, fcZero):
1368 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1369 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001370 return opOK;
1371
Michael Gottesman9b877e12013-06-24 09:57:57 +00001372 case PackCategoriesIntoKey(fcZero, fcNaN):
1373 case PackCategoriesIntoKey(fcNormal, fcNaN):
1374 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001375 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001376 category = fcNaN;
1377 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001378 return opOK;
1379
Michael Gottesman9b877e12013-06-24 09:57:57 +00001380 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1381 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001382 category = fcInfinity;
1383 sign = rhs.sign ^ subtract;
1384 return opOK;
1385
Michael Gottesman9b877e12013-06-24 09:57:57 +00001386 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001387 assign(rhs);
1388 sign = rhs.sign ^ subtract;
1389 return opOK;
1390
Michael Gottesman9b877e12013-06-24 09:57:57 +00001391 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001392 /* Sign depends on rounding mode; handled by caller. */
1393 return opOK;
1394
Michael Gottesman9b877e12013-06-24 09:57:57 +00001395 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001396 /* Differently signed infinities can only be validly
1397 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001398 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001399 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001400 return opInvalidOp;
1401 }
1402
1403 return opOK;
1404
Michael Gottesman9b877e12013-06-24 09:57:57 +00001405 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001406 return opDivByZero;
1407 }
1408}
1409
1410/* Add or subtract two normal numbers. */
1411lostFraction
1412APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1413{
1414 integerPart carry;
1415 lostFraction lost_fraction;
1416 int bits;
1417
1418 /* Determine if the operation on the absolute values is effectively
1419 an addition or subtraction. */
Hartmut Kaiserfc69d322007-10-25 23:15:31 +00001420 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001421
1422 /* Are we bigger exponent-wise than the RHS? */
1423 bits = exponent - rhs.exponent;
1424
1425 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001426 if (subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001427 APFloat temp_rhs(rhs);
1428 bool reverse;
1429
Chris Lattner3da18eb2007-08-24 03:02:34 +00001430 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001431 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1432 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001433 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001434 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1435 shiftSignificandLeft(1);
1436 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001437 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001438 lost_fraction = shiftSignificandRight(-bits - 1);
1439 temp_rhs.shiftSignificandLeft(1);
1440 reverse = true;
1441 }
1442
Chris Lattner3da18eb2007-08-24 03:02:34 +00001443 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001444 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001445 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001446 copySignificand(temp_rhs);
1447 sign = !sign;
1448 } else {
1449 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001450 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001451 }
1452
1453 /* Invert the lost fraction - it was on the RHS and
1454 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001455 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001456 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001457 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001458 lost_fraction = lfLessThanHalf;
1459
1460 /* The code above is intended to ensure that no borrow is
1461 necessary. */
1462 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001463 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001464 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001465 if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001466 APFloat temp_rhs(rhs);
1467
1468 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1469 carry = addSignificand(temp_rhs);
1470 } else {
1471 lost_fraction = shiftSignificandRight(-bits);
1472 carry = addSignificand(rhs);
1473 }
1474
1475 /* We have a guard bit; generating a carry cannot happen. */
1476 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001477 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001478 }
1479
1480 return lost_fraction;
1481}
1482
1483APFloat::opStatus
1484APFloat::multiplySpecials(const APFloat &rhs)
1485{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001486 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001487 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001488 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001489
Michael Gottesman9b877e12013-06-24 09:57:57 +00001490 case PackCategoriesIntoKey(fcNaN, fcZero):
1491 case PackCategoriesIntoKey(fcNaN, fcNormal):
1492 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1493 case PackCategoriesIntoKey(fcNaN, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001494 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001495 return opOK;
1496
Michael Gottesman9b877e12013-06-24 09:57:57 +00001497 case PackCategoriesIntoKey(fcZero, fcNaN):
1498 case PackCategoriesIntoKey(fcNormal, fcNaN):
1499 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001500 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001501 category = fcNaN;
1502 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001503 return opOK;
1504
Michael Gottesman9b877e12013-06-24 09:57:57 +00001505 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1506 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1507 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001508 category = fcInfinity;
1509 return opOK;
1510
Michael Gottesman9b877e12013-06-24 09:57:57 +00001511 case PackCategoriesIntoKey(fcZero, fcNormal):
1512 case PackCategoriesIntoKey(fcNormal, fcZero):
1513 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001514 category = fcZero;
1515 return opOK;
1516
Michael Gottesman9b877e12013-06-24 09:57:57 +00001517 case PackCategoriesIntoKey(fcZero, fcInfinity):
1518 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001519 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001520 return opInvalidOp;
1521
Michael Gottesman9b877e12013-06-24 09:57:57 +00001522 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001523 return opOK;
1524 }
1525}
1526
1527APFloat::opStatus
1528APFloat::divideSpecials(const APFloat &rhs)
1529{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001530 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001531 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001532 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001533
Michael Gottesman9b877e12013-06-24 09:57:57 +00001534 case PackCategoriesIntoKey(fcZero, fcNaN):
1535 case PackCategoriesIntoKey(fcNormal, fcNaN):
1536 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001537 category = fcNaN;
1538 copySignificand(rhs);
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001539 case PackCategoriesIntoKey(fcNaN, fcZero):
1540 case PackCategoriesIntoKey(fcNaN, fcNormal):
1541 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1542 case PackCategoriesIntoKey(fcNaN, fcNaN):
1543 sign = false;
1544 case PackCategoriesIntoKey(fcInfinity, fcZero):
1545 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1546 case PackCategoriesIntoKey(fcZero, fcInfinity):
1547 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001548 return opOK;
1549
Michael Gottesman9b877e12013-06-24 09:57:57 +00001550 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001551 category = fcZero;
1552 return opOK;
1553
Michael Gottesman9b877e12013-06-24 09:57:57 +00001554 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001555 category = fcInfinity;
1556 return opDivByZero;
1557
Michael Gottesman9b877e12013-06-24 09:57:57 +00001558 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1559 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001560 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001561 return opInvalidOp;
1562
Michael Gottesman9b877e12013-06-24 09:57:57 +00001563 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001564 return opOK;
1565 }
1566}
1567
Dale Johannesenb5721632009-01-21 00:35:19 +00001568APFloat::opStatus
1569APFloat::modSpecials(const APFloat &rhs)
1570{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001571 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001572 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001573 llvm_unreachable(nullptr);
Dale Johannesenb5721632009-01-21 00:35:19 +00001574
Michael Gottesman9b877e12013-06-24 09:57:57 +00001575 case PackCategoriesIntoKey(fcNaN, fcZero):
1576 case PackCategoriesIntoKey(fcNaN, fcNormal):
1577 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1578 case PackCategoriesIntoKey(fcNaN, fcNaN):
1579 case PackCategoriesIntoKey(fcZero, fcInfinity):
1580 case PackCategoriesIntoKey(fcZero, fcNormal):
1581 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001582 return opOK;
1583
Michael Gottesman9b877e12013-06-24 09:57:57 +00001584 case PackCategoriesIntoKey(fcZero, fcNaN):
1585 case PackCategoriesIntoKey(fcNormal, fcNaN):
1586 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001587 sign = false;
Dale Johannesenb5721632009-01-21 00:35:19 +00001588 category = fcNaN;
1589 copySignificand(rhs);
1590 return opOK;
1591
Michael Gottesman9b877e12013-06-24 09:57:57 +00001592 case PackCategoriesIntoKey(fcNormal, fcZero):
1593 case PackCategoriesIntoKey(fcInfinity, fcZero):
1594 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1595 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1596 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001597 makeNaN();
1598 return opInvalidOp;
1599
Michael Gottesman9b877e12013-06-24 09:57:57 +00001600 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001601 return opOK;
1602 }
1603}
1604
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001605/* Change sign. */
1606void
1607APFloat::changeSign()
1608{
1609 /* Look mummy, this one's easy. */
1610 sign = !sign;
1611}
1612
Dale Johannesen689d17d2007-08-31 23:35:31 +00001613void
1614APFloat::clearSign()
1615{
1616 /* So is this one. */
1617 sign = 0;
1618}
1619
1620void
1621APFloat::copySign(const APFloat &rhs)
1622{
1623 /* And this one. */
1624 sign = rhs.sign;
1625}
1626
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001627/* Normalized addition or subtraction. */
1628APFloat::opStatus
1629APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001630 bool subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001631{
1632 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. */
1659APFloat::opStatus
1660APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1661{
1662 return addOrSubtract(rhs, rounding_mode, false);
1663}
1664
1665/* Normalized subtraction. */
1666APFloat::opStatus
1667APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1668{
1669 return addOrSubtract(rhs, rounding_mode, true);
1670}
1671
1672/* Normalized multiply. */
1673APFloat::opStatus
1674APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1675{
1676 opStatus fs;
1677
1678 sign ^= rhs.sign;
1679 fs = multiplySpecials(rhs);
1680
Michael Gottesman8136c382013-06-26 23:17:28 +00001681 if (isFiniteNonZero()) {
Craig Topperc10719f2014-04-07 04:17:22 +00001682 lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001683 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001684 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001685 fs = (opStatus) (fs | opInexact);
1686 }
1687
1688 return fs;
1689}
1690
1691/* Normalized divide. */
1692APFloat::opStatus
1693APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1694{
1695 opStatus fs;
1696
1697 sign ^= rhs.sign;
1698 fs = divideSpecials(rhs);
1699
Michael Gottesman8136c382013-06-26 23:17:28 +00001700 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001701 lostFraction lost_fraction = divideSignificand(rhs);
1702 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001703 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001704 fs = (opStatus) (fs | opInexact);
1705 }
1706
1707 return fs;
1708}
1709
Dale Johannesenfe750172009-01-20 18:35:05 +00001710/* Normalized remainder. This is not currently correct in all cases. */
1711APFloat::opStatus
1712APFloat::remainder(const APFloat &rhs)
1713{
1714 opStatus fs;
1715 APFloat V = *this;
1716 unsigned int origSign = sign;
1717
Dale Johannesenfe750172009-01-20 18:35:05 +00001718 fs = V.divide(rhs, rmNearestTiesToEven);
1719 if (fs == opDivByZero)
1720 return fs;
1721
1722 int parts = partCount();
1723 integerPart *x = new integerPart[parts];
1724 bool ignored;
1725 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1726 rmNearestTiesToEven, &ignored);
1727 if (fs==opInvalidOp)
1728 return fs;
1729
1730 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1731 rmNearestTiesToEven);
1732 assert(fs==opOK); // should always work
1733
1734 fs = V.multiply(rhs, rmNearestTiesToEven);
1735 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1736
1737 fs = subtract(V, rmNearestTiesToEven);
1738 assert(fs==opOK || fs==opInexact); // likewise
1739
1740 if (isZero())
1741 sign = origSign; // IEEE754 requires this
1742 delete[] x;
1743 return fs;
1744}
1745
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001746/* Normalized llvm frem (C fmod).
Dale Johannesenfe750172009-01-20 18:35:05 +00001747 This is not currently correct in all cases. */
Dale Johannesen689d17d2007-08-31 23:35:31 +00001748APFloat::opStatus
1749APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1750{
1751 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001752 fs = modSpecials(rhs);
Dale Johannesen689d17d2007-08-31 23:35:31 +00001753
Michael Gottesman8136c382013-06-26 23:17:28 +00001754 if (isFiniteNonZero() && rhs.isFiniteNonZero()) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001755 APFloat V = *this;
1756 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001757
Dale Johannesenb5721632009-01-21 00:35:19 +00001758 fs = V.divide(rhs, rmNearestTiesToEven);
1759 if (fs == opDivByZero)
1760 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001761
Dale Johannesenb5721632009-01-21 00:35:19 +00001762 int parts = partCount();
1763 integerPart *x = new integerPart[parts];
1764 bool ignored;
1765 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1766 rmTowardZero, &ignored);
1767 if (fs==opInvalidOp)
1768 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001769
Dale Johannesenb5721632009-01-21 00:35:19 +00001770 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1771 rmNearestTiesToEven);
1772 assert(fs==opOK); // should always work
Dale Johannesen728687c2007-09-05 20:39:49 +00001773
Dale Johannesenb5721632009-01-21 00:35:19 +00001774 fs = V.multiply(rhs, rounding_mode);
1775 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1776
1777 fs = subtract(V, rounding_mode);
1778 assert(fs==opOK || fs==opInexact); // likewise
1779
1780 if (isZero())
1781 sign = origSign; // IEEE754 requires this
1782 delete[] x;
1783 }
Dale Johannesen689d17d2007-08-31 23:35:31 +00001784 return fs;
1785}
1786
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001787/* Normalized fused-multiply-add. */
1788APFloat::opStatus
1789APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001790 const APFloat &addend,
1791 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001792{
1793 opStatus fs;
1794
1795 /* Post-multiplication sign, before addition. */
1796 sign ^= multiplicand.sign;
1797
1798 /* If and only if all arguments are normal do we need to do an
1799 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001800 if (isFiniteNonZero() &&
1801 multiplicand.isFiniteNonZero() &&
1802 addend.isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001803 lostFraction lost_fraction;
1804
1805 lost_fraction = multiplySignificand(multiplicand, &addend);
1806 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001807 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001808 fs = (opStatus) (fs | opInexact);
1809
1810 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1811 positive zero unless rounding to minus infinity, except that
1812 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001813 if (category == fcZero && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001814 sign = (rounding_mode == rmTowardNegative);
1815 } else {
1816 fs = multiplySpecials(multiplicand);
1817
1818 /* FS can only be opOK or opInvalidOp. There is no more work
1819 to do in the latter case. The IEEE-754R standard says it is
1820 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001821 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001822
1823 If we need to do the addition we can do so with normal
1824 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001825 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001826 fs = addOrSubtract(addend, rounding_mode, false);
1827 }
1828
1829 return fs;
1830}
1831
Owen Andersona40319b2012-08-13 23:32:49 +00001832/* Rounding-mode corrrect round to integral value. */
1833APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
1834 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001835
Owen Anderson352dfff2012-08-15 18:28:45 +00001836 // If the exponent is large enough, we know that this value is already
1837 // integral, and the arithmetic below would potentially cause it to saturate
1838 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001839 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001840 return opOK;
1841
Owen Andersona40319b2012-08-13 23:32:49 +00001842 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1843 // precision of our format, and then subtract it back off again. The choice
1844 // of rounding modes for the addition/subtraction determines the rounding mode
1845 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001846 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001847 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001848 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1849 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Owen Andersona40319b2012-08-13 23:32:49 +00001850 APFloat MagicConstant(*semantics);
1851 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1852 rmNearestTiesToEven);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001853 MagicConstant.copySign(*this);
1854
Owen Andersona40319b2012-08-13 23:32:49 +00001855 if (fs != opOK)
1856 return fs;
1857
Owen Anderson1ff74b02012-08-15 05:39:46 +00001858 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1859 bool inputSign = isNegative();
1860
Owen Andersona40319b2012-08-13 23:32:49 +00001861 fs = add(MagicConstant, rounding_mode);
1862 if (fs != opOK && fs != opInexact)
1863 return fs;
1864
1865 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001866
1867 // Restore the input sign.
1868 if (inputSign != isNegative())
1869 changeSign();
1870
Owen Andersona40319b2012-08-13 23:32:49 +00001871 return fs;
1872}
1873
1874
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001875/* Comparison requires normalized numbers. */
1876APFloat::cmpResult
1877APFloat::compare(const APFloat &rhs) const
1878{
1879 cmpResult result;
1880
1881 assert(semantics == rhs.semantics);
1882
Michael Gottesman9b877e12013-06-24 09:57:57 +00001883 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001884 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001885 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001886
Michael Gottesman9b877e12013-06-24 09:57:57 +00001887 case PackCategoriesIntoKey(fcNaN, fcZero):
1888 case PackCategoriesIntoKey(fcNaN, fcNormal):
1889 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1890 case PackCategoriesIntoKey(fcNaN, fcNaN):
1891 case PackCategoriesIntoKey(fcZero, fcNaN):
1892 case PackCategoriesIntoKey(fcNormal, fcNaN):
1893 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001894 return cmpUnordered;
1895
Michael Gottesman9b877e12013-06-24 09:57:57 +00001896 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1897 case PackCategoriesIntoKey(fcInfinity, fcZero):
1898 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001899 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001900 return cmpLessThan;
1901 else
1902 return cmpGreaterThan;
1903
Michael Gottesman9b877e12013-06-24 09:57:57 +00001904 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1905 case PackCategoriesIntoKey(fcZero, fcInfinity):
1906 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001907 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001908 return cmpGreaterThan;
1909 else
1910 return cmpLessThan;
1911
Michael Gottesman9b877e12013-06-24 09:57:57 +00001912 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001913 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001914 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001915 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001916 return cmpLessThan;
1917 else
1918 return cmpGreaterThan;
1919
Michael Gottesman9b877e12013-06-24 09:57:57 +00001920 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001921 return cmpEqual;
1922
Michael Gottesman9b877e12013-06-24 09:57:57 +00001923 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001924 break;
1925 }
1926
1927 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001928 if (sign != rhs.sign) {
1929 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001930 result = cmpLessThan;
1931 else
1932 result = cmpGreaterThan;
1933 } else {
1934 /* Compare absolute values; invert result if negative. */
1935 result = compareAbsoluteValue(rhs);
1936
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001937 if (sign) {
1938 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001939 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001940 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001941 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001942 }
1943 }
1944
1945 return result;
1946}
1947
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001948/// APFloat::convert - convert a value of one floating point type to another.
1949/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1950/// records whether the transformation lost information, i.e. whether
1951/// converting the result back to the original type will produce the
1952/// original value (this is almost the same as return value==fsOK, but there
1953/// are edge cases where this is not so).
1954
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001955APFloat::opStatus
1956APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001957 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001958{
Neil Bootha8d72692007-09-22 02:56:19 +00001959 lostFraction lostFraction;
1960 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001961 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001962 int shift;
1963 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001964
Neil Bootha8d72692007-09-22 02:56:19 +00001965 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001966 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001967 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001968 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001969
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001970 bool X86SpecialNan = false;
1971 if (&fromSemantics == &APFloat::x87DoubleExtended &&
1972 &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
1973 (!(*significandParts() & 0x8000000000000000ULL) ||
1974 !(*significandParts() & 0x4000000000000000ULL))) {
1975 // x86 has some unusual NaNs which cannot be represented in any other
1976 // format; note them here.
1977 X86SpecialNan = true;
1978 }
1979
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00001980 // If this is a truncation of a denormal number, and the target semantics
1981 // has larger exponent range than the source semantics (this can happen
1982 // when truncating from PowerPC double-double to double format), the
1983 // right shift could lose result mantissa bits. Adjust exponent instead
1984 // of performing excessive shift.
1985 if (shift < 0 && isFiniteNonZero()) {
1986 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1987 if (exponent + exponentChange < toSemantics.minExponent)
1988 exponentChange = toSemantics.minExponent - exponent;
1989 if (exponentChange < shift)
1990 exponentChange = shift;
1991 if (exponentChange < 0) {
1992 shift -= exponentChange;
1993 exponent += exponentChange;
1994 }
1995 }
1996
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001997 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00001998 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001999 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
2000
2001 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00002002 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002003 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002004 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002005 newParts = new integerPart[newPartCount];
2006 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00002007 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002008 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002009 freeSignificand();
2010 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002011 } else if (newPartCount == 1 && oldPartCount != 1) {
2012 // Switch to built-in storage for a single part.
2013 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00002014 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002015 newPart = significandParts()[0];
2016 freeSignificand();
2017 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002018 }
2019
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002020 // Now that we have the right storage, switch the semantics.
2021 semantics = &toSemantics;
2022
2023 // If this is an extension, perform the shift now that the storage is
2024 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00002025 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002026 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2027
Michael Gottesman8136c382013-06-26 23:17:28 +00002028 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00002029 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002030 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002031 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002032 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002033
2034 // For x87 extended precision, we want to make a NaN, not a special NaN if
2035 // the input wasn't special either.
2036 if (!X86SpecialNan && semantics == &APFloat::x87DoubleExtended)
2037 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2038
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002039 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2040 // does not give you back the same bits. This is dubious, and we
2041 // don't currently do it. You're really supposed to get
2042 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002043 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002044 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002045 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002046 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002047 }
2048
2049 return fs;
2050}
2051
2052/* Convert a floating point number to an integer according to the
2053 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002054 returns an invalid operation exception and the contents of the
2055 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002056 range but the floating point number is not the exact integer, the C
2057 standard doesn't require an inexact exception to be raised. IEEE
2058 854 does require it so we do that.
2059
2060 Note that for conversions to integer type the C standard requires
2061 round-to-zero to always be used. */
2062APFloat::opStatus
Neil Booth618d0fc2007-11-01 22:43:37 +00002063APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
2064 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002065 roundingMode rounding_mode,
2066 bool *isExact) const
Neil Booth618d0fc2007-11-01 22:43:37 +00002067{
2068 lostFraction lost_fraction;
2069 const integerPart *src;
2070 unsigned int dstPartsCount, truncatedBits;
2071
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002072 *isExact = false;
2073
Neil Booth618d0fc2007-11-01 22:43:37 +00002074 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002075 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002076 return opInvalidOp;
2077
2078 dstPartsCount = partCountForBits(width);
2079
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002080 if (category == fcZero) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002081 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002082 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002083 *isExact = !sign;
2084 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002085 }
2086
2087 src = significandParts();
2088
2089 /* Step 1: place our absolute value, with any fraction truncated, in
2090 the destination. */
2091 if (exponent < 0) {
2092 /* Our absolute value is less than one; truncate everything. */
2093 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002094 /* For exponent -1 the integer bit represents .5, look at that.
2095 For smaller exponents leftmost truncated bit is 0. */
2096 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002097 } else {
2098 /* We want the most significant (exponent + 1) bits; the rest are
2099 truncated. */
2100 unsigned int bits = exponent + 1U;
2101
2102 /* Hopelessly large in magnitude? */
2103 if (bits > width)
2104 return opInvalidOp;
2105
2106 if (bits < semantics->precision) {
2107 /* We truncate (semantics->precision - bits) bits. */
2108 truncatedBits = semantics->precision - bits;
2109 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2110 } else {
2111 /* We want at least as many bits as are available. */
2112 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2113 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2114 truncatedBits = 0;
2115 }
2116 }
2117
2118 /* Step 2: work out any lost fraction, and increment the absolute
2119 value if we would round away from zero. */
2120 if (truncatedBits) {
2121 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2122 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002123 if (lost_fraction != lfExactlyZero &&
2124 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002125 if (APInt::tcIncrement(parts, dstPartsCount))
2126 return opInvalidOp; /* Overflow. */
2127 }
2128 } else {
2129 lost_fraction = lfExactlyZero;
2130 }
2131
2132 /* Step 3: check if we fit in the destination. */
2133 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2134
2135 if (sign) {
2136 if (!isSigned) {
2137 /* Negative numbers cannot be represented as unsigned. */
2138 if (omsb != 0)
2139 return opInvalidOp;
2140 } else {
2141 /* It takes omsb bits to represent the unsigned integer value.
2142 We lose a bit for the sign, but care is needed as the
2143 maximally negative integer is a special case. */
2144 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2145 return opInvalidOp;
2146
2147 /* This case can happen because of rounding. */
2148 if (omsb > width)
2149 return opInvalidOp;
2150 }
2151
2152 APInt::tcNegate (parts, dstPartsCount);
2153 } else {
2154 if (omsb >= width + !isSigned)
2155 return opInvalidOp;
2156 }
2157
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002158 if (lost_fraction == lfExactlyZero) {
2159 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002160 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002161 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002162 return opInexact;
2163}
2164
2165/* Same as convertToSignExtendedInteger, except we provide
2166 deterministic values in case of an invalid operation exception,
2167 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002168 for underflow or overflow.
2169 The *isExact output tells whether the result is exact, in the sense
2170 that converting it back to the original floating point type produces
2171 the original value. This is almost equivalent to result==opOK,
2172 except for negative zeroes.
2173*/
Neil Booth618d0fc2007-11-01 22:43:37 +00002174APFloat::opStatus
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002175APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth9acbf5a2007-09-26 21:33:42 +00002176 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002177 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002178{
Neil Booth618d0fc2007-11-01 22:43:37 +00002179 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002180
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002181 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002182 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002183
Neil Booth618d0fc2007-11-01 22:43:37 +00002184 if (fs == opInvalidOp) {
2185 unsigned int bits, dstPartsCount;
2186
2187 dstPartsCount = partCountForBits(width);
2188
2189 if (category == fcNaN)
2190 bits = 0;
2191 else if (sign)
2192 bits = isSigned;
2193 else
2194 bits = width - isSigned;
2195
2196 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2197 if (sign && isSigned)
2198 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002199 }
2200
Neil Booth618d0fc2007-11-01 22:43:37 +00002201 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002202}
2203
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002204/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2205 an APSInt, whose initial bit-width and signed-ness are used to determine the
2206 precision of the conversion.
2207 */
2208APFloat::opStatus
2209APFloat::convertToInteger(APSInt &result,
2210 roundingMode rounding_mode, bool *isExact) const
2211{
2212 unsigned bitWidth = result.getBitWidth();
2213 SmallVector<uint64_t, 4> parts(result.getNumWords());
2214 opStatus status = convertToInteger(
2215 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2216 // Keeps the original signed-ness.
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002217 result = APInt(bitWidth, parts);
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002218 return status;
2219}
2220
Neil Booth6c1c8582007-10-07 12:07:53 +00002221/* Convert an unsigned integer SRC to a floating point number,
2222 rounding according to ROUNDING_MODE. The sign of the floating
2223 point number is not modified. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002224APFloat::opStatus
Neil Booth6c1c8582007-10-07 12:07:53 +00002225APFloat::convertFromUnsignedParts(const integerPart *src,
2226 unsigned int srcCount,
2227 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002228{
Neil Booth49c6aab2007-10-08 14:39:42 +00002229 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002230 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002231 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002232
2233 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002234 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002235 dst = significandParts();
2236 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002237 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002238
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002239 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002240 be that many; extract what we can. */
2241 if (precision <= omsb) {
2242 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002243 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002244 omsb - precision);
2245 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2246 } else {
2247 exponent = precision - 1;
2248 lost_fraction = lfExactlyZero;
2249 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002250 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002251
2252 return normalize(rounding_mode, lost_fraction);
2253}
2254
Dan Gohman35723eb2008-02-29 01:26:11 +00002255APFloat::opStatus
2256APFloat::convertFromAPInt(const APInt &Val,
2257 bool isSigned,
2258 roundingMode rounding_mode)
2259{
2260 unsigned int partCount = Val.getNumWords();
2261 APInt api = Val;
2262
2263 sign = false;
2264 if (isSigned && api.isNegative()) {
2265 sign = true;
2266 api = -api;
2267 }
2268
2269 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2270}
2271
Neil Booth03f58ab2007-10-07 12:15:41 +00002272/* Convert a two's complement integer SRC to a floating point number,
2273 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2274 integer is signed, in which case it must be sign-extended. */
2275APFloat::opStatus
2276APFloat::convertFromSignExtendedInteger(const integerPart *src,
2277 unsigned int srcCount,
2278 bool isSigned,
2279 roundingMode rounding_mode)
2280{
2281 opStatus status;
2282
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002283 if (isSigned &&
2284 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002285 integerPart *copy;
2286
2287 /* If we're signed and negative negate a copy. */
2288 sign = true;
2289 copy = new integerPart[srcCount];
2290 APInt::tcAssign(copy, src, srcCount);
2291 APInt::tcNegate(copy, srcCount);
2292 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2293 delete [] copy;
2294 } else {
2295 sign = false;
2296 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2297 }
2298
2299 return status;
2300}
2301
Neil Booth5f009732007-10-07 11:45:55 +00002302/* FIXME: should this just take a const APInt reference? */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002303APFloat::opStatus
Neil Booth5f009732007-10-07 11:45:55 +00002304APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2305 unsigned int width, bool isSigned,
2306 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002307{
Dale Johannesen42305122007-09-21 22:09:37 +00002308 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002309 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002310
2311 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002312 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002313 sign = true;
2314 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002315 }
2316
Neil Boothba205222007-10-07 12:10:57 +00002317 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002318}
2319
2320APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002321APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002322{
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002323 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002324
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002325 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002326 zeroSignificand();
2327 exponent = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002328
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002329 integerPart *significand = significandParts();
2330 unsigned partsCount = partCount();
2331 unsigned bitPos = partsCount * integerPartWidth;
2332 bool computedTrailingFraction = false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002333
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002334 // Skip leading zeroes and any (hexa)decimal point.
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002335 StringRef::iterator begin = s.begin();
2336 StringRef::iterator end = s.end();
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002337 StringRef::iterator dot;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002338 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002339 StringRef::iterator firstSignificantDigit = p;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002340
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002341 while (p != end) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002342 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002343
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002344 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002345 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002346 dot = p++;
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002347 continue;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002348 }
2349
2350 hex_value = hexDigitValue(*p);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002351 if (hex_value == -1U)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002352 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002353
2354 p++;
2355
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002356 // Store the number while we have space.
2357 if (bitPos) {
2358 bitPos -= 4;
2359 hex_value <<= bitPos % integerPartWidth;
2360 significand[bitPos / integerPartWidth] |= hex_value;
2361 } else if (!computedTrailingFraction) {
2362 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2363 computedTrailingFraction = true;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002364 }
2365 }
2366
2367 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002368 assert(p != end && "Hex strings require an exponent");
2369 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2370 assert(p != begin && "Significand has no digits");
2371 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002372
2373 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002374 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002375 int expAdjustment;
2376
2377 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002378 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002379 dot = p;
2380
2381 /* Calculate the exponent adjustment implicit in the number of
2382 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002383 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002384 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002385 expAdjustment++;
2386 expAdjustment = expAdjustment * 4 - 1;
2387
2388 /* Adjust for writing the significand starting at the most
2389 significant nibble. */
2390 expAdjustment += semantics->precision;
2391 expAdjustment -= partsCount * integerPartWidth;
2392
2393 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002394 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002395 }
2396
2397 return normalize(rounding_mode, lost_fraction);
2398}
2399
2400APFloat::opStatus
Neil Boothb93d90e2007-10-12 16:02:31 +00002401APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2402 unsigned sigPartCount, int exp,
2403 roundingMode rounding_mode)
2404{
2405 unsigned int parts, pow5PartCount;
Ulrich Weigand908c9362012-10-29 18:18:44 +00002406 fltSemantics calcSemantics = { 32767, -32767, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002407 integerPart pow5Parts[maxPowerOfFiveParts];
2408 bool isNearest;
2409
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002410 isNearest = (rounding_mode == rmNearestTiesToEven ||
2411 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002412
2413 parts = partCountForBits(semantics->precision + 11);
2414
2415 /* Calculate pow(5, abs(exp)). */
2416 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2417
2418 for (;; parts *= 2) {
2419 opStatus sigStatus, powStatus;
2420 unsigned int excessPrecision, truncatedBits;
2421
2422 calcSemantics.precision = parts * integerPartWidth - 1;
2423 excessPrecision = calcSemantics.precision - semantics->precision;
2424 truncatedBits = excessPrecision;
2425
Michael Gottesman79b09672013-06-27 21:58:19 +00002426 APFloat decSig = APFloat::getZero(calcSemantics, sign);
2427 APFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002428
2429 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2430 rmNearestTiesToEven);
2431 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2432 rmNearestTiesToEven);
2433 /* Add exp, as 10^n = 5^n * 2^n. */
2434 decSig.exponent += exp;
2435
2436 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002437 integerPart HUerr, HUdistance;
2438 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002439
2440 if (exp >= 0) {
2441 /* multiplySignificand leaves the precision-th bit set to 1. */
Craig Topperc10719f2014-04-07 04:17:22 +00002442 calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
Neil Boothb93d90e2007-10-12 16:02:31 +00002443 powHUerr = powStatus != opOK;
2444 } else {
2445 calcLostFraction = decSig.divideSignificand(pow5);
2446 /* Denormal numbers have less precision. */
2447 if (decSig.exponent < semantics->minExponent) {
2448 excessPrecision += (semantics->minExponent - decSig.exponent);
2449 truncatedBits = excessPrecision;
2450 if (excessPrecision > calcSemantics.precision)
2451 excessPrecision = calcSemantics.precision;
2452 }
2453 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002454 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002455 }
2456
2457 /* Both multiplySignificand and divideSignificand return the
2458 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002459 assert(APInt::tcExtractBit
2460 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002461
2462 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2463 powHUerr);
2464 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2465 excessPrecision, isNearest);
2466
2467 /* Are we guaranteed to round correctly if we truncate? */
2468 if (HUdistance >= HUerr) {
2469 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2470 calcSemantics.precision - excessPrecision,
2471 excessPrecision);
2472 /* Take the exponent of decSig. If we tcExtract-ed less bits
2473 above we must adjust our exponent to compensate for the
2474 implicit right shift. */
2475 exponent = (decSig.exponent + semantics->precision
2476 - (calcSemantics.precision - excessPrecision));
2477 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2478 decSig.partCount(),
2479 truncatedBits);
2480 return normalize(rounding_mode, calcLostFraction);
2481 }
2482 }
2483}
2484
2485APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002486APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Boothb93d90e2007-10-12 16:02:31 +00002487{
Neil Booth4ed401b2007-10-14 10:16:12 +00002488 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002489 opStatus fs;
2490
Neil Booth4ed401b2007-10-14 10:16:12 +00002491 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002492 StringRef::iterator p = str.begin();
2493 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002494
Neil Booth91305512007-10-15 15:00:55 +00002495 /* Handle the quick cases. First the case of no significant digits,
2496 i.e. zero, and then exponents that are obviously too large or too
2497 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2498 definitely overflows if
2499
2500 (exp - 1) * L >= maxExponent
2501
2502 and definitely underflows to zero where
2503
2504 (exp + 1) * L <= minExponent - precision
2505
2506 With integer arithmetic the tightest bounds for L are
2507
2508 93/28 < L < 196/59 [ numerator <= 256 ]
2509 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2510 */
2511
Michael Gottesman228156c2013-07-01 23:54:08 +00002512 // Test if we have a zero number allowing for strings with no null terminators
2513 // and zero decimals with non-zero exponents.
2514 //
2515 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2516 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2517 // be at most one dot. On the other hand, if we have a zero with a non-zero
2518 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002519 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002520 category = fcZero;
2521 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002522
2523 /* Check whether the normalized exponent is high enough to overflow
2524 max during the log-rebasing in the max-exponent check below. */
2525 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2526 fs = handleOverflow(rounding_mode);
2527
2528 /* If it wasn't, then it also wasn't high enough to overflow max
2529 during the log-rebasing in the min-exponent check. Check that it
2530 won't overflow min in either check, then perform the min-exponent
2531 check. */
2532 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2533 (D.normalizedExponent + 1) * 28738 <=
2534 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002535 /* Underflow to zero and round. */
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002536 category = fcNormal;
Neil Booth91305512007-10-15 15:00:55 +00002537 zeroSignificand();
2538 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002539
2540 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002541 } else if ((D.normalizedExponent - 1) * 42039
2542 >= 12655 * semantics->maxExponent) {
2543 /* Overflow and round. */
2544 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002545 } else {
Neil Booth4ed401b2007-10-14 10:16:12 +00002546 integerPart *decSignificand;
2547 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002548
Neil Booth4ed401b2007-10-14 10:16:12 +00002549 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002550 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002551 to hold the full significand, and an extra part required by
2552 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002553 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002554 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth4ed401b2007-10-14 10:16:12 +00002555 decSignificand = new integerPart[partCount + 1];
2556 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002557
Neil Booth4ed401b2007-10-14 10:16:12 +00002558 /* Convert to binary efficiently - we do almost all multiplication
2559 in an integerPart. When this would overflow do we do a single
2560 bignum multiplication, and then revert again to multiplication
2561 in an integerPart. */
2562 do {
2563 integerPart decValue, val, multiplier;
2564
2565 val = 0;
2566 multiplier = 1;
2567
2568 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002569 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002570 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002571 if (p == str.end()) {
2572 break;
2573 }
2574 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002575 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002576 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002577 multiplier *= 10;
2578 val = val * 10 + decValue;
2579 /* The maximum number that can be multiplied by ten with any
2580 digit added without overflowing an integerPart. */
2581 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2582
2583 /* Multiply out the current part. */
2584 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2585 partCount, partCount + 1, false);
2586
2587 /* If we used another part (likely but not guaranteed), increase
2588 the count. */
2589 if (decSignificand[partCount])
2590 partCount++;
2591 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002592
Neil Boothae077d22007-11-01 22:51:07 +00002593 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002594 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002595 D.exponent, rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002596
Neil Booth4ed401b2007-10-14 10:16:12 +00002597 delete [] decSignificand;
2598 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002599
2600 return fs;
2601}
2602
Michael Gottesman40e8a182013-06-24 09:58:05 +00002603bool
2604APFloat::convertFromStringSpecials(StringRef str) {
2605 if (str.equals("inf") || str.equals("INFINITY")) {
2606 makeInf(false);
2607 return true;
2608 }
2609
2610 if (str.equals("-inf") || str.equals("-INFINITY")) {
2611 makeInf(true);
2612 return true;
2613 }
2614
2615 if (str.equals("nan") || str.equals("NaN")) {
2616 makeNaN(false, false);
2617 return true;
2618 }
2619
2620 if (str.equals("-nan") || str.equals("-NaN")) {
2621 makeNaN(false, true);
2622 return true;
2623 }
2624
2625 return false;
2626}
2627
Neil Boothb93d90e2007-10-12 16:02:31 +00002628APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002629APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth9acbf5a2007-09-26 21:33:42 +00002630{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002631 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002632
Michael Gottesman40e8a182013-06-24 09:58:05 +00002633 // Handle special cases.
2634 if (convertFromStringSpecials(str))
2635 return opOK;
2636
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002637 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002638 StringRef::iterator p = str.begin();
2639 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002640 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002641 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002642 p++;
2643 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002644 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002645 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002646
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002647 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002648 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002649 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002650 rounding_mode);
2651 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002652
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002653 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002654}
Dale Johannesena719a602007-08-24 00:56:33 +00002655
Neil Booth8f1946f2007-10-03 22:26:02 +00002656/* Write out a hexadecimal representation of the floating point value
2657 to DST, which must be of sufficient size, in the C99 form
2658 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2659 excluding the terminating NUL.
2660
2661 If UPPERCASE, the output is in upper case, otherwise in lower case.
2662
2663 HEXDIGITS digits appear altogether, rounding the value if
2664 necessary. If HEXDIGITS is 0, the minimal precision to display the
2665 number precisely is used instead. If nothing would appear after
2666 the decimal point it is suppressed.
2667
2668 The decimal exponent is always printed and has at least one digit.
2669 Zero values display an exponent of zero. Infinities and NaNs
2670 appear as "infinity" or "nan" respectively.
2671
2672 The above rules are as specified by C99. There is ambiguity about
2673 what the leading hexadecimal digit should be. This implementation
2674 uses whatever is necessary so that the exponent is displayed as
2675 stored. This implies the exponent will fall within the IEEE format
2676 range, and the leading hexadecimal digit will be 0 (for denormals),
2677 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2678 any other digits zero).
2679*/
2680unsigned int
2681APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2682 bool upperCase, roundingMode rounding_mode) const
2683{
2684 char *p;
2685
2686 p = dst;
2687 if (sign)
2688 *dst++ = '-';
2689
2690 switch (category) {
2691 case fcInfinity:
2692 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2693 dst += sizeof infinityL - 1;
2694 break;
2695
2696 case fcNaN:
2697 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2698 dst += sizeof NaNU - 1;
2699 break;
2700
2701 case fcZero:
2702 *dst++ = '0';
2703 *dst++ = upperCase ? 'X': 'x';
2704 *dst++ = '0';
2705 if (hexDigits > 1) {
2706 *dst++ = '.';
2707 memset (dst, '0', hexDigits - 1);
2708 dst += hexDigits - 1;
2709 }
2710 *dst++ = upperCase ? 'P': 'p';
2711 *dst++ = '0';
2712 break;
2713
2714 case fcNormal:
2715 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2716 break;
2717 }
2718
2719 *dst = 0;
2720
Evan Cheng82b9e962008-05-02 21:15:08 +00002721 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002722}
2723
2724/* Does the hard work of outputting the correctly rounded hexadecimal
2725 form of a normal floating point number with the specified number of
2726 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2727 digits necessary to print the value precisely is output. */
2728char *
2729APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2730 bool upperCase,
2731 roundingMode rounding_mode) const
2732{
2733 unsigned int count, valueBits, shift, partsCount, outputDigits;
2734 const char *hexDigitChars;
2735 const integerPart *significand;
2736 char *p;
2737 bool roundUp;
2738
2739 *dst++ = '0';
2740 *dst++ = upperCase ? 'X': 'x';
2741
2742 roundUp = false;
2743 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2744
2745 significand = significandParts();
2746 partsCount = partCount();
2747
2748 /* +3 because the first digit only uses the single integer bit, so
2749 we have 3 virtual zero most-significant-bits. */
2750 valueBits = semantics->precision + 3;
2751 shift = integerPartWidth - valueBits % integerPartWidth;
2752
2753 /* The natural number of digits required ignoring trailing
2754 insignificant zeroes. */
2755 outputDigits = (valueBits - significandLSB () + 3) / 4;
2756
2757 /* hexDigits of zero means use the required number for the
2758 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002759 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002760 if (hexDigits) {
2761 if (hexDigits < outputDigits) {
2762 /* We are dropping non-zero bits, so need to check how to round.
2763 "bits" is the number of dropped bits. */
2764 unsigned int bits;
2765 lostFraction fraction;
2766
2767 bits = valueBits - hexDigits * 4;
2768 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2769 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2770 }
2771 outputDigits = hexDigits;
2772 }
2773
2774 /* Write the digits consecutively, and start writing in the location
2775 of the hexadecimal point. We move the most significant digit
2776 left and add the hexadecimal point later. */
2777 p = ++dst;
2778
2779 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2780
2781 while (outputDigits && count) {
2782 integerPart part;
2783
2784 /* Put the most significant integerPartWidth bits in "part". */
2785 if (--count == partsCount)
2786 part = 0; /* An imaginary higher zero part. */
2787 else
2788 part = significand[count] << shift;
2789
2790 if (count && shift)
2791 part |= significand[count - 1] >> (integerPartWidth - shift);
2792
2793 /* Convert as much of "part" to hexdigits as we can. */
2794 unsigned int curDigits = integerPartWidth / 4;
2795
2796 if (curDigits > outputDigits)
2797 curDigits = outputDigits;
2798 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2799 outputDigits -= curDigits;
2800 }
2801
2802 if (roundUp) {
2803 char *q = dst;
2804
2805 /* Note that hexDigitChars has a trailing '0'. */
2806 do {
2807 q--;
2808 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002809 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002810 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002811 } else {
2812 /* Add trailing zeroes. */
2813 memset (dst, '0', outputDigits);
2814 dst += outputDigits;
2815 }
2816
2817 /* Move the most significant digit to before the point, and if there
2818 is something after the decimal point add it. This must come
2819 after rounding above. */
2820 p[-1] = p[0];
2821 if (dst -1 == p)
2822 dst--;
2823 else
2824 p[0] = '.';
2825
2826 /* Finally output the exponent. */
2827 *dst++ = upperCase ? 'P': 'p';
2828
Neil Booth32897f52007-10-06 07:29:25 +00002829 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002830}
2831
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002832hash_code llvm::hash_value(const APFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002833 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002834 return hash_combine((uint8_t)Arg.category,
2835 // NaN has no sign, fix it at zero.
2836 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2837 Arg.semantics->precision);
2838
2839 // Normal floats need their exponent and significand hashed.
2840 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2841 Arg.semantics->precision, Arg.exponent,
2842 hash_combine_range(
2843 Arg.significandParts(),
2844 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002845}
2846
2847// Conversion from APFloat to/from host float/double. It may eventually be
2848// possible to eliminate these and have everybody deal with APFloats, but that
2849// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002850// Current implementation requires integerPartWidth==64, which is correct at
2851// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002852
Dale Johannesen728687c2007-09-05 20:39:49 +00002853// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002854// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002855
Dale Johannesen245dceb2007-09-11 18:32:33 +00002856APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002857APFloat::convertF80LongDoubleAPFloatToAPInt() const
2858{
Dan Gohmanb456a152008-01-29 12:08:20 +00002859 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002860 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002861
2862 uint64_t myexponent, mysignificand;
2863
Michael Gottesman8136c382013-06-26 23:17:28 +00002864 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002865 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002866 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002867 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2868 myexponent = 0; // denormal
2869 } else if (category==fcZero) {
2870 myexponent = 0;
2871 mysignificand = 0;
2872 } else if (category==fcInfinity) {
2873 myexponent = 0x7fff;
2874 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002875 } else {
2876 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002877 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002878 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002879 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002880
2881 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002882 words[0] = mysignificand;
2883 words[1] = ((uint64_t)(sign & 1) << 15) |
2884 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002885 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002886}
2887
2888APInt
Dale Johannesen007aa372007-10-11 18:07:22 +00002889APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2890{
Dan Gohmanb456a152008-01-29 12:08:20 +00002891 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002892 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002893
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002894 uint64_t words[2];
2895 opStatus fs;
2896 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002897
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002898 // Convert number to double. To avoid spurious underflows, we re-
2899 // normalize against the "double" minExponent first, and only *then*
2900 // truncate the mantissa. The result of that second conversion
2901 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002902 // Declare fltSemantics before APFloat that uses it (and
2903 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002904 fltSemantics extendedSemantics = *semantics;
2905 extendedSemantics.minExponent = IEEEdouble.minExponent;
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002906 APFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002907 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2908 assert(fs == opOK && !losesInfo);
2909 (void)fs;
2910
2911 APFloat u(extended);
2912 fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2913 assert(fs == opOK || fs == opInexact);
2914 (void)fs;
2915 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2916
2917 // If conversion was exact or resulted in a special case, we're done;
2918 // just set the second double to zero. Otherwise, re-convert back to
2919 // the extended format and compute the difference. This now should
2920 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002921 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002922 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2923 assert(fs == opOK && !losesInfo);
2924 (void)fs;
2925
2926 APFloat v(extended);
2927 v.subtract(u, rmNearestTiesToEven);
2928 fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2929 assert(fs == opOK && !losesInfo);
2930 (void)fs;
2931 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002932 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002933 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002934 }
2935
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002936 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002937}
2938
2939APInt
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002940APFloat::convertQuadrupleAPFloatToAPInt() const
2941{
2942 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002943 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002944
2945 uint64_t myexponent, mysignificand, mysignificand2;
2946
Michael Gottesman8136c382013-06-26 23:17:28 +00002947 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002948 myexponent = exponent+16383; //bias
2949 mysignificand = significandParts()[0];
2950 mysignificand2 = significandParts()[1];
2951 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2952 myexponent = 0; // denormal
2953 } else if (category==fcZero) {
2954 myexponent = 0;
2955 mysignificand = mysignificand2 = 0;
2956 } else if (category==fcInfinity) {
2957 myexponent = 0x7fff;
2958 mysignificand = mysignificand2 = 0;
2959 } else {
2960 assert(category == fcNaN && "Unknown category!");
2961 myexponent = 0x7fff;
2962 mysignificand = significandParts()[0];
2963 mysignificand2 = significandParts()[1];
2964 }
2965
2966 uint64_t words[2];
2967 words[0] = mysignificand;
2968 words[1] = ((uint64_t)(sign & 1) << 63) |
2969 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002970 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002971
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002972 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002973}
2974
2975APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002976APFloat::convertDoubleAPFloatToAPInt() const
2977{
Dan Gohman58c468f2007-09-14 20:08:19 +00002978 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002979 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002980
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002981 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002982
Michael Gottesman8136c382013-06-26 23:17:28 +00002983 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002984 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002985 mysignificand = *significandParts();
2986 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2987 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002988 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002989 myexponent = 0;
2990 mysignificand = 0;
2991 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002992 myexponent = 0x7ff;
2993 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002994 } else {
2995 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002996 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002997 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002998 }
Dale Johannesena719a602007-08-24 00:56:33 +00002999
Evan Cheng82b9e962008-05-02 21:15:08 +00003000 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003001 ((myexponent & 0x7ff) << 52) |
3002 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00003003}
3004
Dale Johannesen245dceb2007-09-11 18:32:33 +00003005APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00003006APFloat::convertFloatAPFloatToAPInt() const
3007{
Dan Gohman58c468f2007-09-14 20:08:19 +00003008 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00003009 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00003010
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003011 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003012
Michael Gottesman8136c382013-06-26 23:17:28 +00003013 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00003014 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00003015 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00003016 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00003017 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00003018 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00003019 myexponent = 0;
3020 mysignificand = 0;
3021 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00003022 myexponent = 0xff;
3023 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003024 } else {
3025 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00003026 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00003027 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003028 }
Dale Johannesena719a602007-08-24 00:56:33 +00003029
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003030 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
3031 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00003032}
3033
Chris Lattner4794b2b2009-10-16 02:13:51 +00003034APInt
3035APFloat::convertHalfAPFloatToAPInt() const
3036{
3037 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00003038 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003039
3040 uint32_t myexponent, mysignificand;
3041
Michael Gottesman8136c382013-06-26 23:17:28 +00003042 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003043 myexponent = exponent+15; //bias
3044 mysignificand = (uint32_t)*significandParts();
3045 if (myexponent == 1 && !(mysignificand & 0x400))
3046 myexponent = 0; // denormal
3047 } else if (category==fcZero) {
3048 myexponent = 0;
3049 mysignificand = 0;
3050 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00003051 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003052 mysignificand = 0;
3053 } else {
3054 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00003055 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003056 mysignificand = (uint32_t)*significandParts();
3057 }
3058
3059 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
3060 (mysignificand & 0x3ff)));
3061}
3062
Dale Johannesen007aa372007-10-11 18:07:22 +00003063// This function creates an APInt that is just a bit map of the floating
3064// point constant as it would appear in memory. It is not a conversion,
3065// and treating the result as a normal integer is unlikely to be useful.
3066
Dale Johannesen245dceb2007-09-11 18:32:33 +00003067APInt
Dale Johannesen54306fe2008-10-09 18:53:47 +00003068APFloat::bitcastToAPInt() const
Neil Booth9acbf5a2007-09-26 21:33:42 +00003069{
Chris Lattner4794b2b2009-10-16 02:13:51 +00003070 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
3071 return convertHalfAPFloatToAPInt();
3072
Dan Gohmanb456a152008-01-29 12:08:20 +00003073 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003074 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003075
Dan Gohmanb456a152008-01-29 12:08:20 +00003076 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003077 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003078
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003079 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
3080 return convertQuadrupleAPFloatToAPInt();
3081
Dan Gohmanb456a152008-01-29 12:08:20 +00003082 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesen007aa372007-10-11 18:07:22 +00003083 return convertPPCDoubleDoubleAPFloatToAPInt();
3084
Dan Gohmanb456a152008-01-29 12:08:20 +00003085 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003086 "unknown format!");
3087 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003088}
3089
Neil Booth9acbf5a2007-09-26 21:33:42 +00003090float
3091APFloat::convertToFloat() const
3092{
Chris Lattner688f9912009-09-24 21:44:20 +00003093 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
3094 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003095 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003096 return api.bitsToFloat();
3097}
3098
Neil Booth9acbf5a2007-09-26 21:33:42 +00003099double
3100APFloat::convertToDouble() const
3101{
Chris Lattner688f9912009-09-24 21:44:20 +00003102 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
3103 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003104 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003105 return api.bitsToDouble();
3106}
3107
Dale Johannesenfff29952008-10-06 18:22:29 +00003108/// Integer bit is explicit in this format. Intel hardware (387 and later)
3109/// does not support these bit patterns:
3110/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3111/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3112/// exponent = 0, integer bit 1 ("pseudodenormal")
3113/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3114/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen245dceb2007-09-11 18:32:33 +00003115void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003116APFloat::initFromF80LongDoubleAPInt(const APInt &api)
3117{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003118 assert(api.getBitWidth()==80);
3119 uint64_t i1 = api.getRawData()[0];
3120 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003121 uint64_t myexponent = (i2 & 0x7fff);
3122 uint64_t mysignificand = i1;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003123
3124 initialize(&APFloat::x87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003125 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003126
Dale Johannesen93eefa02009-03-23 21:16:53 +00003127 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003128 if (myexponent==0 && mysignificand==0) {
3129 // exponent, significand meaningless
3130 category = fcZero;
3131 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3132 // exponent, significand meaningless
3133 category = fcInfinity;
3134 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3135 // exponent meaningless
3136 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003137 significandParts()[0] = mysignificand;
3138 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003139 } else {
3140 category = fcNormal;
3141 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003142 significandParts()[0] = mysignificand;
3143 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003144 if (myexponent==0) // denormal
3145 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003146 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003147}
3148
3149void
Dale Johannesen007aa372007-10-11 18:07:22 +00003150APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3151{
3152 assert(api.getBitWidth()==128);
3153 uint64_t i1 = api.getRawData()[0];
3154 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003155 opStatus fs;
3156 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003157
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003158 // Get the first double and convert to our format.
3159 initFromDoubleAPInt(APInt(64, i1));
3160 fs = convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3161 assert(fs == opOK && !losesInfo);
3162 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003163
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003164 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003165 if (isFiniteNonZero()) {
Tim Northover29178a32013-01-22 09:46:31 +00003166 APFloat v(IEEEdouble, APInt(64, i2));
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003167 fs = v.convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3168 assert(fs == opOK && !losesInfo);
3169 (void)fs;
3170
3171 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003172 }
3173}
3174
3175void
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003176APFloat::initFromQuadrupleAPInt(const APInt &api)
3177{
3178 assert(api.getBitWidth()==128);
3179 uint64_t i1 = api.getRawData()[0];
3180 uint64_t i2 = api.getRawData()[1];
3181 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3182 uint64_t mysignificand = i1;
3183 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3184
3185 initialize(&APFloat::IEEEquad);
3186 assert(partCount()==2);
3187
3188 sign = static_cast<unsigned int>(i2>>63);
3189 if (myexponent==0 &&
3190 (mysignificand==0 && mysignificand2==0)) {
3191 // exponent, significand meaningless
3192 category = fcZero;
3193 } else if (myexponent==0x7fff &&
3194 (mysignificand==0 && mysignificand2==0)) {
3195 // exponent, significand meaningless
3196 category = fcInfinity;
3197 } else if (myexponent==0x7fff &&
3198 (mysignificand!=0 || mysignificand2 !=0)) {
3199 // exponent meaningless
3200 category = fcNaN;
3201 significandParts()[0] = mysignificand;
3202 significandParts()[1] = mysignificand2;
3203 } else {
3204 category = fcNormal;
3205 exponent = myexponent - 16383;
3206 significandParts()[0] = mysignificand;
3207 significandParts()[1] = mysignificand2;
3208 if (myexponent==0) // denormal
3209 exponent = -16382;
3210 else
3211 significandParts()[1] |= 0x1000000000000LL; // integer bit
3212 }
3213}
3214
3215void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003216APFloat::initFromDoubleAPInt(const APInt &api)
3217{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003218 assert(api.getBitWidth()==64);
3219 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003220 uint64_t myexponent = (i >> 52) & 0x7ff;
3221 uint64_t mysignificand = i & 0xfffffffffffffLL;
3222
Dale Johannesena719a602007-08-24 00:56:33 +00003223 initialize(&APFloat::IEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003224 assert(partCount()==1);
3225
Evan Cheng82b9e962008-05-02 21:15:08 +00003226 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003227 if (myexponent==0 && mysignificand==0) {
3228 // exponent, significand meaningless
3229 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003230 } else if (myexponent==0x7ff && mysignificand==0) {
3231 // exponent, significand meaningless
3232 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003233 } else if (myexponent==0x7ff && mysignificand!=0) {
3234 // exponent meaningless
3235 category = fcNaN;
3236 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003237 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003238 category = fcNormal;
3239 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003240 *significandParts() = mysignificand;
3241 if (myexponent==0) // denormal
3242 exponent = -1022;
3243 else
3244 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003245 }
Dale Johannesena719a602007-08-24 00:56:33 +00003246}
3247
Dale Johannesen245dceb2007-09-11 18:32:33 +00003248void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003249APFloat::initFromFloatAPInt(const APInt & api)
3250{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003251 assert(api.getBitWidth()==32);
3252 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003253 uint32_t myexponent = (i >> 23) & 0xff;
3254 uint32_t mysignificand = i & 0x7fffff;
3255
Dale Johannesena719a602007-08-24 00:56:33 +00003256 initialize(&APFloat::IEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003257 assert(partCount()==1);
3258
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003259 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003260 if (myexponent==0 && mysignificand==0) {
3261 // exponent, significand meaningless
3262 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003263 } else if (myexponent==0xff && mysignificand==0) {
3264 // exponent, significand meaningless
3265 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003266 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003267 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003268 category = fcNaN;
3269 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003270 } else {
3271 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003272 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003273 *significandParts() = mysignificand;
3274 if (myexponent==0) // denormal
3275 exponent = -126;
3276 else
3277 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003278 }
3279}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003280
Chris Lattner4794b2b2009-10-16 02:13:51 +00003281void
3282APFloat::initFromHalfAPInt(const APInt & api)
3283{
3284 assert(api.getBitWidth()==16);
3285 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003286 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003287 uint32_t mysignificand = i & 0x3ff;
3288
3289 initialize(&APFloat::IEEEhalf);
3290 assert(partCount()==1);
3291
3292 sign = i >> 15;
3293 if (myexponent==0 && mysignificand==0) {
3294 // exponent, significand meaningless
3295 category = fcZero;
3296 } else if (myexponent==0x1f && mysignificand==0) {
3297 // exponent, significand meaningless
3298 category = fcInfinity;
3299 } else if (myexponent==0x1f && mysignificand!=0) {
3300 // sign, exponent, significand meaningless
3301 category = fcNaN;
3302 *significandParts() = mysignificand;
3303 } else {
3304 category = fcNormal;
3305 exponent = myexponent - 15; //bias
3306 *significandParts() = mysignificand;
3307 if (myexponent==0) // denormal
3308 exponent = -14;
3309 else
3310 *significandParts() |= 0x400; // integer bit
3311 }
3312}
3313
Dale Johannesen245dceb2007-09-11 18:32:33 +00003314/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003315/// we infer the floating point type from the size of the APInt. The
3316/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3317/// when the size is anything else).
Dale Johannesen245dceb2007-09-11 18:32:33 +00003318void
Tim Northover29178a32013-01-22 09:46:31 +00003319APFloat::initFromAPInt(const fltSemantics* Sem, const APInt& api)
Neil Booth9acbf5a2007-09-26 21:33:42 +00003320{
Tim Northover29178a32013-01-22 09:46:31 +00003321 if (Sem == &IEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003322 return initFromHalfAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003323 if (Sem == &IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003324 return initFromFloatAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003325 if (Sem == &IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003326 return initFromDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003327 if (Sem == &x87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003328 return initFromF80LongDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003329 if (Sem == &IEEEquad)
3330 return initFromQuadrupleAPInt(api);
3331 if (Sem == &PPCDoubleDouble)
3332 return initFromPPCDoubleDoubleAPInt(api);
3333
Craig Topper2617dcc2014-04-15 06:32:26 +00003334 llvm_unreachable(nullptr);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003335}
3336
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003337APFloat
3338APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3339{
Tim Northover29178a32013-01-22 09:46:31 +00003340 switch (BitWidth) {
3341 case 16:
3342 return APFloat(IEEEhalf, APInt::getAllOnesValue(BitWidth));
3343 case 32:
3344 return APFloat(IEEEsingle, APInt::getAllOnesValue(BitWidth));
3345 case 64:
3346 return APFloat(IEEEdouble, APInt::getAllOnesValue(BitWidth));
3347 case 80:
3348 return APFloat(x87DoubleExtended, APInt::getAllOnesValue(BitWidth));
3349 case 128:
3350 if (isIEEE)
3351 return APFloat(IEEEquad, APInt::getAllOnesValue(BitWidth));
3352 return APFloat(PPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
3353 default:
3354 llvm_unreachable("Unknown floating bit width");
3355 }
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003356}
3357
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003358/// Make this number the largest magnitude normal number in the given
3359/// semantics.
3360void APFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003361 // We want (in interchange format):
3362 // sign = {Negative}
3363 // exponent = 1..10
3364 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003365 category = fcNormal;
3366 sign = Negative;
3367 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003368
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003369 // Use memset to set all but the highest integerPart to all ones.
3370 integerPart *significand = significandParts();
3371 unsigned PartCount = partCount();
3372 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003373
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003374 // Set the high integerPart especially setting all unused top bits for
3375 // internal consistency.
3376 const unsigned NumUnusedHighBits =
3377 PartCount*integerPartWidth - semantics->precision;
3378 significand[PartCount - 1] = ~integerPart(0) >> NumUnusedHighBits;
John McCall29b5c282009-12-24 08:56:26 +00003379}
3380
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003381/// Make this number the smallest magnitude denormal number in the given
3382/// semantics.
3383void APFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003384 // We want (in interchange format):
3385 // sign = {Negative}
3386 // exponent = 0..0
3387 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003388 category = fcNormal;
3389 sign = Negative;
3390 exponent = semantics->minExponent;
3391 APInt::tcSet(significandParts(), 1, partCount());
3392}
John McCall29b5c282009-12-24 08:56:26 +00003393
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003394
3395APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3396 // We want (in interchange format):
3397 // sign = {Negative}
3398 // exponent = 1..10
3399 // significand = 1..1
3400 APFloat Val(Sem, uninitialized);
3401 Val.makeLargest(Negative);
3402 return Val;
3403}
3404
3405APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3406 // We want (in interchange format):
3407 // sign = {Negative}
3408 // exponent = 0..0
3409 // significand = 0..01
3410 APFloat Val(Sem, uninitialized);
3411 Val.makeSmallest(Negative);
John McCall29b5c282009-12-24 08:56:26 +00003412 return Val;
3413}
3414
3415APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
Michael Gottesman79b09672013-06-27 21:58:19 +00003416 APFloat Val(Sem, uninitialized);
John McCall29b5c282009-12-24 08:56:26 +00003417
3418 // We want (in interchange format):
3419 // sign = {Negative}
3420 // exponent = 0..0
3421 // significand = 10..0
3422
Michael Gottesman30a90eb2013-07-27 21:49:21 +00003423 Val.category = fcNormal;
Michael Gottesmanccaf3322013-06-27 20:40:11 +00003424 Val.zeroSignificand();
Michael Gottesman79b09672013-06-27 21:58:19 +00003425 Val.sign = Negative;
3426 Val.exponent = Sem.minExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003427 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
Eli Friedmand4330422011-10-12 21:56:19 +00003428 (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003429
3430 return Val;
3431}
3432
Tim Northover29178a32013-01-22 09:46:31 +00003433APFloat::APFloat(const fltSemantics &Sem, const APInt &API) {
3434 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003435}
3436
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003437APFloat::APFloat(float f) {
Tim Northover29178a32013-01-22 09:46:31 +00003438 initFromAPInt(&IEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003439}
3440
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003441APFloat::APFloat(double d) {
Tim Northover29178a32013-01-22 09:46:31 +00003442 initFromAPInt(&IEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003443}
John McCall29b5c282009-12-24 08:56:26 +00003444
3445namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003446 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3447 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003448 }
3449
John McCalle6212ace2009-12-24 12:16:56 +00003450 /// Removes data from the given significand until it is no more
3451 /// precise than is required for the desired precision.
3452 void AdjustToPrecision(APInt &significand,
3453 int &exp, unsigned FormatPrecision) {
3454 unsigned bits = significand.getActiveBits();
3455
3456 // 196/59 is a very slight overestimate of lg_2(10).
3457 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3458
3459 if (bits <= bitsRequired) return;
3460
3461 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3462 if (!tensRemovable) return;
3463
3464 exp += tensRemovable;
3465
3466 APInt divisor(significand.getBitWidth(), 1);
3467 APInt powten(significand.getBitWidth(), 10);
3468 while (true) {
3469 if (tensRemovable & 1)
3470 divisor *= powten;
3471 tensRemovable >>= 1;
3472 if (!tensRemovable) break;
3473 powten *= powten;
3474 }
3475
3476 significand = significand.udiv(divisor);
3477
Hao Liube99cc32013-03-20 01:46:36 +00003478 // Truncate the significand down to its active bit count.
3479 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003480 }
3481
3482
John McCall29b5c282009-12-24 08:56:26 +00003483 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3484 int &exp, unsigned FormatPrecision) {
3485 unsigned N = buffer.size();
3486 if (N <= FormatPrecision) return;
3487
3488 // The most significant figures are the last ones in the buffer.
3489 unsigned FirstSignificant = N - FormatPrecision;
3490
3491 // Round.
3492 // FIXME: this probably shouldn't use 'round half up'.
3493
3494 // Rounding down is just a truncation, except we also want to drop
3495 // trailing zeros from the new result.
3496 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003497 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003498 FirstSignificant++;
3499
3500 exp += FirstSignificant;
3501 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3502 return;
3503 }
3504
3505 // Rounding up requires a decimal add-with-carry. If we continue
3506 // the carry, the newly-introduced zeros will just be truncated.
3507 for (unsigned I = FirstSignificant; I != N; ++I) {
3508 if (buffer[I] == '9') {
3509 FirstSignificant++;
3510 } else {
3511 buffer[I]++;
3512 break;
3513 }
3514 }
3515
3516 // If we carried through, we have exactly one digit of precision.
3517 if (FirstSignificant == N) {
3518 exp += FirstSignificant;
3519 buffer.clear();
3520 buffer.push_back('1');
3521 return;
3522 }
3523
3524 exp += FirstSignificant;
3525 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3526 }
3527}
3528
3529void APFloat::toString(SmallVectorImpl<char> &Str,
3530 unsigned FormatPrecision,
Chris Lattner4c1e4db2010-03-06 19:20:13 +00003531 unsigned FormatMaxPadding) const {
John McCall29b5c282009-12-24 08:56:26 +00003532 switch (category) {
3533 case fcInfinity:
3534 if (isNegative())
3535 return append(Str, "-Inf");
3536 else
3537 return append(Str, "+Inf");
3538
3539 case fcNaN: return append(Str, "NaN");
3540
3541 case fcZero:
3542 if (isNegative())
3543 Str.push_back('-');
3544
3545 if (!FormatMaxPadding)
3546 append(Str, "0.0E+0");
3547 else
3548 Str.push_back('0');
3549 return;
3550
3551 case fcNormal:
3552 break;
3553 }
3554
3555 if (isNegative())
3556 Str.push_back('-');
3557
3558 // Decompose the number into an APInt and an exponent.
3559 int exp = exponent - ((int) semantics->precision - 1);
3560 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003561 makeArrayRef(significandParts(),
3562 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003563
John McCalldd5044a2009-12-24 23:18:09 +00003564 // Set FormatPrecision if zero. We want to do this before we
3565 // truncate trailing zeros, as those are part of the precision.
3566 if (!FormatPrecision) {
Eli Friedmane72f1322013-08-29 23:44:34 +00003567 // We use enough digits so the number can be round-tripped back to an
3568 // APFloat. The formula comes from "How to Print Floating-Point Numbers
3569 // Accurately" by Steele and White.
3570 // FIXME: Using a formula based purely on the precision is conservative;
3571 // we can print fewer digits depending on the actual value being printed.
John McCalldd5044a2009-12-24 23:18:09 +00003572
Eli Friedmane72f1322013-08-29 23:44:34 +00003573 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3574 FormatPrecision = 2 + semantics->precision * 59 / 196;
John McCalldd5044a2009-12-24 23:18:09 +00003575 }
3576
John McCall29b5c282009-12-24 08:56:26 +00003577 // Ignore trailing binary zeros.
3578 int trailingZeros = significand.countTrailingZeros();
3579 exp += trailingZeros;
3580 significand = significand.lshr(trailingZeros);
3581
3582 // Change the exponent from 2^e to 10^e.
3583 if (exp == 0) {
3584 // Nothing to do.
3585 } else if (exp > 0) {
3586 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003587 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003588 significand <<= exp;
3589 exp = 0;
3590 } else { /* exp < 0 */
3591 int texp = -exp;
3592
3593 // We transform this using the identity:
3594 // (N)(2^-e) == (N)(5^e)(10^-e)
3595 // This means we have to multiply N (the significand) by 5^e.
3596 // To avoid overflow, we have to operate on numbers large
3597 // enough to store N * 5^e:
3598 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003599 // <= semantics->precision + e * 137 / 59
3600 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003601
Eli Friedman19546412011-10-07 23:40:49 +00003602 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003603
3604 // Multiply significand by 5^e.
3605 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003606 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003607 APInt five_to_the_i(precision, 5);
3608 while (true) {
3609 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003610
John McCall29b5c282009-12-24 08:56:26 +00003611 texp >>= 1;
3612 if (!texp) break;
3613 five_to_the_i *= five_to_the_i;
3614 }
3615 }
3616
John McCalle6212ace2009-12-24 12:16:56 +00003617 AdjustToPrecision(significand, exp, FormatPrecision);
3618
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003619 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003620
3621 // Fill the buffer.
3622 unsigned precision = significand.getBitWidth();
3623 APInt ten(precision, 10);
3624 APInt digit(precision, 0);
3625
3626 bool inTrail = true;
3627 while (significand != 0) {
3628 // digit <- significand % 10
3629 // significand <- significand / 10
3630 APInt::udivrem(significand, ten, significand, digit);
3631
3632 unsigned d = digit.getZExtValue();
3633
3634 // Drop trailing zeros.
3635 if (inTrail && !d) exp++;
3636 else {
3637 buffer.push_back((char) ('0' + d));
3638 inTrail = false;
3639 }
3640 }
3641
3642 assert(!buffer.empty() && "no characters in buffer!");
3643
3644 // Drop down to FormatPrecision.
3645 // TODO: don't do more precise calculations above than are required.
3646 AdjustToPrecision(buffer, exp, FormatPrecision);
3647
3648 unsigned NDigits = buffer.size();
3649
John McCalldd5044a2009-12-24 23:18:09 +00003650 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003651 bool FormatScientific;
3652 if (!FormatMaxPadding)
3653 FormatScientific = true;
3654 else {
John McCall29b5c282009-12-24 08:56:26 +00003655 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003656 // 765e3 --> 765000
3657 // ^^^
3658 // But we shouldn't make the number look more precise than it is.
3659 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3660 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003661 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003662 // Power of the most significant digit.
3663 int MSD = exp + (int) (NDigits - 1);
3664 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003665 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003666 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003667 } else {
3668 // 765e-5 == 0.00765
3669 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003670 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003671 }
3672 }
John McCall29b5c282009-12-24 08:56:26 +00003673 }
3674
3675 // Scientific formatting is pretty straightforward.
3676 if (FormatScientific) {
3677 exp += (NDigits - 1);
3678
3679 Str.push_back(buffer[NDigits-1]);
3680 Str.push_back('.');
3681 if (NDigits == 1)
3682 Str.push_back('0');
3683 else
3684 for (unsigned I = 1; I != NDigits; ++I)
3685 Str.push_back(buffer[NDigits-1-I]);
3686 Str.push_back('E');
3687
3688 Str.push_back(exp >= 0 ? '+' : '-');
3689 if (exp < 0) exp = -exp;
3690 SmallVector<char, 6> expbuf;
3691 do {
3692 expbuf.push_back((char) ('0' + (exp % 10)));
3693 exp /= 10;
3694 } while (exp);
3695 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3696 Str.push_back(expbuf[E-1-I]);
3697 return;
3698 }
3699
3700 // Non-scientific, positive exponents.
3701 if (exp >= 0) {
3702 for (unsigned I = 0; I != NDigits; ++I)
3703 Str.push_back(buffer[NDigits-1-I]);
3704 for (unsigned I = 0; I != (unsigned) exp; ++I)
3705 Str.push_back('0');
3706 return;
3707 }
3708
3709 // Non-scientific, negative exponents.
3710
3711 // The number of digits to the left of the decimal point.
3712 int NWholeDigits = exp + (int) NDigits;
3713
3714 unsigned I = 0;
3715 if (NWholeDigits > 0) {
3716 for (; I != (unsigned) NWholeDigits; ++I)
3717 Str.push_back(buffer[NDigits-I-1]);
3718 Str.push_back('.');
3719 } else {
3720 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3721
3722 Str.push_back('0');
3723 Str.push_back('.');
3724 for (unsigned Z = 1; Z != NZeros; ++Z)
3725 Str.push_back('0');
3726 }
3727
3728 for (; I != NDigits; ++I)
3729 Str.push_back(buffer[NDigits-I-1]);
3730}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003731
3732bool APFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003733 // Special floats and denormals have no exact inverse.
Michael Gottesman8136c382013-06-26 23:17:28 +00003734 if (!isFiniteNonZero())
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003735 return false;
3736
3737 // Check that the number is a power of two by making sure that only the
3738 // integer bit is set in the significand.
3739 if (significandLSB() != semantics->precision - 1)
3740 return false;
3741
3742 // Get the inverse.
3743 APFloat reciprocal(*semantics, 1ULL);
3744 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3745 return false;
3746
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003747 // Avoid multiplication with a denormal, it is not safe on all platforms and
3748 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003749 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003750 return false;
3751
Michael Gottesman8136c382013-06-26 23:17:28 +00003752 assert(reciprocal.isFiniteNonZero() &&
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003753 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3754
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003755 if (inv)
3756 *inv = reciprocal;
3757
3758 return true;
3759}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003760
3761bool APFloat::isSignaling() const {
3762 if (!isNaN())
3763 return false;
3764
3765 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3766 // first bit of the trailing significand being 0.
3767 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3768}
3769
3770/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3771///
3772/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3773/// appropriate sign switching before/after the computation.
3774APFloat::opStatus APFloat::next(bool nextDown) {
3775 // If we are performing nextDown, swap sign so we have -x.
3776 if (nextDown)
3777 changeSign();
3778
3779 // Compute nextUp(x)
3780 opStatus result = opOK;
3781
3782 // Handle each float category separately.
3783 switch (category) {
3784 case fcInfinity:
3785 // nextUp(+inf) = +inf
3786 if (!isNegative())
3787 break;
3788 // nextUp(-inf) = -getLargest()
3789 makeLargest(true);
3790 break;
3791 case fcNaN:
3792 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3793 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3794 // change the payload.
3795 if (isSignaling()) {
3796 result = opInvalidOp;
Alp Tokercb402912014-01-24 17:20:08 +00003797 // For consistency, propagate the sign of the sNaN to the qNaN.
Craig Topperc10719f2014-04-07 04:17:22 +00003798 makeNaN(false, isNegative(), nullptr);
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003799 }
3800 break;
3801 case fcZero:
3802 // nextUp(pm 0) = +getSmallest()
3803 makeSmallest(false);
3804 break;
3805 case fcNormal:
3806 // nextUp(-getSmallest()) = -0
3807 if (isSmallest() && isNegative()) {
3808 APInt::tcSet(significandParts(), 0, partCount());
3809 category = fcZero;
3810 exponent = 0;
3811 break;
3812 }
3813
3814 // nextUp(getLargest()) == INFINITY
3815 if (isLargest() && !isNegative()) {
3816 APInt::tcSet(significandParts(), 0, partCount());
3817 category = fcInfinity;
3818 exponent = semantics->maxExponent + 1;
3819 break;
3820 }
3821
3822 // nextUp(normal) == normal + inc.
3823 if (isNegative()) {
3824 // If we are negative, we need to decrement the significand.
3825
3826 // We only cross a binade boundary that requires adjusting the exponent
3827 // if:
3828 // 1. exponent != semantics->minExponent. This implies we are not in the
3829 // smallest binade or are dealing with denormals.
3830 // 2. Our significand excluding the integral bit is all zeros.
3831 bool WillCrossBinadeBoundary =
3832 exponent != semantics->minExponent && isSignificandAllZeros();
3833
3834 // Decrement the significand.
3835 //
3836 // We always do this since:
Alp Tokerf907b892013-12-05 05:44:44 +00003837 // 1. If we are dealing with a non-binade decrement, by definition we
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003838 // just decrement the significand.
3839 // 2. If we are dealing with a normal -> normal binade decrement, since
3840 // we have an explicit integral bit the fact that all bits but the
3841 // integral bit are zero implies that subtracting one will yield a
3842 // significand with 0 integral bit and 1 in all other spots. Thus we
3843 // must just adjust the exponent and set the integral bit to 1.
3844 // 3. If we are dealing with a normal -> denormal binade decrement,
3845 // since we set the integral bit to 0 when we represent denormals, we
3846 // just decrement the significand.
3847 integerPart *Parts = significandParts();
3848 APInt::tcDecrement(Parts, partCount());
3849
3850 if (WillCrossBinadeBoundary) {
3851 // Our result is a normal number. Do the following:
3852 // 1. Set the integral bit to 1.
3853 // 2. Decrement the exponent.
3854 APInt::tcSetBit(Parts, semantics->precision - 1);
3855 exponent--;
3856 }
3857 } else {
3858 // If we are positive, we need to increment the significand.
3859
3860 // We only cross a binade boundary that requires adjusting the exponent if
3861 // the input is not a denormal and all of said input's significand bits
3862 // are set. If all of said conditions are true: clear the significand, set
3863 // the integral bit to 1, and increment the exponent. If we have a
3864 // denormal always increment since moving denormals and the numbers in the
3865 // smallest normal binade have the same exponent in our representation.
3866 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3867
3868 if (WillCrossBinadeBoundary) {
3869 integerPart *Parts = significandParts();
3870 APInt::tcSet(Parts, 0, partCount());
3871 APInt::tcSetBit(Parts, semantics->precision - 1);
3872 assert(exponent != semantics->maxExponent &&
3873 "We can not increment an exponent beyond the maxExponent allowed"
3874 " by the given floating point semantics.");
3875 exponent++;
3876 } else {
3877 incrementSignificand();
3878 }
3879 }
3880 break;
3881 }
3882
3883 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3884 if (nextDown)
3885 changeSign();
3886
3887 return result;
3888}
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003889
3890void
3891APFloat::makeInf(bool Negative) {
3892 category = fcInfinity;
3893 sign = Negative;
3894 exponent = semantics->maxExponent + 1;
3895 APInt::tcSet(significandParts(), 0, partCount());
3896}
3897
3898void
3899APFloat::makeZero(bool Negative) {
3900 category = fcZero;
3901 sign = Negative;
3902 exponent = semantics->minExponent-1;
3903 APInt::tcSet(significandParts(), 0, partCount());
3904}