blob: d07a3c9e7f35b8c7eaa2e937fc8474b7c5d437d4 [file] [log] [blame]
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-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 Lattnerb39cdde2007-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 Lattner36d26c22007-12-08 19:00:03 +000015#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +000016#include "llvm/ADT/APSInt.h"
Ted Kremenek1f801fa2008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruthed7692a2012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
19#include "llvm/ADT/StringRef.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000020#include "llvm/Support/ErrorHandling.h"
Dale Johannesend3b51fd2007-08-24 05:08:11 +000021#include "llvm/Support/MathExtras.h"
John McCall8b3f3302010-02-26 22:20:41 +000022#include <limits.h>
Chris Lattnerfad86b02008-08-17 07:19:36 +000023#include <cstring>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000024
25using namespace llvm;
26
27#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
28
Neil Bootha30b0ee2007-10-03 22:26:02 +000029/* Assumed in hexadecimal significand parsing, and conversion to
30 hexadecimal strings. */
Chris Lattner9f17eb02008-08-17 04:58:58 +000031#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerb39cdde2007-08-20 22:49:32 +000032COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
33
34namespace llvm {
35
36 /* Represents floating point arithmetic semantics. */
37 struct fltSemantics {
38 /* The largest E such that 2^E is representable; this matches the
39 definition of IEEE 754. */
40 exponent_t maxExponent;
41
42 /* The smallest E such that 2^E is a normalized number; this
43 matches the definition of IEEE 754. */
44 exponent_t minExponent;
45
46 /* Number of bits in the significand. This includes the integer
47 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000048 unsigned int precision;
Neil Boothcaf19d72007-10-14 10:29:28 +000049
50 /* True if arithmetic is supported. */
51 unsigned int arithmeticOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000052 };
53
Chris Lattnercc4287a2009-10-16 02:13:51 +000054 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11, true };
Neil Boothcaf19d72007-10-14 10:29:28 +000055 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
56 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
57 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
58 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
59 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesena471c2e2007-10-11 18:07:22 +000060
61 // The PowerPC format consists of two doubles. It does not map cleanly
62 // onto the usual format above. For now only storage of constants of
63 // this type is supported, no arithmetic.
Neil Boothcaf19d72007-10-14 10:29:28 +000064 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
Neil Booth96c74712007-10-12 16:02:31 +000065
66 /* A tight upper bound on number of parts required to hold the value
67 pow(5, power) is
68
Neil Booth686700e2007-10-15 15:00:55 +000069 power * 815 / (351 * integerPartWidth) + 1
Dan Gohman16e02092010-03-24 19:38:02 +000070
Neil Booth96c74712007-10-12 16:02:31 +000071 However, whilst the result may require only this many parts,
72 because we are multiplying two values to get it, the
73 multiplication may require an extra part with the excess part
74 being zero (consider the trivial case of 1 * 1, tcFullMultiply
75 requires two parts to hold the single-part result). So we add an
76 extra one to guarantee enough space whilst multiplying. */
77 const unsigned int maxExponent = 16383;
78 const unsigned int maxPrecision = 113;
79 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth686700e2007-10-15 15:00:55 +000080 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
81 / (351 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000082}
83
Chris Lattnere213f3f2009-03-12 23:59:55 +000084/* A bunch of private, handy routines. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +000085
Chris Lattnere213f3f2009-03-12 23:59:55 +000086static inline unsigned int
87partCountForBits(unsigned int bits)
88{
89 return ((bits) + integerPartWidth - 1) / integerPartWidth;
90}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000091
Chris Lattnere213f3f2009-03-12 23:59:55 +000092/* Returns 0U-9U. Return values >= 10U are not digits. */
93static inline unsigned int
94decDigitValue(unsigned int c)
95{
96 return c - '0';
97}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000098
Chris Lattnere213f3f2009-03-12 23:59:55 +000099static unsigned int
100hexDigitValue(unsigned int c)
101{
102 unsigned int r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000103
Chris Lattnere213f3f2009-03-12 23:59:55 +0000104 r = c - '0';
Dan Gohman16e02092010-03-24 19:38:02 +0000105 if (r <= 9)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000106 return r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000107
Chris Lattnere213f3f2009-03-12 23:59:55 +0000108 r = c - 'A';
Dan Gohman16e02092010-03-24 19:38:02 +0000109 if (r <= 5)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000110 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000111
Chris Lattnere213f3f2009-03-12 23:59:55 +0000112 r = c - 'a';
Dan Gohman16e02092010-03-24 19:38:02 +0000113 if (r <= 5)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000114 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000115
Chris Lattnere213f3f2009-03-12 23:59:55 +0000116 return -1U;
117}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000118
Chris Lattnere213f3f2009-03-12 23:59:55 +0000119static inline void
120assertArithmeticOK(const llvm::fltSemantics &semantics) {
Dan Gohman16e02092010-03-24 19:38:02 +0000121 assert(semantics.arithmeticOK &&
122 "Compile-time arithmetic does not support these semantics");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000123}
Neil Boothcaf19d72007-10-14 10:29:28 +0000124
Chris Lattnere213f3f2009-03-12 23:59:55 +0000125/* Return the value of a decimal exponent of the form
126 [+-]ddddddd.
Neil Booth1870f292007-10-14 10:16:12 +0000127
Chris Lattnere213f3f2009-03-12 23:59:55 +0000128 If the exponent overflows, returns a large exponent with the
129 appropriate sign. */
130static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000131readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000132{
133 bool isNegative;
134 unsigned int absExponent;
135 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000136 StringRef::iterator p = begin;
137
138 assert(p != end && "Exponent has no digits");
Neil Booth1870f292007-10-14 10:16:12 +0000139
Chris Lattnere213f3f2009-03-12 23:59:55 +0000140 isNegative = (*p == '-');
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000141 if (*p == '-' || *p == '+') {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000142 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000143 assert(p != end && "Exponent has no digits");
144 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000145
Chris Lattnere213f3f2009-03-12 23:59:55 +0000146 absExponent = decDigitValue(*p++);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000147 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000148
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000149 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000150 unsigned int value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000151
Chris Lattnere213f3f2009-03-12 23:59:55 +0000152 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000153 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000154
Chris Lattnere213f3f2009-03-12 23:59:55 +0000155 value += absExponent * 10;
156 if (absExponent >= overlargeExponent) {
157 absExponent = overlargeExponent;
Dale Johannesenb1508d12010-08-19 17:58:35 +0000158 p = end; /* outwit assert below */
Chris Lattnere213f3f2009-03-12 23:59:55 +0000159 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000160 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000161 absExponent = value;
162 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000163
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000164 assert(p == end && "Invalid exponent in exponent");
165
Chris Lattnere213f3f2009-03-12 23:59:55 +0000166 if (isNegative)
167 return -(int) absExponent;
168 else
169 return (int) absExponent;
170}
171
172/* This is ugly and needs cleaning up, but I don't immediately see
173 how whilst remaining safe. */
174static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000175totalExponent(StringRef::iterator p, StringRef::iterator end,
176 int exponentAdjustment)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000177{
178 int unsignedExponent;
179 bool negative, overflow;
Ted Kremenek584520e2011-01-23 17:05:06 +0000180 int exponent = 0;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000181
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000182 assert(p != end && "Exponent has no digits");
183
Chris Lattnere213f3f2009-03-12 23:59:55 +0000184 negative = *p == '-';
Dan Gohman16e02092010-03-24 19:38:02 +0000185 if (*p == '-' || *p == '+') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000186 p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000187 assert(p != end && "Exponent has no digits");
188 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000189
190 unsignedExponent = 0;
191 overflow = false;
Dan Gohman16e02092010-03-24 19:38:02 +0000192 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000193 unsigned int value;
194
195 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000196 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000197
Chris Lattnere213f3f2009-03-12 23:59:55 +0000198 unsignedExponent = unsignedExponent * 10 + value;
Richard Smithb080e2f2012-08-24 00:01:19 +0000199 if (unsignedExponent > 32767) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000200 overflow = true;
Richard Smithb080e2f2012-08-24 00:01:19 +0000201 break;
202 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000203 }
204
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000205 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000206 overflow = true;
207
Dan Gohman16e02092010-03-24 19:38:02 +0000208 if (!overflow) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000209 exponent = unsignedExponent;
Dan Gohman16e02092010-03-24 19:38:02 +0000210 if (negative)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000211 exponent = -exponent;
212 exponent += exponentAdjustment;
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000213 if (exponent > 32767 || exponent < -32768)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000214 overflow = true;
215 }
216
Dan Gohman16e02092010-03-24 19:38:02 +0000217 if (overflow)
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000218 exponent = negative ? -32768: 32767;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000219
220 return exponent;
221}
222
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000223static StringRef::iterator
224skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
225 StringRef::iterator *dot)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000226{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000227 StringRef::iterator p = begin;
228 *dot = end;
Dan Gohman16e02092010-03-24 19:38:02 +0000229 while (*p == '0' && p != end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000230 p++;
231
Dan Gohman16e02092010-03-24 19:38:02 +0000232 if (*p == '.') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000233 *dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000234
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000235 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000236
Dan Gohman16e02092010-03-24 19:38:02 +0000237 while (*p == '0' && p != end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000238 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000239 }
240
Chris Lattnere213f3f2009-03-12 23:59:55 +0000241 return p;
242}
Neil Booth1870f292007-10-14 10:16:12 +0000243
Chris Lattnere213f3f2009-03-12 23:59:55 +0000244/* Given a normal decimal floating point number of the form
Neil Booth1870f292007-10-14 10:16:12 +0000245
Chris Lattnere213f3f2009-03-12 23:59:55 +0000246 dddd.dddd[eE][+-]ddd
Neil Booth686700e2007-10-15 15:00:55 +0000247
Chris Lattnere213f3f2009-03-12 23:59:55 +0000248 where the decimal point and exponent are optional, fill out the
249 structure D. Exponent is appropriate if the significand is
250 treated as an integer, and normalizedExponent if the significand
251 is taken to have the decimal point after a single leading
252 non-zero digit.
Neil Booth1870f292007-10-14 10:16:12 +0000253
Chris Lattnere213f3f2009-03-12 23:59:55 +0000254 If the value is zero, V->firstSigDigit points to a non-digit, and
255 the return exponent is zero.
256*/
257struct decimalInfo {
258 const char *firstSigDigit;
259 const char *lastSigDigit;
260 int exponent;
261 int normalizedExponent;
262};
Neil Booth1870f292007-10-14 10:16:12 +0000263
Chris Lattnere213f3f2009-03-12 23:59:55 +0000264static void
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000265interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
266 decimalInfo *D)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000267{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000268 StringRef::iterator dot = end;
269 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth1870f292007-10-14 10:16:12 +0000270
Chris Lattnere213f3f2009-03-12 23:59:55 +0000271 D->firstSigDigit = p;
272 D->exponent = 0;
273 D->normalizedExponent = 0;
274
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000275 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000276 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000277 assert(dot == end && "String contains multiple dots");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000278 dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000279 if (p == end)
280 break;
Neil Booth1870f292007-10-14 10:16:12 +0000281 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000282 if (decDigitValue(*p) >= 10U)
283 break;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000284 }
Neil Booth1870f292007-10-14 10:16:12 +0000285
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000286 if (p != end) {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000287 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
288 assert(p != begin && "Significand has no digits");
289 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000290
291 /* p points to the first non-digit in the string */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000292 D->exponent = readExponent(p + 1, end);
Neil Booth1870f292007-10-14 10:16:12 +0000293
Chris Lattnere213f3f2009-03-12 23:59:55 +0000294 /* Implied decimal point? */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000295 if (dot == end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000296 dot = p;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000297 }
Neil Booth1870f292007-10-14 10:16:12 +0000298
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000299 /* If number is all zeroes accept any exponent. */
300 if (p != D->firstSigDigit) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000301 /* Drop insignificant trailing zeroes. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000302 if (p != begin) {
Neil Booth1870f292007-10-14 10:16:12 +0000303 do
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000304 do
305 p--;
306 while (p != begin && *p == '0');
307 while (p != begin && *p == '.');
308 }
Neil Booth1870f292007-10-14 10:16:12 +0000309
Chris Lattnere213f3f2009-03-12 23:59:55 +0000310 /* Adjust the exponents for any decimal point. */
311 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
312 D->normalizedExponent = (D->exponent +
313 static_cast<exponent_t>((p - D->firstSigDigit)
314 - (dot > D->firstSigDigit && dot < p)));
Neil Booth1870f292007-10-14 10:16:12 +0000315 }
316
Chris Lattnere213f3f2009-03-12 23:59:55 +0000317 D->lastSigDigit = p;
318}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000319
Chris Lattnere213f3f2009-03-12 23:59:55 +0000320/* Return the trailing fraction of a hexadecimal number.
321 DIGITVALUE is the first hex digit of the fraction, P points to
322 the next digit. */
323static lostFraction
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000324trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
325 unsigned int digitValue)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000326{
327 unsigned int hexDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000328
Chris Lattnere213f3f2009-03-12 23:59:55 +0000329 /* If the first trailing digit isn't 0 or 8 we can work out the
330 fraction immediately. */
Dan Gohman16e02092010-03-24 19:38:02 +0000331 if (digitValue > 8)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000332 return lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000333 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000334 return lfLessThanHalf;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000335
336 /* Otherwise we need to find the first non-zero digit. */
Dan Gohman16e02092010-03-24 19:38:02 +0000337 while (*p == '0')
Chris Lattnere213f3f2009-03-12 23:59:55 +0000338 p++;
339
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000340 assert(p != end && "Invalid trailing hexadecimal fraction!");
341
Chris Lattnere213f3f2009-03-12 23:59:55 +0000342 hexDigit = hexDigitValue(*p);
343
344 /* If we ran off the end it is exactly zero or one-half, otherwise
345 a little more. */
Dan Gohman16e02092010-03-24 19:38:02 +0000346 if (hexDigit == -1U)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000347 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
348 else
349 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
350}
351
352/* Return the fraction lost were a bignum truncated losing the least
353 significant BITS bits. */
354static lostFraction
355lostFractionThroughTruncation(const integerPart *parts,
356 unsigned int partCount,
357 unsigned int bits)
358{
359 unsigned int lsb;
360
361 lsb = APInt::tcLSB(parts, partCount);
362
363 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohman16e02092010-03-24 19:38:02 +0000364 if (bits <= lsb)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000365 return lfExactlyZero;
Dan Gohman16e02092010-03-24 19:38:02 +0000366 if (bits == lsb + 1)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000367 return lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000368 if (bits <= partCount * integerPartWidth &&
369 APInt::tcExtractBit(parts, bits - 1))
Chris Lattnere213f3f2009-03-12 23:59:55 +0000370 return lfMoreThanHalf;
371
372 return lfLessThanHalf;
373}
374
375/* Shift DST right BITS bits noting lost fraction. */
376static lostFraction
377shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
378{
379 lostFraction lost_fraction;
380
381 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
382
383 APInt::tcShiftRight(dst, parts, bits);
384
385 return lost_fraction;
386}
387
388/* Combine the effect of two lost fractions. */
389static lostFraction
390combineLostFractions(lostFraction moreSignificant,
391 lostFraction lessSignificant)
392{
Dan Gohman16e02092010-03-24 19:38:02 +0000393 if (lessSignificant != lfExactlyZero) {
394 if (moreSignificant == lfExactlyZero)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000395 moreSignificant = lfLessThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000396 else if (moreSignificant == lfExactlyHalf)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000397 moreSignificant = lfMoreThanHalf;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000398 }
399
Chris Lattnere213f3f2009-03-12 23:59:55 +0000400 return moreSignificant;
401}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000402
Chris Lattnere213f3f2009-03-12 23:59:55 +0000403/* The error from the true value, in half-ulps, on multiplying two
404 floating point numbers, which differ from the value they
405 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
406 than the returned value.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000407
Chris Lattnere213f3f2009-03-12 23:59:55 +0000408 See "How to Read Floating Point Numbers Accurately" by William D
409 Clinger. */
410static unsigned int
411HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
412{
413 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000414
Chris Lattnere213f3f2009-03-12 23:59:55 +0000415 if (HUerr1 + HUerr2 == 0)
416 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
417 else
418 return inexactMultiply + 2 * (HUerr1 + HUerr2);
419}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000420
Chris Lattnere213f3f2009-03-12 23:59:55 +0000421/* The number of ulps from the boundary (zero, or half if ISNEAREST)
422 when the least significant BITS are truncated. BITS cannot be
423 zero. */
424static integerPart
425ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
426{
427 unsigned int count, partBits;
428 integerPart part, boundary;
Neil Booth33d4c922007-10-07 08:51:21 +0000429
Evan Cheng99ebfa52009-10-27 21:35:42 +0000430 assert(bits != 0);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000431
Chris Lattnere213f3f2009-03-12 23:59:55 +0000432 bits--;
433 count = bits / integerPartWidth;
434 partBits = bits % integerPartWidth + 1;
Neil Booth96c74712007-10-12 16:02:31 +0000435
Chris Lattnere213f3f2009-03-12 23:59:55 +0000436 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Booth96c74712007-10-12 16:02:31 +0000437
Chris Lattnere213f3f2009-03-12 23:59:55 +0000438 if (isNearest)
439 boundary = (integerPart) 1 << (partBits - 1);
440 else
441 boundary = 0;
442
443 if (count == 0) {
444 if (part - boundary <= boundary - part)
445 return part - boundary;
Neil Booth96c74712007-10-12 16:02:31 +0000446 else
Chris Lattnere213f3f2009-03-12 23:59:55 +0000447 return boundary - part;
Neil Booth96c74712007-10-12 16:02:31 +0000448 }
449
Chris Lattnere213f3f2009-03-12 23:59:55 +0000450 if (part == boundary) {
451 while (--count)
452 if (parts[count])
453 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000454
Chris Lattnere213f3f2009-03-12 23:59:55 +0000455 return parts[0];
456 } else if (part == boundary - 1) {
457 while (--count)
458 if (~parts[count])
459 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000460
Chris Lattnere213f3f2009-03-12 23:59:55 +0000461 return -parts[0];
462 }
Neil Booth96c74712007-10-12 16:02:31 +0000463
Chris Lattnere213f3f2009-03-12 23:59:55 +0000464 return ~(integerPart) 0; /* A lot. */
465}
Neil Booth96c74712007-10-12 16:02:31 +0000466
Chris Lattnere213f3f2009-03-12 23:59:55 +0000467/* Place pow(5, power) in DST, and return the number of parts used.
468 DST must be at least one part larger than size of the answer. */
469static unsigned int
470powerOf5(integerPart *dst, unsigned int power)
471{
472 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
473 15625, 78125 };
Chris Lattneree167a72009-03-13 00:24:01 +0000474 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
475 pow5s[0] = 78125 * 5;
Dan Gohman16e02092010-03-24 19:38:02 +0000476
Chris Lattner807926a2009-03-13 00:03:51 +0000477 unsigned int partsCount[16] = { 1 };
Chris Lattnere213f3f2009-03-12 23:59:55 +0000478 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
479 unsigned int result;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000480 assert(power <= maxExponent);
481
482 p1 = dst;
483 p2 = scratch;
484
485 *p1 = firstEightPowers[power & 7];
486 power >>= 3;
487
488 result = 1;
489 pow5 = pow5s;
490
491 for (unsigned int n = 0; power; power >>= 1, n++) {
492 unsigned int pc;
493
494 pc = partsCount[n];
495
496 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
497 if (pc == 0) {
498 pc = partsCount[n - 1];
499 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
500 pc *= 2;
501 if (pow5[pc - 1] == 0)
502 pc--;
503 partsCount[n] = pc;
Neil Booth96c74712007-10-12 16:02:31 +0000504 }
505
Chris Lattnere213f3f2009-03-12 23:59:55 +0000506 if (power & 1) {
507 integerPart *tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000508
Chris Lattnere213f3f2009-03-12 23:59:55 +0000509 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
510 result += pc;
511 if (p2[result - 1] == 0)
512 result--;
Neil Booth96c74712007-10-12 16:02:31 +0000513
Chris Lattnere213f3f2009-03-12 23:59:55 +0000514 /* Now result is in p1 with partsCount parts and p2 is scratch
515 space. */
516 tmp = p1, p1 = p2, p2 = tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000517 }
518
Chris Lattnere213f3f2009-03-12 23:59:55 +0000519 pow5 += pc;
Neil Booth96c74712007-10-12 16:02:31 +0000520 }
521
Chris Lattnere213f3f2009-03-12 23:59:55 +0000522 if (p1 != dst)
523 APInt::tcAssign(dst, p1, result);
Neil Booth96c74712007-10-12 16:02:31 +0000524
Chris Lattnere213f3f2009-03-12 23:59:55 +0000525 return result;
526}
Neil Booth96c74712007-10-12 16:02:31 +0000527
Chris Lattnere213f3f2009-03-12 23:59:55 +0000528/* Zero at the end to avoid modular arithmetic when adding one; used
529 when rounding up during hexadecimal output. */
530static const char hexDigitsLower[] = "0123456789abcdef0";
531static const char hexDigitsUpper[] = "0123456789ABCDEF0";
532static const char infinityL[] = "infinity";
533static const char infinityU[] = "INFINITY";
534static const char NaNL[] = "nan";
535static const char NaNU[] = "NAN";
Neil Booth96c74712007-10-12 16:02:31 +0000536
Chris Lattnere213f3f2009-03-12 23:59:55 +0000537/* Write out an integerPart in hexadecimal, starting with the most
538 significant nibble. Write out exactly COUNT hexdigits, return
539 COUNT. */
540static unsigned int
541partAsHex (char *dst, integerPart part, unsigned int count,
542 const char *hexDigitChars)
543{
544 unsigned int result = count;
Neil Booth96c74712007-10-12 16:02:31 +0000545
Evan Cheng99ebfa52009-10-27 21:35:42 +0000546 assert(count != 0 && count <= integerPartWidth / 4);
Neil Booth96c74712007-10-12 16:02:31 +0000547
Chris Lattnere213f3f2009-03-12 23:59:55 +0000548 part >>= (integerPartWidth - 4 * count);
549 while (count--) {
550 dst[count] = hexDigitChars[part & 0xf];
551 part >>= 4;
Neil Booth96c74712007-10-12 16:02:31 +0000552 }
553
Chris Lattnere213f3f2009-03-12 23:59:55 +0000554 return result;
555}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000556
Chris Lattnere213f3f2009-03-12 23:59:55 +0000557/* Write out an unsigned decimal integer. */
558static char *
559writeUnsignedDecimal (char *dst, unsigned int n)
560{
561 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000562
Chris Lattnere213f3f2009-03-12 23:59:55 +0000563 p = buff;
564 do
565 *p++ = '0' + n % 10;
566 while (n /= 10);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000567
Chris Lattnere213f3f2009-03-12 23:59:55 +0000568 do
569 *dst++ = *--p;
570 while (p != buff);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000571
Chris Lattnere213f3f2009-03-12 23:59:55 +0000572 return dst;
573}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000574
Chris Lattnere213f3f2009-03-12 23:59:55 +0000575/* Write out a signed decimal integer. */
576static char *
577writeSignedDecimal (char *dst, int value)
578{
579 if (value < 0) {
580 *dst++ = '-';
581 dst = writeUnsignedDecimal(dst, -(unsigned) value);
582 } else
583 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000584
Chris Lattnere213f3f2009-03-12 23:59:55 +0000585 return dst;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000586}
587
588/* Constructors. */
589void
590APFloat::initialize(const fltSemantics *ourSemantics)
591{
592 unsigned int count;
593
594 semantics = ourSemantics;
595 count = partCount();
Dan Gohman16e02092010-03-24 19:38:02 +0000596 if (count > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000597 significand.parts = new integerPart[count];
598}
599
600void
601APFloat::freeSignificand()
602{
Dan Gohman16e02092010-03-24 19:38:02 +0000603 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000604 delete [] significand.parts;
605}
606
607void
608APFloat::assign(const APFloat &rhs)
609{
610 assert(semantics == rhs.semantics);
611
612 sign = rhs.sign;
613 category = rhs.category;
614 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000615 sign2 = rhs.sign2;
616 exponent2 = rhs.exponent2;
Dan Gohman16e02092010-03-24 19:38:02 +0000617 if (category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000618 copySignificand(rhs);
619}
620
621void
622APFloat::copySignificand(const APFloat &rhs)
623{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000624 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000625 assert(rhs.partCount() >= partCount());
626
627 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000628 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000629}
630
Neil Boothe5e01942007-10-14 10:39:51 +0000631/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen541ed9f2009-01-21 20:32:55 +0000632 for the significand. If double or longer, this is a signalling NaN,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000633 which may not be ideal. If float, this is QNaN(0). */
John McCalle12b7382010-02-28 02:51:25 +0000634void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Boothe5e01942007-10-14 10:39:51 +0000635{
636 category = fcNaN;
John McCalle12b7382010-02-28 02:51:25 +0000637 sign = Negative;
638
John McCall165e96b2010-02-28 12:49:50 +0000639 integerPart *significand = significandParts();
640 unsigned numParts = partCount();
641
John McCalle12b7382010-02-28 02:51:25 +0000642 // Set the significand bits to the fill.
John McCall165e96b2010-02-28 12:49:50 +0000643 if (!fill || fill->getNumWords() < numParts)
644 APInt::tcSet(significand, 0, numParts);
645 if (fill) {
John McCalld44c6cc2010-03-01 18:38:45 +0000646 APInt::tcAssign(significand, fill->getRawData(),
647 std::min(fill->getNumWords(), numParts));
John McCall165e96b2010-02-28 12:49:50 +0000648
649 // Zero out the excess bits of the significand.
650 unsigned bitsToPreserve = semantics->precision - 1;
651 unsigned part = bitsToPreserve / 64;
652 bitsToPreserve %= 64;
653 significand[part] &= ((1ULL << bitsToPreserve) - 1);
654 for (part++; part != numParts; ++part)
655 significand[part] = 0;
656 }
657
658 unsigned QNaNBit = semantics->precision - 2;
John McCalle12b7382010-02-28 02:51:25 +0000659
660 if (SNaN) {
661 // We always have to clear the QNaN bit to make it an SNaN.
John McCall165e96b2010-02-28 12:49:50 +0000662 APInt::tcClearBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000663
664 // If there are no bits set in the payload, we have to set
665 // *something* to make it a NaN instead of an infinity;
666 // conventionally, this is the next bit down from the QNaN bit.
John McCall165e96b2010-02-28 12:49:50 +0000667 if (APInt::tcIsZero(significand, numParts))
668 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalle12b7382010-02-28 02:51:25 +0000669 } else {
670 // We always have to set the QNaN bit to make it a QNaN.
John McCall165e96b2010-02-28 12:49:50 +0000671 APInt::tcSetBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000672 }
John McCall165e96b2010-02-28 12:49:50 +0000673
674 // For x87 extended precision, we want to make a NaN, not a
675 // pseudo-NaN. Maybe we should expose the ability to make
676 // pseudo-NaNs?
677 if (semantics == &APFloat::x87DoubleExtended)
678 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalle12b7382010-02-28 02:51:25 +0000679}
680
681APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
682 const APInt *fill) {
683 APFloat value(Sem, uninitialized);
684 value.makeNaN(SNaN, Negative, fill);
685 return value;
Neil Boothe5e01942007-10-14 10:39:51 +0000686}
687
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000688APFloat &
689APFloat::operator=(const APFloat &rhs)
690{
Dan Gohman16e02092010-03-24 19:38:02 +0000691 if (this != &rhs) {
692 if (semantics != rhs.semantics) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000693 freeSignificand();
694 initialize(rhs.semantics);
695 }
696 assign(rhs);
697 }
698
699 return *this;
700}
701
Dale Johannesen343e7702007-08-24 00:56:33 +0000702bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000703APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000704 if (this == &rhs)
705 return true;
706 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000707 category != rhs.category ||
708 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000709 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000710 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000711 sign2 != rhs.sign2)
712 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000713 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000714 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000715 else if (category==fcNormal && exponent!=rhs.exponent)
716 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000717 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000718 exponent2!=rhs.exponent2)
719 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000720 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000721 int i= partCount();
722 const integerPart* p=significandParts();
723 const integerPart* q=rhs.significandParts();
724 for (; i>0; i--, p++, q++) {
725 if (*p != *q)
726 return false;
727 }
728 return true;
729 }
730}
731
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000732APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000733 : exponent2(0), sign2(0) {
Neil Boothcaf19d72007-10-14 10:29:28 +0000734 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000735 initialize(&ourSemantics);
736 sign = 0;
737 zeroSignificand();
738 exponent = ourSemantics.precision - 1;
739 significandParts()[0] = value;
740 normalize(rmNearestTiesToEven, lfExactlyZero);
741}
742
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000743APFloat::APFloat(const fltSemantics &ourSemantics) : exponent2(0), sign2(0) {
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000744 assertArithmeticOK(ourSemantics);
745 initialize(&ourSemantics);
746 category = fcZero;
747 sign = false;
748}
749
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000750APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
751 : exponent2(0), sign2(0) {
John McCalle12b7382010-02-28 02:51:25 +0000752 assertArithmeticOK(ourSemantics);
753 // Allocates storage if necessary but does not initialize it.
754 initialize(&ourSemantics);
755}
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000756
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000757APFloat::APFloat(const fltSemantics &ourSemantics,
John McCalle12b7382010-02-28 02:51:25 +0000758 fltCategory ourCategory, bool negative)
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000759 : exponent2(0), sign2(0) {
Neil Boothcaf19d72007-10-14 10:29:28 +0000760 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000761 initialize(&ourSemantics);
762 category = ourCategory;
763 sign = negative;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000764 if (category == fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000765 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000766 else if (ourCategory == fcNaN)
John McCalle12b7382010-02-28 02:51:25 +0000767 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000768}
769
Benjamin Kramer38e59892010-07-14 22:38:02 +0000770APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text)
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000771 : exponent2(0), sign2(0) {
Neil Boothcaf19d72007-10-14 10:29:28 +0000772 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000773 initialize(&ourSemantics);
774 convertFromString(text, rmNearestTiesToEven);
775}
776
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000777APFloat::APFloat(const APFloat &rhs) : exponent2(0), sign2(0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000778 initialize(rhs.semantics);
779 assign(rhs);
780}
781
782APFloat::~APFloat()
783{
784 freeSignificand();
785}
786
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000787// Profile - This method 'profiles' an APFloat for use with FoldingSet.
788void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000789 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000790}
791
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000792unsigned int
793APFloat::partCount() const
794{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000795 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000796}
797
798unsigned int
799APFloat::semanticsPrecision(const fltSemantics &semantics)
800{
801 return semantics.precision;
802}
803
804const integerPart *
805APFloat::significandParts() const
806{
807 return const_cast<APFloat *>(this)->significandParts();
808}
809
810integerPart *
811APFloat::significandParts()
812{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000813 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000814
Evan Cheng99ebfa52009-10-27 21:35:42 +0000815 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000816 return significand.parts;
817 else
818 return &significand.part;
819}
820
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000821void
822APFloat::zeroSignificand()
823{
824 category = fcNormal;
825 APInt::tcSet(significandParts(), 0, partCount());
826}
827
828/* Increment an fcNormal floating point number's significand. */
829void
830APFloat::incrementSignificand()
831{
832 integerPart carry;
833
834 carry = APInt::tcIncrement(significandParts(), partCount());
835
836 /* Our callers should never cause us to overflow. */
837 assert(carry == 0);
Duncan Sands1f6a3292011-08-12 14:54:45 +0000838 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000839}
840
841/* Add the significand of the RHS. Returns the carry flag. */
842integerPart
843APFloat::addSignificand(const APFloat &rhs)
844{
845 integerPart *parts;
846
847 parts = significandParts();
848
849 assert(semantics == rhs.semantics);
850 assert(exponent == rhs.exponent);
851
852 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
853}
854
855/* Subtract the significand of the RHS with a borrow flag. Returns
856 the borrow flag. */
857integerPart
858APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
859{
860 integerPart *parts;
861
862 parts = significandParts();
863
864 assert(semantics == rhs.semantics);
865 assert(exponent == rhs.exponent);
866
867 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000868 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000869}
870
871/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
872 on to the full-precision result of the multiplication. Returns the
873 lost fraction. */
874lostFraction
875APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
876{
Neil Booth4f881702007-09-26 21:33:42 +0000877 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000878 unsigned int partsCount, newPartsCount, precision;
879 integerPart *lhsSignificand;
880 integerPart scratch[4];
881 integerPart *fullSignificand;
882 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000883 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000884
885 assert(semantics == rhs.semantics);
886
887 precision = semantics->precision;
888 newPartsCount = partCountForBits(precision * 2);
889
Dan Gohman16e02092010-03-24 19:38:02 +0000890 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000891 fullSignificand = new integerPart[newPartsCount];
892 else
893 fullSignificand = scratch;
894
895 lhsSignificand = significandParts();
896 partsCount = partCount();
897
898 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000899 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000900
901 lost_fraction = lfExactlyZero;
902 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
903 exponent += rhs.exponent;
904
Dan Gohman16e02092010-03-24 19:38:02 +0000905 if (addend) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000906 Significand savedSignificand = significand;
907 const fltSemantics *savedSemantics = semantics;
908 fltSemantics extendedSemantics;
909 opStatus status;
910 unsigned int extendedPrecision;
911
912 /* Normalize our MSB. */
913 extendedPrecision = precision + precision - 1;
Dan Gohman16e02092010-03-24 19:38:02 +0000914 if (omsb != extendedPrecision) {
915 APInt::tcShiftLeft(fullSignificand, newPartsCount,
916 extendedPrecision - omsb);
917 exponent -= extendedPrecision - omsb;
918 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000919
920 /* Create new semantics. */
921 extendedSemantics = *semantics;
922 extendedSemantics.precision = extendedPrecision;
923
Dan Gohman16e02092010-03-24 19:38:02 +0000924 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000925 significand.part = fullSignificand[0];
926 else
927 significand.parts = fullSignificand;
928 semantics = &extendedSemantics;
929
930 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000931 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000932 assert(status == opOK);
Duncan Sands1f6a3292011-08-12 14:54:45 +0000933 (void)status;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000934 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
935
936 /* Restore our state. */
Dan Gohman16e02092010-03-24 19:38:02 +0000937 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000938 fullSignificand[0] = significand.part;
939 significand = savedSignificand;
940 semantics = savedSemantics;
941
942 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
943 }
944
945 exponent -= (precision - 1);
946
Dan Gohman16e02092010-03-24 19:38:02 +0000947 if (omsb > precision) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000948 unsigned int bits, significantParts;
949 lostFraction lf;
950
951 bits = omsb - precision;
952 significantParts = partCountForBits(omsb);
953 lf = shiftRight(fullSignificand, significantParts, bits);
954 lost_fraction = combineLostFractions(lf, lost_fraction);
955 exponent += bits;
956 }
957
958 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
959
Dan Gohman16e02092010-03-24 19:38:02 +0000960 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000961 delete [] fullSignificand;
962
963 return lost_fraction;
964}
965
966/* Multiply the significands of LHS and RHS to DST. */
967lostFraction
968APFloat::divideSignificand(const APFloat &rhs)
969{
970 unsigned int bit, i, partsCount;
971 const integerPart *rhsSignificand;
972 integerPart *lhsSignificand, *dividend, *divisor;
973 integerPart scratch[4];
974 lostFraction lost_fraction;
975
976 assert(semantics == rhs.semantics);
977
978 lhsSignificand = significandParts();
979 rhsSignificand = rhs.significandParts();
980 partsCount = partCount();
981
Dan Gohman16e02092010-03-24 19:38:02 +0000982 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000983 dividend = new integerPart[partsCount * 2];
984 else
985 dividend = scratch;
986
987 divisor = dividend + partsCount;
988
989 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohman16e02092010-03-24 19:38:02 +0000990 for (i = 0; i < partsCount; i++) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000991 dividend[i] = lhsSignificand[i];
992 divisor[i] = rhsSignificand[i];
993 lhsSignificand[i] = 0;
994 }
995
996 exponent -= rhs.exponent;
997
998 unsigned int precision = semantics->precision;
999
1000 /* Normalize the divisor. */
1001 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohman16e02092010-03-24 19:38:02 +00001002 if (bit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001003 exponent += bit;
1004 APInt::tcShiftLeft(divisor, partsCount, bit);
1005 }
1006
1007 /* Normalize the dividend. */
1008 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohman16e02092010-03-24 19:38:02 +00001009 if (bit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001010 exponent -= bit;
1011 APInt::tcShiftLeft(dividend, partsCount, bit);
1012 }
1013
Neil Booth96c74712007-10-12 16:02:31 +00001014 /* Ensure the dividend >= divisor initially for the loop below.
1015 Incidentally, this means that the division loop below is
1016 guaranteed to set the integer bit to one. */
Dan Gohman16e02092010-03-24 19:38:02 +00001017 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001018 exponent--;
1019 APInt::tcShiftLeft(dividend, partsCount, 1);
1020 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1021 }
1022
1023 /* Long division. */
Dan Gohman16e02092010-03-24 19:38:02 +00001024 for (bit = precision; bit; bit -= 1) {
1025 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001026 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1027 APInt::tcSetBit(lhsSignificand, bit - 1);
1028 }
1029
1030 APInt::tcShiftLeft(dividend, partsCount, 1);
1031 }
1032
1033 /* Figure out the lost fraction. */
1034 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1035
Dan Gohman16e02092010-03-24 19:38:02 +00001036 if (cmp > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001037 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001038 else if (cmp == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001039 lost_fraction = lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001040 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001041 lost_fraction = lfExactlyZero;
1042 else
1043 lost_fraction = lfLessThanHalf;
1044
Dan Gohman16e02092010-03-24 19:38:02 +00001045 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001046 delete [] dividend;
1047
1048 return lost_fraction;
1049}
1050
1051unsigned int
1052APFloat::significandMSB() const
1053{
1054 return APInt::tcMSB(significandParts(), partCount());
1055}
1056
1057unsigned int
1058APFloat::significandLSB() const
1059{
1060 return APInt::tcLSB(significandParts(), partCount());
1061}
1062
1063/* Note that a zero result is NOT normalized to fcZero. */
1064lostFraction
1065APFloat::shiftSignificandRight(unsigned int bits)
1066{
1067 /* Our exponent should not overflow. */
1068 assert((exponent_t) (exponent + bits) >= exponent);
1069
1070 exponent += bits;
1071
1072 return shiftRight(significandParts(), partCount(), bits);
1073}
1074
1075/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1076void
1077APFloat::shiftSignificandLeft(unsigned int bits)
1078{
1079 assert(bits < semantics->precision);
1080
Dan Gohman16e02092010-03-24 19:38:02 +00001081 if (bits) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001082 unsigned int partsCount = partCount();
1083
1084 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1085 exponent -= bits;
1086
1087 assert(!APInt::tcIsZero(significandParts(), partsCount));
1088 }
1089}
1090
1091APFloat::cmpResult
1092APFloat::compareAbsoluteValue(const APFloat &rhs) const
1093{
1094 int compare;
1095
1096 assert(semantics == rhs.semantics);
1097 assert(category == fcNormal);
1098 assert(rhs.category == fcNormal);
1099
1100 compare = exponent - rhs.exponent;
1101
1102 /* If exponents are equal, do an unsigned bignum comparison of the
1103 significands. */
Dan Gohman16e02092010-03-24 19:38:02 +00001104 if (compare == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001105 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001106 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001107
Dan Gohman16e02092010-03-24 19:38:02 +00001108 if (compare > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001109 return cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001110 else if (compare < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001111 return cmpLessThan;
1112 else
1113 return cmpEqual;
1114}
1115
1116/* Handle overflow. Sign is preserved. We either become infinity or
1117 the largest finite number. */
1118APFloat::opStatus
1119APFloat::handleOverflow(roundingMode rounding_mode)
1120{
1121 /* Infinity? */
Dan Gohman16e02092010-03-24 19:38:02 +00001122 if (rounding_mode == rmNearestTiesToEven ||
1123 rounding_mode == rmNearestTiesToAway ||
1124 (rounding_mode == rmTowardPositive && !sign) ||
1125 (rounding_mode == rmTowardNegative && sign)) {
1126 category = fcInfinity;
1127 return (opStatus) (opOverflow | opInexact);
1128 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001129
1130 /* Otherwise we become the largest finite number. */
1131 category = fcNormal;
1132 exponent = semantics->maxExponent;
1133 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001134 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001135
1136 return opInexact;
1137}
1138
Neil Boothb7dea4c2007-10-03 15:16:41 +00001139/* Returns TRUE if, when truncating the current number, with BIT the
1140 new LSB, with the given lost fraction and rounding mode, the result
1141 would need to be rounded away from zero (i.e., by increasing the
1142 signficand). This routine must work for fcZero of both signs, and
1143 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001144bool
1145APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001146 lostFraction lost_fraction,
1147 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001148{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001149 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001150 assert(category == fcNormal || category == fcZero);
1151
Neil Boothb7dea4c2007-10-03 15:16:41 +00001152 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001153 assert(lost_fraction != lfExactlyZero);
1154
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001155 switch (rounding_mode) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001156 case rmNearestTiesToAway:
1157 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1158
1159 case rmNearestTiesToEven:
Dan Gohman16e02092010-03-24 19:38:02 +00001160 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001161 return true;
1162
1163 /* Our zeroes don't have a significand to test. */
Dan Gohman16e02092010-03-24 19:38:02 +00001164 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001165 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001166
1167 return false;
1168
1169 case rmTowardZero:
1170 return false;
1171
1172 case rmTowardPositive:
1173 return sign == false;
1174
1175 case rmTowardNegative:
1176 return sign == true;
1177 }
Chandler Carruth732f05c2012-01-10 18:08:01 +00001178 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001179}
1180
1181APFloat::opStatus
1182APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001183 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001184{
Neil Booth4f881702007-09-26 21:33:42 +00001185 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001186 int exponentChange;
1187
Dan Gohman16e02092010-03-24 19:38:02 +00001188 if (category != fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001189 return opOK;
1190
1191 /* Before rounding normalize the exponent of fcNormal numbers. */
1192 omsb = significandMSB() + 1;
1193
Dan Gohman16e02092010-03-24 19:38:02 +00001194 if (omsb) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001195 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewycky03dd4e82011-10-03 21:30:08 +00001196 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001197 the exponent. */
1198 exponentChange = omsb - semantics->precision;
1199
1200 /* If the resulting exponent is too high, overflow according to
1201 the rounding mode. */
Dan Gohman16e02092010-03-24 19:38:02 +00001202 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001203 return handleOverflow(rounding_mode);
1204
1205 /* Subnormal numbers have exponent minExponent, and their MSB
1206 is forced based on that. */
Dan Gohman16e02092010-03-24 19:38:02 +00001207 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001208 exponentChange = semantics->minExponent - exponent;
1209
1210 /* Shifting left is easy as we don't lose precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001211 if (exponentChange < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001212 assert(lost_fraction == lfExactlyZero);
1213
1214 shiftSignificandLeft(-exponentChange);
1215
1216 return opOK;
1217 }
1218
Dan Gohman16e02092010-03-24 19:38:02 +00001219 if (exponentChange > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001220 lostFraction lf;
1221
1222 /* Shift right and capture any new lost fraction. */
1223 lf = shiftSignificandRight(exponentChange);
1224
1225 lost_fraction = combineLostFractions(lf, lost_fraction);
1226
1227 /* Keep OMSB up-to-date. */
Dan Gohman16e02092010-03-24 19:38:02 +00001228 if (omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001229 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001230 else
Neil Booth4f881702007-09-26 21:33:42 +00001231 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001232 }
1233 }
1234
1235 /* Now round the number according to rounding_mode given the lost
1236 fraction. */
1237
1238 /* As specified in IEEE 754, since we do not trap we do not report
1239 underflow for exact results. */
Dan Gohman16e02092010-03-24 19:38:02 +00001240 if (lost_fraction == lfExactlyZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001241 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001242 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001243 category = fcZero;
1244
1245 return opOK;
1246 }
1247
1248 /* Increment the significand if we're rounding away from zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001249 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1250 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001251 exponent = semantics->minExponent;
1252
1253 incrementSignificand();
1254 omsb = significandMSB() + 1;
1255
1256 /* Did the significand increment overflow? */
Dan Gohman16e02092010-03-24 19:38:02 +00001257 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001258 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001259 significand right one. However if we already have the
1260 maximum exponent we overflow to infinity. */
Dan Gohman16e02092010-03-24 19:38:02 +00001261 if (exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001262 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001263
Neil Booth4f881702007-09-26 21:33:42 +00001264 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001265 }
1266
1267 shiftSignificandRight(1);
1268
1269 return opInexact;
1270 }
1271 }
1272
1273 /* The normal case - we were and are not denormal, and any
1274 significand increment above didn't overflow. */
Dan Gohman16e02092010-03-24 19:38:02 +00001275 if (omsb == semantics->precision)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001276 return opInexact;
1277
1278 /* We have a non-zero denormal. */
1279 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001280
1281 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001282 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001283 category = fcZero;
1284
1285 /* The fcZero case is a denormal that underflowed to zero. */
1286 return (opStatus) (opUnderflow | opInexact);
1287}
1288
1289APFloat::opStatus
1290APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1291{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001292 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001293 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001294 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001295
Dale Johanneseneaf08942007-08-31 04:03:46 +00001296 case convolve(fcNaN, fcZero):
1297 case convolve(fcNaN, fcNormal):
1298 case convolve(fcNaN, fcInfinity):
1299 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001300 case convolve(fcNormal, fcZero):
1301 case convolve(fcInfinity, fcNormal):
1302 case convolve(fcInfinity, fcZero):
1303 return opOK;
1304
Dale Johanneseneaf08942007-08-31 04:03:46 +00001305 case convolve(fcZero, fcNaN):
1306 case convolve(fcNormal, fcNaN):
1307 case convolve(fcInfinity, fcNaN):
1308 category = fcNaN;
1309 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001310 return opOK;
1311
1312 case convolve(fcNormal, fcInfinity):
1313 case convolve(fcZero, fcInfinity):
1314 category = fcInfinity;
1315 sign = rhs.sign ^ subtract;
1316 return opOK;
1317
1318 case convolve(fcZero, fcNormal):
1319 assign(rhs);
1320 sign = rhs.sign ^ subtract;
1321 return opOK;
1322
1323 case convolve(fcZero, fcZero):
1324 /* Sign depends on rounding mode; handled by caller. */
1325 return opOK;
1326
1327 case convolve(fcInfinity, fcInfinity):
1328 /* Differently signed infinities can only be validly
1329 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001330 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001331 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001332 return opInvalidOp;
1333 }
1334
1335 return opOK;
1336
1337 case convolve(fcNormal, fcNormal):
1338 return opDivByZero;
1339 }
1340}
1341
1342/* Add or subtract two normal numbers. */
1343lostFraction
1344APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1345{
1346 integerPart carry;
1347 lostFraction lost_fraction;
1348 int bits;
1349
1350 /* Determine if the operation on the absolute values is effectively
1351 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001352 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001353
1354 /* Are we bigger exponent-wise than the RHS? */
1355 bits = exponent - rhs.exponent;
1356
1357 /* Subtraction is more subtle than one might naively expect. */
Dan Gohman16e02092010-03-24 19:38:02 +00001358 if (subtract) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001359 APFloat temp_rhs(rhs);
1360 bool reverse;
1361
Chris Lattnerada530b2007-08-24 03:02:34 +00001362 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001363 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1364 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001365 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001366 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1367 shiftSignificandLeft(1);
1368 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001369 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001370 lost_fraction = shiftSignificandRight(-bits - 1);
1371 temp_rhs.shiftSignificandLeft(1);
1372 reverse = true;
1373 }
1374
Chris Lattnerada530b2007-08-24 03:02:34 +00001375 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001376 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001377 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001378 copySignificand(temp_rhs);
1379 sign = !sign;
1380 } else {
1381 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001382 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001383 }
1384
1385 /* Invert the lost fraction - it was on the RHS and
1386 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001387 if (lost_fraction == lfLessThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001388 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001389 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001390 lost_fraction = lfLessThanHalf;
1391
1392 /* The code above is intended to ensure that no borrow is
1393 necessary. */
1394 assert(!carry);
Duncan Sands1f6a3292011-08-12 14:54:45 +00001395 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001396 } else {
Dan Gohman16e02092010-03-24 19:38:02 +00001397 if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001398 APFloat temp_rhs(rhs);
1399
1400 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1401 carry = addSignificand(temp_rhs);
1402 } else {
1403 lost_fraction = shiftSignificandRight(-bits);
1404 carry = addSignificand(rhs);
1405 }
1406
1407 /* We have a guard bit; generating a carry cannot happen. */
1408 assert(!carry);
Duncan Sands1f6a3292011-08-12 14:54:45 +00001409 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001410 }
1411
1412 return lost_fraction;
1413}
1414
1415APFloat::opStatus
1416APFloat::multiplySpecials(const APFloat &rhs)
1417{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001418 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001419 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001420 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001421
Dale Johanneseneaf08942007-08-31 04:03:46 +00001422 case convolve(fcNaN, fcZero):
1423 case convolve(fcNaN, fcNormal):
1424 case convolve(fcNaN, fcInfinity):
1425 case convolve(fcNaN, fcNaN):
1426 return opOK;
1427
1428 case convolve(fcZero, fcNaN):
1429 case convolve(fcNormal, fcNaN):
1430 case convolve(fcInfinity, fcNaN):
1431 category = fcNaN;
1432 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001433 return opOK;
1434
1435 case convolve(fcNormal, fcInfinity):
1436 case convolve(fcInfinity, fcNormal):
1437 case convolve(fcInfinity, fcInfinity):
1438 category = fcInfinity;
1439 return opOK;
1440
1441 case convolve(fcZero, fcNormal):
1442 case convolve(fcNormal, fcZero):
1443 case convolve(fcZero, fcZero):
1444 category = fcZero;
1445 return opOK;
1446
1447 case convolve(fcZero, fcInfinity):
1448 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001449 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001450 return opInvalidOp;
1451
1452 case convolve(fcNormal, fcNormal):
1453 return opOK;
1454 }
1455}
1456
1457APFloat::opStatus
1458APFloat::divideSpecials(const APFloat &rhs)
1459{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001460 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001461 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001462 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001463
Dale Johanneseneaf08942007-08-31 04:03:46 +00001464 case convolve(fcNaN, fcZero):
1465 case convolve(fcNaN, fcNormal):
1466 case convolve(fcNaN, fcInfinity):
1467 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001468 case convolve(fcInfinity, fcZero):
1469 case convolve(fcInfinity, fcNormal):
1470 case convolve(fcZero, fcInfinity):
1471 case convolve(fcZero, fcNormal):
1472 return opOK;
1473
Dale Johanneseneaf08942007-08-31 04:03:46 +00001474 case convolve(fcZero, fcNaN):
1475 case convolve(fcNormal, fcNaN):
1476 case convolve(fcInfinity, fcNaN):
1477 category = fcNaN;
1478 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001479 return opOK;
1480
1481 case convolve(fcNormal, fcInfinity):
1482 category = fcZero;
1483 return opOK;
1484
1485 case convolve(fcNormal, fcZero):
1486 category = fcInfinity;
1487 return opDivByZero;
1488
1489 case convolve(fcInfinity, fcInfinity):
1490 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001491 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001492 return opInvalidOp;
1493
1494 case convolve(fcNormal, fcNormal):
1495 return opOK;
1496 }
1497}
1498
Dale Johannesened6af242009-01-21 00:35:19 +00001499APFloat::opStatus
1500APFloat::modSpecials(const APFloat &rhs)
1501{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001502 switch (convolve(category, rhs.category)) {
Dale Johannesened6af242009-01-21 00:35:19 +00001503 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001504 llvm_unreachable(0);
Dale Johannesened6af242009-01-21 00:35:19 +00001505
1506 case convolve(fcNaN, fcZero):
1507 case convolve(fcNaN, fcNormal):
1508 case convolve(fcNaN, fcInfinity):
1509 case convolve(fcNaN, fcNaN):
1510 case convolve(fcZero, fcInfinity):
1511 case convolve(fcZero, fcNormal):
1512 case convolve(fcNormal, fcInfinity):
1513 return opOK;
1514
1515 case convolve(fcZero, fcNaN):
1516 case convolve(fcNormal, fcNaN):
1517 case convolve(fcInfinity, fcNaN):
1518 category = fcNaN;
1519 copySignificand(rhs);
1520 return opOK;
1521
1522 case convolve(fcNormal, fcZero):
1523 case convolve(fcInfinity, fcZero):
1524 case convolve(fcInfinity, fcNormal):
1525 case convolve(fcInfinity, fcInfinity):
1526 case convolve(fcZero, fcZero):
1527 makeNaN();
1528 return opInvalidOp;
1529
1530 case convolve(fcNormal, fcNormal):
1531 return opOK;
1532 }
1533}
1534
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001535/* Change sign. */
1536void
1537APFloat::changeSign()
1538{
1539 /* Look mummy, this one's easy. */
1540 sign = !sign;
1541}
1542
Dale Johannesene15c2db2007-08-31 23:35:31 +00001543void
1544APFloat::clearSign()
1545{
1546 /* So is this one. */
1547 sign = 0;
1548}
1549
1550void
1551APFloat::copySign(const APFloat &rhs)
1552{
1553 /* And this one. */
1554 sign = rhs.sign;
1555}
1556
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001557/* Normalized addition or subtraction. */
1558APFloat::opStatus
1559APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001560 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001561{
1562 opStatus fs;
1563
Neil Boothcaf19d72007-10-14 10:29:28 +00001564 assertArithmeticOK(*semantics);
1565
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001566 fs = addOrSubtractSpecials(rhs, subtract);
1567
1568 /* This return code means it was not a simple case. */
Dan Gohman16e02092010-03-24 19:38:02 +00001569 if (fs == opDivByZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001570 lostFraction lost_fraction;
1571
1572 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1573 fs = normalize(rounding_mode, lost_fraction);
1574
1575 /* Can only be zero if we lost no fraction. */
1576 assert(category != fcZero || lost_fraction == lfExactlyZero);
1577 }
1578
1579 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1580 positive zero unless rounding to minus infinity, except that
1581 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001582 if (category == fcZero) {
1583 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001584 sign = (rounding_mode == rmTowardNegative);
1585 }
1586
1587 return fs;
1588}
1589
1590/* Normalized addition. */
1591APFloat::opStatus
1592APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1593{
1594 return addOrSubtract(rhs, rounding_mode, false);
1595}
1596
1597/* Normalized subtraction. */
1598APFloat::opStatus
1599APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1600{
1601 return addOrSubtract(rhs, rounding_mode, true);
1602}
1603
1604/* Normalized multiply. */
1605APFloat::opStatus
1606APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1607{
1608 opStatus fs;
1609
Neil Boothcaf19d72007-10-14 10:29:28 +00001610 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001611 sign ^= rhs.sign;
1612 fs = multiplySpecials(rhs);
1613
Dan Gohman16e02092010-03-24 19:38:02 +00001614 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001615 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1616 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001617 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001618 fs = (opStatus) (fs | opInexact);
1619 }
1620
1621 return fs;
1622}
1623
1624/* Normalized divide. */
1625APFloat::opStatus
1626APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1627{
1628 opStatus fs;
1629
Neil Boothcaf19d72007-10-14 10:29:28 +00001630 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001631 sign ^= rhs.sign;
1632 fs = divideSpecials(rhs);
1633
Dan Gohman16e02092010-03-24 19:38:02 +00001634 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001635 lostFraction lost_fraction = divideSignificand(rhs);
1636 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001637 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001638 fs = (opStatus) (fs | opInexact);
1639 }
1640
1641 return fs;
1642}
1643
Dale Johannesen24b66a82009-01-20 18:35:05 +00001644/* Normalized remainder. This is not currently correct in all cases. */
1645APFloat::opStatus
1646APFloat::remainder(const APFloat &rhs)
1647{
1648 opStatus fs;
1649 APFloat V = *this;
1650 unsigned int origSign = sign;
1651
1652 assertArithmeticOK(*semantics);
1653 fs = V.divide(rhs, rmNearestTiesToEven);
1654 if (fs == opDivByZero)
1655 return fs;
1656
1657 int parts = partCount();
1658 integerPart *x = new integerPart[parts];
1659 bool ignored;
1660 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1661 rmNearestTiesToEven, &ignored);
1662 if (fs==opInvalidOp)
1663 return fs;
1664
1665 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1666 rmNearestTiesToEven);
1667 assert(fs==opOK); // should always work
1668
1669 fs = V.multiply(rhs, rmNearestTiesToEven);
1670 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1671
1672 fs = subtract(V, rmNearestTiesToEven);
1673 assert(fs==opOK || fs==opInexact); // likewise
1674
1675 if (isZero())
1676 sign = origSign; // IEEE754 requires this
1677 delete[] x;
1678 return fs;
1679}
1680
Dan Gohman16e02092010-03-24 19:38:02 +00001681/* Normalized llvm frem (C fmod).
Dale Johannesen24b66a82009-01-20 18:35:05 +00001682 This is not currently correct in all cases. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001683APFloat::opStatus
1684APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1685{
1686 opStatus fs;
Neil Boothcaf19d72007-10-14 10:29:28 +00001687 assertArithmeticOK(*semantics);
Dale Johannesened6af242009-01-21 00:35:19 +00001688 fs = modSpecials(rhs);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001689
Dale Johannesened6af242009-01-21 00:35:19 +00001690 if (category == fcNormal && rhs.category == fcNormal) {
1691 APFloat V = *this;
1692 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001693
Dale Johannesened6af242009-01-21 00:35:19 +00001694 fs = V.divide(rhs, rmNearestTiesToEven);
1695 if (fs == opDivByZero)
1696 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001697
Dale Johannesened6af242009-01-21 00:35:19 +00001698 int parts = partCount();
1699 integerPart *x = new integerPart[parts];
1700 bool ignored;
1701 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1702 rmTowardZero, &ignored);
1703 if (fs==opInvalidOp)
1704 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001705
Dale Johannesened6af242009-01-21 00:35:19 +00001706 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1707 rmNearestTiesToEven);
1708 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001709
Dale Johannesened6af242009-01-21 00:35:19 +00001710 fs = V.multiply(rhs, rounding_mode);
1711 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1712
1713 fs = subtract(V, rounding_mode);
1714 assert(fs==opOK || fs==opInexact); // likewise
1715
1716 if (isZero())
1717 sign = origSign; // IEEE754 requires this
1718 delete[] x;
1719 }
Dale Johannesene15c2db2007-08-31 23:35:31 +00001720 return fs;
1721}
1722
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001723/* Normalized fused-multiply-add. */
1724APFloat::opStatus
1725APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001726 const APFloat &addend,
1727 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001728{
1729 opStatus fs;
1730
Neil Boothcaf19d72007-10-14 10:29:28 +00001731 assertArithmeticOK(*semantics);
1732
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001733 /* Post-multiplication sign, before addition. */
1734 sign ^= multiplicand.sign;
1735
1736 /* If and only if all arguments are normal do we need to do an
1737 extended-precision calculation. */
Dan Gohman16e02092010-03-24 19:38:02 +00001738 if (category == fcNormal &&
1739 multiplicand.category == fcNormal &&
1740 addend.category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001741 lostFraction lost_fraction;
1742
1743 lost_fraction = multiplySignificand(multiplicand, &addend);
1744 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001745 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001746 fs = (opStatus) (fs | opInexact);
1747
1748 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1749 positive zero unless rounding to minus infinity, except that
1750 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001751 if (category == fcZero && sign != addend.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001752 sign = (rounding_mode == rmTowardNegative);
1753 } else {
1754 fs = multiplySpecials(multiplicand);
1755
1756 /* FS can only be opOK or opInvalidOp. There is no more work
1757 to do in the latter case. The IEEE-754R standard says it is
1758 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001759 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001760
1761 If we need to do the addition we can do so with normal
1762 precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001763 if (fs == opOK)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001764 fs = addOrSubtract(addend, rounding_mode, false);
1765 }
1766
1767 return fs;
1768}
1769
Owen Anderson7c626d32012-08-13 23:32:49 +00001770/* Rounding-mode corrrect round to integral value. */
1771APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
1772 opStatus fs;
1773 assertArithmeticOK(*semantics);
1774
Owen Andersonc82cc582012-08-15 18:28:45 +00001775 // If the exponent is large enough, we know that this value is already
1776 // integral, and the arithmetic below would potentially cause it to saturate
1777 // to +/-Inf. Bail out early instead.
Benjamin Kramer3e7735f2012-09-26 14:06:58 +00001778 if (category == fcNormal && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Andersonc82cc582012-08-15 18:28:45 +00001779 return opOK;
1780
Owen Anderson7c626d32012-08-13 23:32:49 +00001781 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1782 // precision of our format, and then subtract it back off again. The choice
1783 // of rounding modes for the addition/subtraction determines the rounding mode
1784 // for our integral rounding as well.
Owen Anderson7c289782012-08-15 16:42:53 +00001785 // NOTE: When the input value is negative, we do subtraction followed by
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001786 // addition instead.
Owen Andersond7a85b12012-08-14 18:51:15 +00001787 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1788 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Owen Anderson7c626d32012-08-13 23:32:49 +00001789 APFloat MagicConstant(*semantics);
1790 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1791 rmNearestTiesToEven);
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001792 MagicConstant.copySign(*this);
1793
Owen Anderson7c626d32012-08-13 23:32:49 +00001794 if (fs != opOK)
1795 return fs;
1796
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001797 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1798 bool inputSign = isNegative();
1799
Owen Anderson7c626d32012-08-13 23:32:49 +00001800 fs = add(MagicConstant, rounding_mode);
1801 if (fs != opOK && fs != opInexact)
1802 return fs;
1803
1804 fs = subtract(MagicConstant, rounding_mode);
Owen Andersonf7a5dfc2012-08-15 05:39:46 +00001805
1806 // Restore the input sign.
1807 if (inputSign != isNegative())
1808 changeSign();
1809
Owen Anderson7c626d32012-08-13 23:32:49 +00001810 return fs;
1811}
1812
1813
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001814/* Comparison requires normalized numbers. */
1815APFloat::cmpResult
1816APFloat::compare(const APFloat &rhs) const
1817{
1818 cmpResult result;
1819
Neil Boothcaf19d72007-10-14 10:29:28 +00001820 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001821 assert(semantics == rhs.semantics);
1822
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001823 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001824 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001825 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001826
Dale Johanneseneaf08942007-08-31 04:03:46 +00001827 case convolve(fcNaN, fcZero):
1828 case convolve(fcNaN, fcNormal):
1829 case convolve(fcNaN, fcInfinity):
1830 case convolve(fcNaN, fcNaN):
1831 case convolve(fcZero, fcNaN):
1832 case convolve(fcNormal, fcNaN):
1833 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001834 return cmpUnordered;
1835
1836 case convolve(fcInfinity, fcNormal):
1837 case convolve(fcInfinity, fcZero):
1838 case convolve(fcNormal, fcZero):
Dan Gohman16e02092010-03-24 19:38:02 +00001839 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001840 return cmpLessThan;
1841 else
1842 return cmpGreaterThan;
1843
1844 case convolve(fcNormal, fcInfinity):
1845 case convolve(fcZero, fcInfinity):
1846 case convolve(fcZero, fcNormal):
Dan Gohman16e02092010-03-24 19:38:02 +00001847 if (rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001848 return cmpGreaterThan;
1849 else
1850 return cmpLessThan;
1851
1852 case convolve(fcInfinity, fcInfinity):
Dan Gohman16e02092010-03-24 19:38:02 +00001853 if (sign == rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001854 return cmpEqual;
Dan Gohman16e02092010-03-24 19:38:02 +00001855 else if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001856 return cmpLessThan;
1857 else
1858 return cmpGreaterThan;
1859
1860 case convolve(fcZero, fcZero):
1861 return cmpEqual;
1862
1863 case convolve(fcNormal, fcNormal):
1864 break;
1865 }
1866
1867 /* Two normal numbers. Do they have the same sign? */
Dan Gohman16e02092010-03-24 19:38:02 +00001868 if (sign != rhs.sign) {
1869 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001870 result = cmpLessThan;
1871 else
1872 result = cmpGreaterThan;
1873 } else {
1874 /* Compare absolute values; invert result if negative. */
1875 result = compareAbsoluteValue(rhs);
1876
Dan Gohman16e02092010-03-24 19:38:02 +00001877 if (sign) {
1878 if (result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001879 result = cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001880 else if (result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001881 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001882 }
1883 }
1884
1885 return result;
1886}
1887
Dale Johannesen23a98552008-10-09 23:00:39 +00001888/// APFloat::convert - convert a value of one floating point type to another.
1889/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1890/// records whether the transformation lost information, i.e. whether
1891/// converting the result back to the original type will produce the
1892/// original value (this is almost the same as return value==fsOK, but there
1893/// are edge cases where this is not so).
1894
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001895APFloat::opStatus
1896APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001897 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001898{
Neil Boothc8db43d2007-09-22 02:56:19 +00001899 lostFraction lostFraction;
1900 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001901 opStatus fs;
Eli Friedman44551422011-11-26 03:38:02 +00001902 int shift;
1903 const fltSemantics &fromSemantics = *semantics;
Neil Booth4f881702007-09-26 21:33:42 +00001904
Eli Friedman44551422011-11-26 03:38:02 +00001905 assertArithmeticOK(fromSemantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001906 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001907 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001908 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001909 oldPartCount = partCount();
Eli Friedman44551422011-11-26 03:38:02 +00001910 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001911
Eli Friedman44551422011-11-26 03:38:02 +00001912 bool X86SpecialNan = false;
1913 if (&fromSemantics == &APFloat::x87DoubleExtended &&
1914 &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
1915 (!(*significandParts() & 0x8000000000000000ULL) ||
1916 !(*significandParts() & 0x4000000000000000ULL))) {
1917 // x86 has some unusual NaNs which cannot be represented in any other
1918 // format; note them here.
1919 X86SpecialNan = true;
1920 }
1921
1922 // If this is a truncation, perform the shift before we narrow the storage.
1923 if (shift < 0 && (category==fcNormal || category==fcNaN))
1924 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1925
1926 // Fix the storage so it can hold to new value.
Neil Boothc8db43d2007-09-22 02:56:19 +00001927 if (newPartCount > oldPartCount) {
Eli Friedman44551422011-11-26 03:38:02 +00001928 // The new type requires more storage; make it available.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001929 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001930 newParts = new integerPart[newPartCount];
1931 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001932 if (category==fcNormal || category==fcNaN)
1933 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001934 freeSignificand();
1935 significand.parts = newParts;
Eli Friedman44551422011-11-26 03:38:02 +00001936 } else if (newPartCount == 1 && oldPartCount != 1) {
1937 // Switch to built-in storage for a single part.
1938 integerPart newPart = 0;
1939 if (category==fcNormal || category==fcNaN)
1940 newPart = significandParts()[0];
1941 freeSignificand();
1942 significand.part = newPart;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001943 }
1944
Eli Friedman44551422011-11-26 03:38:02 +00001945 // Now that we have the right storage, switch the semantics.
1946 semantics = &toSemantics;
1947
1948 // If this is an extension, perform the shift now that the storage is
1949 // available.
1950 if (shift > 0 && (category==fcNormal || category==fcNaN))
1951 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1952
Dan Gohman16e02092010-03-24 19:38:02 +00001953 if (category == fcNormal) {
Neil Boothc8db43d2007-09-22 02:56:19 +00001954 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001955 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001956 } else if (category == fcNaN) {
Eli Friedman44551422011-11-26 03:38:02 +00001957 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Dale Johannesen902ff942007-09-25 17:25:00 +00001958 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1959 // does not give you back the same bits. This is dubious, and we
1960 // don't currently do it. You're really supposed to get
1961 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001962 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001963 } else {
Dale Johannesen23a98552008-10-09 23:00:39 +00001964 *losesInfo = false;
Eli Friedmanf9b1cd02011-11-28 18:50:37 +00001965 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001966 }
1967
1968 return fs;
1969}
1970
1971/* Convert a floating point number to an integer according to the
1972 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001973 returns an invalid operation exception and the contents of the
1974 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001975 range but the floating point number is not the exact integer, the C
1976 standard doesn't require an inexact exception to be raised. IEEE
1977 854 does require it so we do that.
1978
1979 Note that for conversions to integer type the C standard requires
1980 round-to-zero to always be used. */
1981APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001982APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1983 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001984 roundingMode rounding_mode,
1985 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001986{
1987 lostFraction lost_fraction;
1988 const integerPart *src;
1989 unsigned int dstPartsCount, truncatedBits;
1990
Evan Cheng794a7db2008-11-26 01:11:57 +00001991 assertArithmeticOK(*semantics);
Neil Boothe3d936a2007-11-02 15:10:05 +00001992
Dale Johannesen23a98552008-10-09 23:00:39 +00001993 *isExact = false;
1994
Neil Boothee7ae382007-11-01 22:43:37 +00001995 /* Handle the three special cases first. */
Dan Gohman16e02092010-03-24 19:38:02 +00001996 if (category == fcInfinity || category == fcNaN)
Neil Boothee7ae382007-11-01 22:43:37 +00001997 return opInvalidOp;
1998
1999 dstPartsCount = partCountForBits(width);
2000
Dan Gohman16e02092010-03-24 19:38:02 +00002001 if (category == fcZero) {
Neil Boothee7ae382007-11-01 22:43:37 +00002002 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00002003 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00002004 *isExact = !sign;
2005 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00002006 }
2007
2008 src = significandParts();
2009
2010 /* Step 1: place our absolute value, with any fraction truncated, in
2011 the destination. */
2012 if (exponent < 0) {
2013 /* Our absolute value is less than one; truncate everything. */
2014 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen1f54f582009-01-19 21:17:05 +00002015 /* For exponent -1 the integer bit represents .5, look at that.
2016 For smaller exponents leftmost truncated bit is 0. */
2017 truncatedBits = semantics->precision -1U - exponent;
Neil Boothee7ae382007-11-01 22:43:37 +00002018 } else {
2019 /* We want the most significant (exponent + 1) bits; the rest are
2020 truncated. */
2021 unsigned int bits = exponent + 1U;
2022
2023 /* Hopelessly large in magnitude? */
2024 if (bits > width)
2025 return opInvalidOp;
2026
2027 if (bits < semantics->precision) {
2028 /* We truncate (semantics->precision - bits) bits. */
2029 truncatedBits = semantics->precision - bits;
2030 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2031 } else {
2032 /* We want at least as many bits as are available. */
2033 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2034 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2035 truncatedBits = 0;
2036 }
2037 }
2038
2039 /* Step 2: work out any lost fraction, and increment the absolute
2040 value if we would round away from zero. */
2041 if (truncatedBits) {
2042 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2043 truncatedBits);
Dan Gohman16e02092010-03-24 19:38:02 +00002044 if (lost_fraction != lfExactlyZero &&
2045 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Boothee7ae382007-11-01 22:43:37 +00002046 if (APInt::tcIncrement(parts, dstPartsCount))
2047 return opInvalidOp; /* Overflow. */
2048 }
2049 } else {
2050 lost_fraction = lfExactlyZero;
2051 }
2052
2053 /* Step 3: check if we fit in the destination. */
2054 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2055
2056 if (sign) {
2057 if (!isSigned) {
2058 /* Negative numbers cannot be represented as unsigned. */
2059 if (omsb != 0)
2060 return opInvalidOp;
2061 } else {
2062 /* It takes omsb bits to represent the unsigned integer value.
2063 We lose a bit for the sign, but care is needed as the
2064 maximally negative integer is a special case. */
2065 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2066 return opInvalidOp;
2067
2068 /* This case can happen because of rounding. */
2069 if (omsb > width)
2070 return opInvalidOp;
2071 }
2072
2073 APInt::tcNegate (parts, dstPartsCount);
2074 } else {
2075 if (omsb >= width + !isSigned)
2076 return opInvalidOp;
2077 }
2078
Dale Johannesen23a98552008-10-09 23:00:39 +00002079 if (lost_fraction == lfExactlyZero) {
2080 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00002081 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00002082 } else
Neil Boothee7ae382007-11-01 22:43:37 +00002083 return opInexact;
2084}
2085
2086/* Same as convertToSignExtendedInteger, except we provide
2087 deterministic values in case of an invalid operation exception,
2088 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00002089 for underflow or overflow.
2090 The *isExact output tells whether the result is exact, in the sense
2091 that converting it back to the original floating point type produces
2092 the original value. This is almost equivalent to result==opOK,
2093 except for negative zeroes.
2094*/
Neil Boothee7ae382007-11-01 22:43:37 +00002095APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002096APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00002097 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00002098 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002099{
Neil Boothee7ae382007-11-01 22:43:37 +00002100 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002101
Dan Gohman16e02092010-03-24 19:38:02 +00002102 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen23a98552008-10-09 23:00:39 +00002103 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002104
Neil Boothee7ae382007-11-01 22:43:37 +00002105 if (fs == opInvalidOp) {
2106 unsigned int bits, dstPartsCount;
2107
2108 dstPartsCount = partCountForBits(width);
2109
2110 if (category == fcNaN)
2111 bits = 0;
2112 else if (sign)
2113 bits = isSigned;
2114 else
2115 bits = width - isSigned;
2116
2117 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2118 if (sign && isSigned)
2119 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002120 }
2121
Neil Boothee7ae382007-11-01 22:43:37 +00002122 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002123}
2124
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +00002125/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2126 an APSInt, whose initial bit-width and signed-ness are used to determine the
2127 precision of the conversion.
2128 */
2129APFloat::opStatus
2130APFloat::convertToInteger(APSInt &result,
2131 roundingMode rounding_mode, bool *isExact) const
2132{
2133 unsigned bitWidth = result.getBitWidth();
2134 SmallVector<uint64_t, 4> parts(result.getNumWords());
2135 opStatus status = convertToInteger(
2136 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2137 // Keeps the original signed-ness.
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002138 result = APInt(bitWidth, parts);
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +00002139 return status;
2140}
2141
Neil Booth643ce592007-10-07 12:07:53 +00002142/* Convert an unsigned integer SRC to a floating point number,
2143 rounding according to ROUNDING_MODE. The sign of the floating
2144 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002145APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00002146APFloat::convertFromUnsignedParts(const integerPart *src,
2147 unsigned int srcCount,
2148 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002149{
Neil Booth5477f852007-10-08 14:39:42 +00002150 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00002151 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00002152 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002153
Neil Boothcaf19d72007-10-14 10:29:28 +00002154 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002155 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00002156 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00002157 dst = significandParts();
2158 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00002159 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00002160
Nick Lewycky03dd4e82011-10-03 21:30:08 +00002161 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth5477f852007-10-08 14:39:42 +00002162 be that many; extract what we can. */
2163 if (precision <= omsb) {
2164 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00002165 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00002166 omsb - precision);
2167 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2168 } else {
2169 exponent = precision - 1;
2170 lost_fraction = lfExactlyZero;
2171 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00002172 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002173
2174 return normalize(rounding_mode, lost_fraction);
2175}
2176
Dan Gohman93c276e2008-02-29 01:26:11 +00002177APFloat::opStatus
2178APFloat::convertFromAPInt(const APInt &Val,
2179 bool isSigned,
2180 roundingMode rounding_mode)
2181{
2182 unsigned int partCount = Val.getNumWords();
2183 APInt api = Val;
2184
2185 sign = false;
2186 if (isSigned && api.isNegative()) {
2187 sign = true;
2188 api = -api;
2189 }
2190
2191 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2192}
2193
Neil Boothf16c5952007-10-07 12:15:41 +00002194/* Convert a two's complement integer SRC to a floating point number,
2195 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2196 integer is signed, in which case it must be sign-extended. */
2197APFloat::opStatus
2198APFloat::convertFromSignExtendedInteger(const integerPart *src,
2199 unsigned int srcCount,
2200 bool isSigned,
2201 roundingMode rounding_mode)
2202{
2203 opStatus status;
2204
Neil Boothcaf19d72007-10-14 10:29:28 +00002205 assertArithmeticOK(*semantics);
Dan Gohman16e02092010-03-24 19:38:02 +00002206 if (isSigned &&
2207 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Neil Boothf16c5952007-10-07 12:15:41 +00002208 integerPart *copy;
2209
2210 /* If we're signed and negative negate a copy. */
2211 sign = true;
2212 copy = new integerPart[srcCount];
2213 APInt::tcAssign(copy, src, srcCount);
2214 APInt::tcNegate(copy, srcCount);
2215 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2216 delete [] copy;
2217 } else {
2218 sign = false;
2219 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2220 }
2221
2222 return status;
2223}
2224
Neil Boothccf596a2007-10-07 11:45:55 +00002225/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002226APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002227APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2228 unsigned int width, bool isSigned,
2229 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002230{
Dale Johannesen910993e2007-09-21 22:09:37 +00002231 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002232 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002233
2234 sign = false;
Dan Gohman16e02092010-03-24 19:38:02 +00002235 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesencce23a42007-09-30 18:17:01 +00002236 sign = true;
2237 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002238 }
2239
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002240 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002241}
2242
2243APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002244APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002245{
Erick Tryzelaarf8bc8012009-08-18 18:20:37 +00002246 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002247 integerPart *significand;
2248 unsigned int bitPos, partsCount;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002249 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002250
2251 zeroSignificand();
2252 exponent = 0;
2253 category = fcNormal;
2254
2255 significand = significandParts();
2256 partsCount = partCount();
2257 bitPos = partsCount * integerPartWidth;
2258
Neil Booth33d4c922007-10-07 08:51:21 +00002259 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002260 StringRef::iterator begin = s.begin();
2261 StringRef::iterator end = s.end();
2262 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002263 firstSignificantDigit = p;
2264
Dan Gohman16e02092010-03-24 19:38:02 +00002265 for (; p != end;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002266 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002267
Dan Gohman16e02092010-03-24 19:38:02 +00002268 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002269 assert(dot == end && "String contains multiple dots");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002270 dot = p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002271 if (p == end) {
2272 break;
2273 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002274 }
2275
2276 hex_value = hexDigitValue(*p);
Dan Gohman16e02092010-03-24 19:38:02 +00002277 if (hex_value == -1U) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002278 break;
2279 }
2280
2281 p++;
2282
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002283 if (p == end) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002284 break;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002285 } else {
2286 /* Store the number whilst 4-bit nibbles remain. */
Dan Gohman16e02092010-03-24 19:38:02 +00002287 if (bitPos) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002288 bitPos -= 4;
2289 hex_value <<= bitPos % integerPartWidth;
2290 significand[bitPos / integerPartWidth] |= hex_value;
2291 } else {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002292 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
Dan Gohman16e02092010-03-24 19:38:02 +00002293 while (p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002294 p++;
2295 break;
2296 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002297 }
2298 }
2299
2300 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002301 assert(p != end && "Hex strings require an exponent");
2302 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2303 assert(p != begin && "Significand has no digits");
2304 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002305
2306 /* Ignore the exponent if we are zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00002307 if (p != firstSignificantDigit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002308 int expAdjustment;
2309
2310 /* Implicit hexadecimal point? */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002311 if (dot == end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002312 dot = p;
2313
2314 /* Calculate the exponent adjustment implicit in the number of
2315 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002316 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohman16e02092010-03-24 19:38:02 +00002317 if (expAdjustment < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002318 expAdjustment++;
2319 expAdjustment = expAdjustment * 4 - 1;
2320
2321 /* Adjust for writing the significand starting at the most
2322 significant nibble. */
2323 expAdjustment += semantics->precision;
2324 expAdjustment -= partsCount * integerPartWidth;
2325
2326 /* Adjust for the given exponent. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002327 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002328 }
2329
2330 return normalize(rounding_mode, lost_fraction);
2331}
2332
2333APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002334APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2335 unsigned sigPartCount, int exp,
2336 roundingMode rounding_mode)
2337{
2338 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002339 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002340 integerPart pow5Parts[maxPowerOfFiveParts];
2341 bool isNearest;
2342
Dan Gohman16e02092010-03-24 19:38:02 +00002343 isNearest = (rounding_mode == rmNearestTiesToEven ||
2344 rounding_mode == rmNearestTiesToAway);
Neil Booth96c74712007-10-12 16:02:31 +00002345
2346 parts = partCountForBits(semantics->precision + 11);
2347
2348 /* Calculate pow(5, abs(exp)). */
2349 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2350
2351 for (;; parts *= 2) {
2352 opStatus sigStatus, powStatus;
2353 unsigned int excessPrecision, truncatedBits;
2354
2355 calcSemantics.precision = parts * integerPartWidth - 1;
2356 excessPrecision = calcSemantics.precision - semantics->precision;
2357 truncatedBits = excessPrecision;
2358
2359 APFloat decSig(calcSemantics, fcZero, sign);
2360 APFloat pow5(calcSemantics, fcZero, false);
2361
2362 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2363 rmNearestTiesToEven);
2364 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2365 rmNearestTiesToEven);
2366 /* Add exp, as 10^n = 5^n * 2^n. */
2367 decSig.exponent += exp;
2368
2369 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002370 integerPart HUerr, HUdistance;
2371 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002372
2373 if (exp >= 0) {
2374 /* multiplySignificand leaves the precision-th bit set to 1. */
2375 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2376 powHUerr = powStatus != opOK;
2377 } else {
2378 calcLostFraction = decSig.divideSignificand(pow5);
2379 /* Denormal numbers have less precision. */
2380 if (decSig.exponent < semantics->minExponent) {
2381 excessPrecision += (semantics->minExponent - decSig.exponent);
2382 truncatedBits = excessPrecision;
2383 if (excessPrecision > calcSemantics.precision)
2384 excessPrecision = calcSemantics.precision;
2385 }
2386 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002387 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002388 }
2389
2390 /* Both multiplySignificand and divideSignificand return the
2391 result with the integer bit set. */
Evan Cheng99ebfa52009-10-27 21:35:42 +00002392 assert(APInt::tcExtractBit
2393 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Booth96c74712007-10-12 16:02:31 +00002394
2395 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2396 powHUerr);
2397 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2398 excessPrecision, isNearest);
2399
2400 /* Are we guaranteed to round correctly if we truncate? */
2401 if (HUdistance >= HUerr) {
2402 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2403 calcSemantics.precision - excessPrecision,
2404 excessPrecision);
2405 /* Take the exponent of decSig. If we tcExtract-ed less bits
2406 above we must adjust our exponent to compensate for the
2407 implicit right shift. */
2408 exponent = (decSig.exponent + semantics->precision
2409 - (calcSemantics.precision - excessPrecision));
2410 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2411 decSig.partCount(),
2412 truncatedBits);
2413 return normalize(rounding_mode, calcLostFraction);
2414 }
2415 }
2416}
2417
2418APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002419APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Booth96c74712007-10-12 16:02:31 +00002420{
Neil Booth1870f292007-10-14 10:16:12 +00002421 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002422 opStatus fs;
2423
Neil Booth1870f292007-10-14 10:16:12 +00002424 /* Scan the text. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002425 StringRef::iterator p = str.begin();
2426 interpretDecimal(p, str.end(), &D);
Neil Booth96c74712007-10-12 16:02:31 +00002427
Neil Booth686700e2007-10-15 15:00:55 +00002428 /* Handle the quick cases. First the case of no significant digits,
2429 i.e. zero, and then exponents that are obviously too large or too
2430 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2431 definitely overflows if
2432
2433 (exp - 1) * L >= maxExponent
2434
2435 and definitely underflows to zero where
2436
2437 (exp + 1) * L <= minExponent - precision
2438
2439 With integer arithmetic the tightest bounds for L are
2440
2441 93/28 < L < 196/59 [ numerator <= 256 ]
2442 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2443 */
2444
Neil Boothcc233592007-12-05 13:06:04 +00002445 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002446 category = fcZero;
2447 fs = opOK;
John McCall8b3f3302010-02-26 22:20:41 +00002448
2449 /* Check whether the normalized exponent is high enough to overflow
2450 max during the log-rebasing in the max-exponent check below. */
2451 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2452 fs = handleOverflow(rounding_mode);
2453
2454 /* If it wasn't, then it also wasn't high enough to overflow max
2455 during the log-rebasing in the min-exponent check. Check that it
2456 won't overflow min in either check, then perform the min-exponent
2457 check. */
2458 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2459 (D.normalizedExponent + 1) * 28738 <=
2460 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth686700e2007-10-15 15:00:55 +00002461 /* Underflow to zero and round. */
2462 zeroSignificand();
2463 fs = normalize(rounding_mode, lfLessThanHalf);
John McCall8b3f3302010-02-26 22:20:41 +00002464
2465 /* We can finally safely perform the max-exponent check. */
Neil Booth686700e2007-10-15 15:00:55 +00002466 } else if ((D.normalizedExponent - 1) * 42039
2467 >= 12655 * semantics->maxExponent) {
2468 /* Overflow and round. */
2469 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002470 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002471 integerPart *decSignificand;
2472 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002473
Neil Booth1870f292007-10-14 10:16:12 +00002474 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002475 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002476 to hold the full significand, and an extra part required by
2477 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002478 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002479 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002480 decSignificand = new integerPart[partCount + 1];
2481 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002482
Neil Booth1870f292007-10-14 10:16:12 +00002483 /* Convert to binary efficiently - we do almost all multiplication
2484 in an integerPart. When this would overflow do we do a single
2485 bignum multiplication, and then revert again to multiplication
2486 in an integerPart. */
2487 do {
2488 integerPart decValue, val, multiplier;
2489
2490 val = 0;
2491 multiplier = 1;
2492
2493 do {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002494 if (*p == '.') {
Neil Booth1870f292007-10-14 10:16:12 +00002495 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002496 if (p == str.end()) {
2497 break;
2498 }
2499 }
Neil Booth1870f292007-10-14 10:16:12 +00002500 decValue = decDigitValue(*p++);
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002501 assert(decValue < 10U && "Invalid character in significand");
Neil Booth1870f292007-10-14 10:16:12 +00002502 multiplier *= 10;
2503 val = val * 10 + decValue;
2504 /* The maximum number that can be multiplied by ten with any
2505 digit added without overflowing an integerPart. */
2506 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2507
2508 /* Multiply out the current part. */
2509 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2510 partCount, partCount + 1, false);
2511
2512 /* If we used another part (likely but not guaranteed), increase
2513 the count. */
2514 if (decSignificand[partCount])
2515 partCount++;
2516 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002517
Neil Booth43a4b282007-11-01 22:51:07 +00002518 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002519 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002520 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002521
Neil Booth1870f292007-10-14 10:16:12 +00002522 delete [] decSignificand;
2523 }
Neil Booth96c74712007-10-12 16:02:31 +00002524
2525 return fs;
2526}
2527
2528APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002529APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth4f881702007-09-26 21:33:42 +00002530{
Neil Boothcaf19d72007-10-14 10:29:28 +00002531 assertArithmeticOK(*semantics);
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002532 assert(!str.empty() && "Invalid string length");
Neil Boothcaf19d72007-10-14 10:29:28 +00002533
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002534 /* Handle a leading minus sign. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002535 StringRef::iterator p = str.begin();
2536 size_t slen = str.size();
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002537 sign = *p == '-' ? 1 : 0;
Dan Gohman16e02092010-03-24 19:38:02 +00002538 if (*p == '-' || *p == '+') {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002539 p++;
2540 slen--;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002541 assert(slen && "String has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002542 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002543
Dan Gohman16e02092010-03-24 19:38:02 +00002544 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002545 assert(slen - 2 && "Invalid string");
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002546 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002547 rounding_mode);
2548 }
Bill Wendlingb7c0d942008-11-27 08:00:12 +00002549
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002550 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002551}
Dale Johannesen343e7702007-08-24 00:56:33 +00002552
Neil Bootha30b0ee2007-10-03 22:26:02 +00002553/* Write out a hexadecimal representation of the floating point value
2554 to DST, which must be of sufficient size, in the C99 form
2555 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2556 excluding the terminating NUL.
2557
2558 If UPPERCASE, the output is in upper case, otherwise in lower case.
2559
2560 HEXDIGITS digits appear altogether, rounding the value if
2561 necessary. If HEXDIGITS is 0, the minimal precision to display the
2562 number precisely is used instead. If nothing would appear after
2563 the decimal point it is suppressed.
2564
2565 The decimal exponent is always printed and has at least one digit.
2566 Zero values display an exponent of zero. Infinities and NaNs
2567 appear as "infinity" or "nan" respectively.
2568
2569 The above rules are as specified by C99. There is ambiguity about
2570 what the leading hexadecimal digit should be. This implementation
2571 uses whatever is necessary so that the exponent is displayed as
2572 stored. This implies the exponent will fall within the IEEE format
2573 range, and the leading hexadecimal digit will be 0 (for denormals),
2574 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2575 any other digits zero).
2576*/
2577unsigned int
2578APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2579 bool upperCase, roundingMode rounding_mode) const
2580{
2581 char *p;
2582
Neil Boothcaf19d72007-10-14 10:29:28 +00002583 assertArithmeticOK(*semantics);
2584
Neil Bootha30b0ee2007-10-03 22:26:02 +00002585 p = dst;
2586 if (sign)
2587 *dst++ = '-';
2588
2589 switch (category) {
2590 case fcInfinity:
2591 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2592 dst += sizeof infinityL - 1;
2593 break;
2594
2595 case fcNaN:
2596 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2597 dst += sizeof NaNU - 1;
2598 break;
2599
2600 case fcZero:
2601 *dst++ = '0';
2602 *dst++ = upperCase ? 'X': 'x';
2603 *dst++ = '0';
2604 if (hexDigits > 1) {
2605 *dst++ = '.';
2606 memset (dst, '0', hexDigits - 1);
2607 dst += hexDigits - 1;
2608 }
2609 *dst++ = upperCase ? 'P': 'p';
2610 *dst++ = '0';
2611 break;
2612
2613 case fcNormal:
2614 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2615 break;
2616 }
2617
2618 *dst = 0;
2619
Evan Cheng48e8c802008-05-02 21:15:08 +00002620 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002621}
2622
2623/* Does the hard work of outputting the correctly rounded hexadecimal
2624 form of a normal floating point number with the specified number of
2625 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2626 digits necessary to print the value precisely is output. */
2627char *
2628APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2629 bool upperCase,
2630 roundingMode rounding_mode) const
2631{
2632 unsigned int count, valueBits, shift, partsCount, outputDigits;
2633 const char *hexDigitChars;
2634 const integerPart *significand;
2635 char *p;
2636 bool roundUp;
2637
2638 *dst++ = '0';
2639 *dst++ = upperCase ? 'X': 'x';
2640
2641 roundUp = false;
2642 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2643
2644 significand = significandParts();
2645 partsCount = partCount();
2646
2647 /* +3 because the first digit only uses the single integer bit, so
2648 we have 3 virtual zero most-significant-bits. */
2649 valueBits = semantics->precision + 3;
2650 shift = integerPartWidth - valueBits % integerPartWidth;
2651
2652 /* The natural number of digits required ignoring trailing
2653 insignificant zeroes. */
2654 outputDigits = (valueBits - significandLSB () + 3) / 4;
2655
2656 /* hexDigits of zero means use the required number for the
2657 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002658 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002659 if (hexDigits) {
2660 if (hexDigits < outputDigits) {
2661 /* We are dropping non-zero bits, so need to check how to round.
2662 "bits" is the number of dropped bits. */
2663 unsigned int bits;
2664 lostFraction fraction;
2665
2666 bits = valueBits - hexDigits * 4;
2667 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2668 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2669 }
2670 outputDigits = hexDigits;
2671 }
2672
2673 /* Write the digits consecutively, and start writing in the location
2674 of the hexadecimal point. We move the most significant digit
2675 left and add the hexadecimal point later. */
2676 p = ++dst;
2677
2678 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2679
2680 while (outputDigits && count) {
2681 integerPart part;
2682
2683 /* Put the most significant integerPartWidth bits in "part". */
2684 if (--count == partsCount)
2685 part = 0; /* An imaginary higher zero part. */
2686 else
2687 part = significand[count] << shift;
2688
2689 if (count && shift)
2690 part |= significand[count - 1] >> (integerPartWidth - shift);
2691
2692 /* Convert as much of "part" to hexdigits as we can. */
2693 unsigned int curDigits = integerPartWidth / 4;
2694
2695 if (curDigits > outputDigits)
2696 curDigits = outputDigits;
2697 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2698 outputDigits -= curDigits;
2699 }
2700
2701 if (roundUp) {
2702 char *q = dst;
2703
2704 /* Note that hexDigitChars has a trailing '0'. */
2705 do {
2706 q--;
2707 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002708 } while (*q == '0');
Evan Cheng99ebfa52009-10-27 21:35:42 +00002709 assert(q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002710 } else {
2711 /* Add trailing zeroes. */
2712 memset (dst, '0', outputDigits);
2713 dst += outputDigits;
2714 }
2715
2716 /* Move the most significant digit to before the point, and if there
2717 is something after the decimal point add it. This must come
2718 after rounding above. */
2719 p[-1] = p[0];
2720 if (dst -1 == p)
2721 dst--;
2722 else
2723 p[0] = '.';
2724
2725 /* Finally output the exponent. */
2726 *dst++ = upperCase ? 'P': 'p';
2727
Neil Booth92f7e8d2007-10-06 07:29:25 +00002728 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002729}
2730
Chandler Carruthed7692a2012-03-04 12:02:57 +00002731hash_code llvm::hash_value(const APFloat &Arg) {
2732 if (Arg.category != APFloat::fcNormal)
2733 return hash_combine((uint8_t)Arg.category,
2734 // NaN has no sign, fix it at zero.
2735 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2736 Arg.semantics->precision);
2737
2738 // Normal floats need their exponent and significand hashed.
2739 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2740 Arg.semantics->precision, Arg.exponent,
2741 hash_combine_range(
2742 Arg.significandParts(),
2743 Arg.significandParts() + Arg.partCount()));
Dale Johannesen343e7702007-08-24 00:56:33 +00002744}
2745
2746// Conversion from APFloat to/from host float/double. It may eventually be
2747// possible to eliminate these and have everybody deal with APFloats, but that
2748// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002749// Current implementation requires integerPartWidth==64, which is correct at
2750// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002751
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002752// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002753// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002754
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002755APInt
Neil Booth4f881702007-09-26 21:33:42 +00002756APFloat::convertF80LongDoubleAPFloatToAPInt() const
2757{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002758 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002759 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002760
2761 uint64_t myexponent, mysignificand;
2762
2763 if (category==fcNormal) {
2764 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002765 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002766 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2767 myexponent = 0; // denormal
2768 } else if (category==fcZero) {
2769 myexponent = 0;
2770 mysignificand = 0;
2771 } else if (category==fcInfinity) {
2772 myexponent = 0x7fff;
2773 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002774 } else {
2775 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002776 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002777 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002778 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002779
2780 uint64_t words[2];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002781 words[0] = mysignificand;
2782 words[1] = ((uint64_t)(sign & 1) << 15) |
2783 (myexponent & 0x7fffLL);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002784 return APInt(80, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002785}
2786
2787APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002788APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2789{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002790 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002791 assert(partCount()==2);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002792
2793 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2794
2795 if (category==fcNormal) {
2796 myexponent = exponent + 1023; //bias
2797 myexponent2 = exponent2 + 1023;
2798 mysignificand = significandParts()[0];
2799 mysignificand2 = significandParts()[1];
2800 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2801 myexponent = 0; // denormal
2802 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2803 myexponent2 = 0; // denormal
2804 } else if (category==fcZero) {
2805 myexponent = 0;
2806 mysignificand = 0;
2807 myexponent2 = 0;
2808 mysignificand2 = 0;
2809 } else if (category==fcInfinity) {
2810 myexponent = 0x7ff;
2811 myexponent2 = 0;
2812 mysignificand = 0;
2813 mysignificand2 = 0;
2814 } else {
2815 assert(category == fcNaN && "Unknown category");
2816 myexponent = 0x7ff;
2817 mysignificand = significandParts()[0];
2818 myexponent2 = exponent2;
2819 mysignificand2 = significandParts()[1];
2820 }
2821
2822 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002823 words[0] = ((uint64_t)(sign & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002824 ((myexponent & 0x7ff) << 52) |
2825 (mysignificand & 0xfffffffffffffLL);
Evan Cheng48e8c802008-05-02 21:15:08 +00002826 words[1] = ((uint64_t)(sign2 & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002827 ((myexponent2 & 0x7ff) << 52) |
2828 (mysignificand2 & 0xfffffffffffffLL);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002829 return APInt(128, words);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002830}
2831
2832APInt
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002833APFloat::convertQuadrupleAPFloatToAPInt() const
2834{
2835 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002836 assert(partCount()==2);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002837
2838 uint64_t myexponent, mysignificand, mysignificand2;
2839
2840 if (category==fcNormal) {
2841 myexponent = exponent+16383; //bias
2842 mysignificand = significandParts()[0];
2843 mysignificand2 = significandParts()[1];
2844 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2845 myexponent = 0; // denormal
2846 } else if (category==fcZero) {
2847 myexponent = 0;
2848 mysignificand = mysignificand2 = 0;
2849 } else if (category==fcInfinity) {
2850 myexponent = 0x7fff;
2851 mysignificand = mysignificand2 = 0;
2852 } else {
2853 assert(category == fcNaN && "Unknown category!");
2854 myexponent = 0x7fff;
2855 mysignificand = significandParts()[0];
2856 mysignificand2 = significandParts()[1];
2857 }
2858
2859 uint64_t words[2];
2860 words[0] = mysignificand;
2861 words[1] = ((uint64_t)(sign & 1) << 63) |
2862 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov4755e992009-08-21 23:09:47 +00002863 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002864
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002865 return APInt(128, words);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002866}
2867
2868APInt
Neil Booth4f881702007-09-26 21:33:42 +00002869APFloat::convertDoubleAPFloatToAPInt() const
2870{
Dan Gohmancb648f92007-09-14 20:08:19 +00002871 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002872 assert(partCount()==1);
Dale Johannesen343e7702007-08-24 00:56:33 +00002873
Dale Johanneseneaf08942007-08-31 04:03:46 +00002874 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002875
2876 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002877 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002878 mysignificand = *significandParts();
2879 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2880 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002881 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002882 myexponent = 0;
2883 mysignificand = 0;
2884 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002885 myexponent = 0x7ff;
2886 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002887 } else {
2888 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002889 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002890 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002891 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002892
Evan Cheng48e8c802008-05-02 21:15:08 +00002893 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002894 ((myexponent & 0x7ff) << 52) |
2895 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002896}
2897
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002898APInt
Neil Booth4f881702007-09-26 21:33:42 +00002899APFloat::convertFloatAPFloatToAPInt() const
2900{
Dan Gohmancb648f92007-09-14 20:08:19 +00002901 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002902 assert(partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002903
Dale Johanneseneaf08942007-08-31 04:03:46 +00002904 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002905
2906 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002907 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002908 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002909 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002910 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002911 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002912 myexponent = 0;
2913 mysignificand = 0;
2914 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002915 myexponent = 0xff;
2916 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002917 } else {
2918 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002919 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002920 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002921 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002922
Chris Lattnera11ef822007-10-06 06:13:42 +00002923 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2924 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002925}
2926
Chris Lattnercc4287a2009-10-16 02:13:51 +00002927APInt
2928APFloat::convertHalfAPFloatToAPInt() const
2929{
2930 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002931 assert(partCount()==1);
Chris Lattnercc4287a2009-10-16 02:13:51 +00002932
2933 uint32_t myexponent, mysignificand;
2934
2935 if (category==fcNormal) {
2936 myexponent = exponent+15; //bias
2937 mysignificand = (uint32_t)*significandParts();
2938 if (myexponent == 1 && !(mysignificand & 0x400))
2939 myexponent = 0; // denormal
2940 } else if (category==fcZero) {
2941 myexponent = 0;
2942 mysignificand = 0;
2943 } else if (category==fcInfinity) {
Dale Johannesena223aed2009-10-23 04:02:51 +00002944 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002945 mysignificand = 0;
2946 } else {
2947 assert(category == fcNaN && "Unknown category!");
Dale Johannesena223aed2009-10-23 04:02:51 +00002948 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002949 mysignificand = (uint32_t)*significandParts();
2950 }
2951
2952 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2953 (mysignificand & 0x3ff)));
2954}
2955
Dale Johannesena471c2e2007-10-11 18:07:22 +00002956// This function creates an APInt that is just a bit map of the floating
2957// point constant as it would appear in memory. It is not a conversion,
2958// and treating the result as a normal integer is unlikely to be useful.
2959
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002960APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002961APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002962{
Chris Lattnercc4287a2009-10-16 02:13:51 +00002963 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2964 return convertHalfAPFloatToAPInt();
2965
Dan Gohmanb10abe12008-01-29 12:08:20 +00002966 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002967 return convertFloatAPFloatToAPInt();
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002968
Dan Gohmanb10abe12008-01-29 12:08:20 +00002969 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002970 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002971
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002972 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2973 return convertQuadrupleAPFloatToAPInt();
2974
Dan Gohmanb10abe12008-01-29 12:08:20 +00002975 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002976 return convertPPCDoubleDoubleAPFloatToAPInt();
2977
Dan Gohmanb10abe12008-01-29 12:08:20 +00002978 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002979 "unknown format!");
2980 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002981}
2982
Neil Booth4f881702007-09-26 21:33:42 +00002983float
2984APFloat::convertToFloat() const
2985{
Chris Lattnerad785002009-09-24 21:44:20 +00002986 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2987 "Float semantics are not IEEEsingle");
Dale Johannesen7111b022008-10-09 18:53:47 +00002988 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002989 return api.bitsToFloat();
2990}
2991
Neil Booth4f881702007-09-26 21:33:42 +00002992double
2993APFloat::convertToDouble() const
2994{
Chris Lattnerad785002009-09-24 21:44:20 +00002995 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2996 "Float semantics are not IEEEdouble");
Dale Johannesen7111b022008-10-09 18:53:47 +00002997 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002998 return api.bitsToDouble();
2999}
3000
Dale Johannesend3d8ce32008-10-06 18:22:29 +00003001/// Integer bit is explicit in this format. Intel hardware (387 and later)
3002/// does not support these bit patterns:
3003/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3004/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3005/// exponent = 0, integer bit 1 ("pseudodenormal")
3006/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3007/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003008void
Neil Booth4f881702007-09-26 21:33:42 +00003009APFloat::initFromF80LongDoubleAPInt(const APInt &api)
3010{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003011 assert(api.getBitWidth()==80);
3012 uint64_t i1 = api.getRawData()[0];
3013 uint64_t i2 = api.getRawData()[1];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00003014 uint64_t myexponent = (i2 & 0x7fff);
3015 uint64_t mysignificand = i1;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003016
3017 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00003018 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003019
Dale Johannesen1b25cb22009-03-23 21:16:53 +00003020 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003021 if (myexponent==0 && mysignificand==0) {
3022 // exponent, significand meaningless
3023 category = fcZero;
3024 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3025 // exponent, significand meaningless
3026 category = fcInfinity;
3027 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3028 // exponent meaningless
3029 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00003030 significandParts()[0] = mysignificand;
3031 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003032 } else {
3033 category = fcNormal;
3034 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00003035 significandParts()[0] = mysignificand;
3036 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003037 if (myexponent==0) // denormal
3038 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00003039 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003040}
3041
3042void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003043APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3044{
3045 assert(api.getBitWidth()==128);
3046 uint64_t i1 = api.getRawData()[0];
3047 uint64_t i2 = api.getRawData()[1];
3048 uint64_t myexponent = (i1 >> 52) & 0x7ff;
3049 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
3050 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
3051 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
3052
3053 initialize(&APFloat::PPCDoubleDouble);
3054 assert(partCount()==2);
3055
Evan Cheng48e8c802008-05-02 21:15:08 +00003056 sign = static_cast<unsigned int>(i1>>63);
3057 sign2 = static_cast<unsigned int>(i2>>63);
Dale Johannesena471c2e2007-10-11 18:07:22 +00003058 if (myexponent==0 && mysignificand==0) {
3059 // exponent, significand meaningless
3060 // exponent2 and significand2 are required to be 0; we don't check
3061 category = fcZero;
3062 } else if (myexponent==0x7ff && mysignificand==0) {
3063 // exponent, significand meaningless
3064 // exponent2 and significand2 are required to be 0; we don't check
3065 category = fcInfinity;
3066 } else if (myexponent==0x7ff && mysignificand!=0) {
Dan Gohman16e02092010-03-24 19:38:02 +00003067 // exponent meaningless. So is the whole second word, but keep it
Dale Johannesena471c2e2007-10-11 18:07:22 +00003068 // for determinism.
3069 category = fcNaN;
3070 exponent2 = myexponent2;
3071 significandParts()[0] = mysignificand;
3072 significandParts()[1] = mysignificand2;
3073 } else {
3074 category = fcNormal;
3075 // Note there is no category2; the second word is treated as if it is
3076 // fcNormal, although it might be something else considered by itself.
3077 exponent = myexponent - 1023;
3078 exponent2 = myexponent2 - 1023;
3079 significandParts()[0] = mysignificand;
3080 significandParts()[1] = mysignificand2;
3081 if (myexponent==0) // denormal
3082 exponent = -1022;
3083 else
3084 significandParts()[0] |= 0x10000000000000LL; // integer bit
Dan Gohman16e02092010-03-24 19:38:02 +00003085 if (myexponent2==0)
Dale Johannesena471c2e2007-10-11 18:07:22 +00003086 exponent2 = -1022;
3087 else
3088 significandParts()[1] |= 0x10000000000000LL; // integer bit
3089 }
3090}
3091
3092void
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003093APFloat::initFromQuadrupleAPInt(const APInt &api)
3094{
3095 assert(api.getBitWidth()==128);
3096 uint64_t i1 = api.getRawData()[0];
3097 uint64_t i2 = api.getRawData()[1];
3098 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3099 uint64_t mysignificand = i1;
3100 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3101
3102 initialize(&APFloat::IEEEquad);
3103 assert(partCount()==2);
3104
3105 sign = static_cast<unsigned int>(i2>>63);
3106 if (myexponent==0 &&
3107 (mysignificand==0 && mysignificand2==0)) {
3108 // exponent, significand meaningless
3109 category = fcZero;
3110 } else if (myexponent==0x7fff &&
3111 (mysignificand==0 && mysignificand2==0)) {
3112 // exponent, significand meaningless
3113 category = fcInfinity;
3114 } else if (myexponent==0x7fff &&
3115 (mysignificand!=0 || mysignificand2 !=0)) {
3116 // exponent meaningless
3117 category = fcNaN;
3118 significandParts()[0] = mysignificand;
3119 significandParts()[1] = mysignificand2;
3120 } else {
3121 category = fcNormal;
3122 exponent = myexponent - 16383;
3123 significandParts()[0] = mysignificand;
3124 significandParts()[1] = mysignificand2;
3125 if (myexponent==0) // denormal
3126 exponent = -16382;
3127 else
3128 significandParts()[1] |= 0x1000000000000LL; // integer bit
3129 }
3130}
3131
3132void
Neil Booth4f881702007-09-26 21:33:42 +00003133APFloat::initFromDoubleAPInt(const APInt &api)
3134{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003135 assert(api.getBitWidth()==64);
3136 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003137 uint64_t myexponent = (i >> 52) & 0x7ff;
3138 uint64_t mysignificand = i & 0xfffffffffffffLL;
3139
Dale Johannesen343e7702007-08-24 00:56:33 +00003140 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00003141 assert(partCount()==1);
3142
Evan Cheng48e8c802008-05-02 21:15:08 +00003143 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00003144 if (myexponent==0 && mysignificand==0) {
3145 // exponent, significand meaningless
3146 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003147 } else if (myexponent==0x7ff && mysignificand==0) {
3148 // exponent, significand meaningless
3149 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00003150 } else if (myexponent==0x7ff && mysignificand!=0) {
3151 // exponent meaningless
3152 category = fcNaN;
3153 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003154 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00003155 category = fcNormal;
3156 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003157 *significandParts() = mysignificand;
3158 if (myexponent==0) // denormal
3159 exponent = -1022;
3160 else
3161 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00003162 }
Dale Johannesen343e7702007-08-24 00:56:33 +00003163}
3164
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003165void
Neil Booth4f881702007-09-26 21:33:42 +00003166APFloat::initFromFloatAPInt(const APInt & api)
3167{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003168 assert(api.getBitWidth()==32);
3169 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003170 uint32_t myexponent = (i >> 23) & 0xff;
3171 uint32_t mysignificand = i & 0x7fffff;
3172
Dale Johannesen343e7702007-08-24 00:56:33 +00003173 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00003174 assert(partCount()==1);
3175
Dale Johanneseneaf08942007-08-31 04:03:46 +00003176 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00003177 if (myexponent==0 && mysignificand==0) {
3178 // exponent, significand meaningless
3179 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003180 } else if (myexponent==0xff && mysignificand==0) {
3181 // exponent, significand meaningless
3182 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00003183 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00003184 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00003185 category = fcNaN;
3186 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003187 } else {
3188 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00003189 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003190 *significandParts() = mysignificand;
3191 if (myexponent==0) // denormal
3192 exponent = -126;
3193 else
3194 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00003195 }
3196}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003197
Chris Lattnercc4287a2009-10-16 02:13:51 +00003198void
3199APFloat::initFromHalfAPInt(const APInt & api)
3200{
3201 assert(api.getBitWidth()==16);
3202 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesena223aed2009-10-23 04:02:51 +00003203 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00003204 uint32_t mysignificand = i & 0x3ff;
3205
3206 initialize(&APFloat::IEEEhalf);
3207 assert(partCount()==1);
3208
3209 sign = i >> 15;
3210 if (myexponent==0 && mysignificand==0) {
3211 // exponent, significand meaningless
3212 category = fcZero;
3213 } else if (myexponent==0x1f && mysignificand==0) {
3214 // exponent, significand meaningless
3215 category = fcInfinity;
3216 } else if (myexponent==0x1f && mysignificand!=0) {
3217 // sign, exponent, significand meaningless
3218 category = fcNaN;
3219 *significandParts() = mysignificand;
3220 } else {
3221 category = fcNormal;
3222 exponent = myexponent - 15; //bias
3223 *significandParts() = mysignificand;
3224 if (myexponent==0) // denormal
3225 exponent = -14;
3226 else
3227 *significandParts() |= 0x400; // integer bit
3228 }
3229}
3230
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003231/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00003232/// we infer the floating point type from the size of the APInt. The
3233/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3234/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003235void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003236APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003237{
Chris Lattnercc4287a2009-10-16 02:13:51 +00003238 if (api.getBitWidth() == 16)
3239 return initFromHalfAPInt(api);
3240 else if (api.getBitWidth() == 32)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003241 return initFromFloatAPInt(api);
3242 else if (api.getBitWidth()==64)
3243 return initFromDoubleAPInt(api);
3244 else if (api.getBitWidth()==80)
3245 return initFromF80LongDoubleAPInt(api);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003246 else if (api.getBitWidth()==128)
3247 return (isIEEE ?
3248 initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003249 else
Torok Edwinc23197a2009-07-14 16:55:14 +00003250 llvm_unreachable(0);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003251}
3252
Nadav Rotem093399c2011-02-17 21:22:27 +00003253APFloat
3254APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3255{
3256 return APFloat(APInt::getAllOnesValue(BitWidth), isIEEE);
3257}
3258
John McCall00e65de2009-12-24 08:56:26 +00003259APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3260 APFloat Val(Sem, fcNormal, Negative);
3261
3262 // We want (in interchange format):
3263 // sign = {Negative}
3264 // exponent = 1..10
3265 // significand = 1..1
3266
3267 Val.exponent = Sem.maxExponent; // unbiased
3268
3269 // 1-initialize all bits....
3270 Val.zeroSignificand();
3271 integerPart *significand = Val.significandParts();
3272 unsigned N = partCountForBits(Sem.precision);
3273 for (unsigned i = 0; i != N; ++i)
3274 significand[i] = ~((integerPart) 0);
3275
3276 // ...and then clear the top bits for internal consistency.
Eli Friedman7247a5f2011-10-12 21:51:36 +00003277 if (Sem.precision % integerPartWidth != 0)
3278 significand[N-1] &=
3279 (((integerPart) 1) << (Sem.precision % integerPartWidth)) - 1;
John McCall00e65de2009-12-24 08:56:26 +00003280
3281 return Val;
3282}
3283
3284APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3285 APFloat Val(Sem, fcNormal, Negative);
3286
3287 // We want (in interchange format):
3288 // sign = {Negative}
3289 // exponent = 0..0
3290 // significand = 0..01
3291
3292 Val.exponent = Sem.minExponent; // unbiased
3293 Val.zeroSignificand();
3294 Val.significandParts()[0] = 1;
3295 return Val;
3296}
3297
3298APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3299 APFloat Val(Sem, fcNormal, Negative);
3300
3301 // We want (in interchange format):
3302 // sign = {Negative}
3303 // exponent = 0..0
3304 // significand = 10..0
3305
3306 Val.exponent = Sem.minExponent;
3307 Val.zeroSignificand();
Dan Gohman16e02092010-03-24 19:38:02 +00003308 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
Eli Friedman90196fc2011-10-12 21:56:19 +00003309 (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
John McCall00e65de2009-12-24 08:56:26 +00003310
3311 return Val;
3312}
3313
Bill Wendlingf09a8b52011-03-18 09:09:44 +00003314APFloat::APFloat(const APInt& api, bool isIEEE) : exponent2(0), sign2(0) {
Dale Johannesena471c2e2007-10-11 18:07:22 +00003315 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003316}
3317
Bill Wendlingf09a8b52011-03-18 09:09:44 +00003318APFloat::APFloat(float f) : exponent2(0), sign2(0) {
Jay Foade4d19c92010-11-28 21:04:48 +00003319 initFromAPInt(APInt::floatToBits(f));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003320}
3321
Bill Wendlingf09a8b52011-03-18 09:09:44 +00003322APFloat::APFloat(double d) : exponent2(0), sign2(0) {
Jay Foade4d19c92010-11-28 21:04:48 +00003323 initFromAPInt(APInt::doubleToBits(d));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003324}
John McCall00e65de2009-12-24 08:56:26 +00003325
3326namespace {
David Blaikie9f14ed12012-07-25 18:04:24 +00003327 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3328 Buffer.append(Str.begin(), Str.end());
John McCall00e65de2009-12-24 08:56:26 +00003329 }
3330
John McCall003a09c2009-12-24 12:16:56 +00003331 /// Removes data from the given significand until it is no more
3332 /// precise than is required for the desired precision.
3333 void AdjustToPrecision(APInt &significand,
3334 int &exp, unsigned FormatPrecision) {
3335 unsigned bits = significand.getActiveBits();
3336
3337 // 196/59 is a very slight overestimate of lg_2(10).
3338 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3339
3340 if (bits <= bitsRequired) return;
3341
3342 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3343 if (!tensRemovable) return;
3344
3345 exp += tensRemovable;
3346
3347 APInt divisor(significand.getBitWidth(), 1);
3348 APInt powten(significand.getBitWidth(), 10);
3349 while (true) {
3350 if (tensRemovable & 1)
3351 divisor *= powten;
3352 tensRemovable >>= 1;
3353 if (!tensRemovable) break;
3354 powten *= powten;
3355 }
3356
3357 significand = significand.udiv(divisor);
3358
3359 // Truncate the significand down to its active bit count, but
3360 // don't try to drop below 32.
John McCall6a09aff2009-12-24 23:18:09 +00003361 unsigned newPrecision = std::max(32U, significand.getActiveBits());
Jay Foad40f8f622010-12-07 08:25:19 +00003362 significand = significand.trunc(newPrecision);
John McCall003a09c2009-12-24 12:16:56 +00003363 }
3364
3365
John McCall00e65de2009-12-24 08:56:26 +00003366 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3367 int &exp, unsigned FormatPrecision) {
3368 unsigned N = buffer.size();
3369 if (N <= FormatPrecision) return;
3370
3371 // The most significant figures are the last ones in the buffer.
3372 unsigned FirstSignificant = N - FormatPrecision;
3373
3374 // Round.
3375 // FIXME: this probably shouldn't use 'round half up'.
3376
3377 // Rounding down is just a truncation, except we also want to drop
3378 // trailing zeros from the new result.
3379 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi752b2f02012-02-19 03:18:29 +00003380 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall00e65de2009-12-24 08:56:26 +00003381 FirstSignificant++;
3382
3383 exp += FirstSignificant;
3384 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3385 return;
3386 }
3387
3388 // Rounding up requires a decimal add-with-carry. If we continue
3389 // the carry, the newly-introduced zeros will just be truncated.
3390 for (unsigned I = FirstSignificant; I != N; ++I) {
3391 if (buffer[I] == '9') {
3392 FirstSignificant++;
3393 } else {
3394 buffer[I]++;
3395 break;
3396 }
3397 }
3398
3399 // If we carried through, we have exactly one digit of precision.
3400 if (FirstSignificant == N) {
3401 exp += FirstSignificant;
3402 buffer.clear();
3403 buffer.push_back('1');
3404 return;
3405 }
3406
3407 exp += FirstSignificant;
3408 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3409 }
3410}
3411
3412void APFloat::toString(SmallVectorImpl<char> &Str,
3413 unsigned FormatPrecision,
Chris Lattner0ddda3b2010-03-06 19:20:13 +00003414 unsigned FormatMaxPadding) const {
John McCall00e65de2009-12-24 08:56:26 +00003415 switch (category) {
3416 case fcInfinity:
3417 if (isNegative())
3418 return append(Str, "-Inf");
3419 else
3420 return append(Str, "+Inf");
3421
3422 case fcNaN: return append(Str, "NaN");
3423
3424 case fcZero:
3425 if (isNegative())
3426 Str.push_back('-');
3427
3428 if (!FormatMaxPadding)
3429 append(Str, "0.0E+0");
3430 else
3431 Str.push_back('0');
3432 return;
3433
3434 case fcNormal:
3435 break;
3436 }
3437
3438 if (isNegative())
3439 Str.push_back('-');
3440
3441 // Decompose the number into an APInt and an exponent.
3442 int exp = exponent - ((int) semantics->precision - 1);
3443 APInt significand(semantics->precision,
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00003444 makeArrayRef(significandParts(),
3445 partCountForBits(semantics->precision)));
John McCall00e65de2009-12-24 08:56:26 +00003446
John McCall6a09aff2009-12-24 23:18:09 +00003447 // Set FormatPrecision if zero. We want to do this before we
3448 // truncate trailing zeros, as those are part of the precision.
3449 if (!FormatPrecision) {
3450 // It's an interesting question whether to use the nominal
3451 // precision or the active precision here for denormals.
3452
3453 // FormatPrecision = ceil(significandBits / lg_2(10))
3454 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3455 }
3456
John McCall00e65de2009-12-24 08:56:26 +00003457 // Ignore trailing binary zeros.
3458 int trailingZeros = significand.countTrailingZeros();
3459 exp += trailingZeros;
3460 significand = significand.lshr(trailingZeros);
3461
3462 // Change the exponent from 2^e to 10^e.
3463 if (exp == 0) {
3464 // Nothing to do.
3465 } else if (exp > 0) {
3466 // Just shift left.
Jay Foad40f8f622010-12-07 08:25:19 +00003467 significand = significand.zext(semantics->precision + exp);
John McCall00e65de2009-12-24 08:56:26 +00003468 significand <<= exp;
3469 exp = 0;
3470 } else { /* exp < 0 */
3471 int texp = -exp;
3472
3473 // We transform this using the identity:
3474 // (N)(2^-e) == (N)(5^e)(10^-e)
3475 // This means we have to multiply N (the significand) by 5^e.
3476 // To avoid overflow, we have to operate on numbers large
3477 // enough to store N * 5^e:
3478 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCall6a09aff2009-12-24 23:18:09 +00003479 // <= semantics->precision + e * 137 / 59
3480 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohman16e02092010-03-24 19:38:02 +00003481
Eli Friedman9eb6b4d2011-10-07 23:40:49 +00003482 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall00e65de2009-12-24 08:56:26 +00003483
3484 // Multiply significand by 5^e.
3485 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad40f8f622010-12-07 08:25:19 +00003486 significand = significand.zext(precision);
John McCall00e65de2009-12-24 08:56:26 +00003487 APInt five_to_the_i(precision, 5);
3488 while (true) {
3489 if (texp & 1) significand *= five_to_the_i;
Dan Gohman16e02092010-03-24 19:38:02 +00003490
John McCall00e65de2009-12-24 08:56:26 +00003491 texp >>= 1;
3492 if (!texp) break;
3493 five_to_the_i *= five_to_the_i;
3494 }
3495 }
3496
John McCall003a09c2009-12-24 12:16:56 +00003497 AdjustToPrecision(significand, exp, FormatPrecision);
3498
John McCall00e65de2009-12-24 08:56:26 +00003499 llvm::SmallVector<char, 256> buffer;
3500
3501 // Fill the buffer.
3502 unsigned precision = significand.getBitWidth();
3503 APInt ten(precision, 10);
3504 APInt digit(precision, 0);
3505
3506 bool inTrail = true;
3507 while (significand != 0) {
3508 // digit <- significand % 10
3509 // significand <- significand / 10
3510 APInt::udivrem(significand, ten, significand, digit);
3511
3512 unsigned d = digit.getZExtValue();
3513
3514 // Drop trailing zeros.
3515 if (inTrail && !d) exp++;
3516 else {
3517 buffer.push_back((char) ('0' + d));
3518 inTrail = false;
3519 }
3520 }
3521
3522 assert(!buffer.empty() && "no characters in buffer!");
3523
3524 // Drop down to FormatPrecision.
3525 // TODO: don't do more precise calculations above than are required.
3526 AdjustToPrecision(buffer, exp, FormatPrecision);
3527
3528 unsigned NDigits = buffer.size();
3529
John McCall6a09aff2009-12-24 23:18:09 +00003530 // Check whether we should use scientific notation.
John McCall00e65de2009-12-24 08:56:26 +00003531 bool FormatScientific;
3532 if (!FormatMaxPadding)
3533 FormatScientific = true;
3534 else {
John McCall00e65de2009-12-24 08:56:26 +00003535 if (exp >= 0) {
John McCall6a09aff2009-12-24 23:18:09 +00003536 // 765e3 --> 765000
3537 // ^^^
3538 // But we shouldn't make the number look more precise than it is.
3539 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3540 NDigits + (unsigned) exp > FormatPrecision);
John McCall00e65de2009-12-24 08:56:26 +00003541 } else {
John McCall6a09aff2009-12-24 23:18:09 +00003542 // Power of the most significant digit.
3543 int MSD = exp + (int) (NDigits - 1);
3544 if (MSD >= 0) {
John McCall00e65de2009-12-24 08:56:26 +00003545 // 765e-2 == 7.65
John McCall6a09aff2009-12-24 23:18:09 +00003546 FormatScientific = false;
John McCall00e65de2009-12-24 08:56:26 +00003547 } else {
3548 // 765e-5 == 0.00765
3549 // ^ ^^
John McCall6a09aff2009-12-24 23:18:09 +00003550 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall00e65de2009-12-24 08:56:26 +00003551 }
3552 }
John McCall00e65de2009-12-24 08:56:26 +00003553 }
3554
3555 // Scientific formatting is pretty straightforward.
3556 if (FormatScientific) {
3557 exp += (NDigits - 1);
3558
3559 Str.push_back(buffer[NDigits-1]);
3560 Str.push_back('.');
3561 if (NDigits == 1)
3562 Str.push_back('0');
3563 else
3564 for (unsigned I = 1; I != NDigits; ++I)
3565 Str.push_back(buffer[NDigits-1-I]);
3566 Str.push_back('E');
3567
3568 Str.push_back(exp >= 0 ? '+' : '-');
3569 if (exp < 0) exp = -exp;
3570 SmallVector<char, 6> expbuf;
3571 do {
3572 expbuf.push_back((char) ('0' + (exp % 10)));
3573 exp /= 10;
3574 } while (exp);
3575 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3576 Str.push_back(expbuf[E-1-I]);
3577 return;
3578 }
3579
3580 // Non-scientific, positive exponents.
3581 if (exp >= 0) {
3582 for (unsigned I = 0; I != NDigits; ++I)
3583 Str.push_back(buffer[NDigits-1-I]);
3584 for (unsigned I = 0; I != (unsigned) exp; ++I)
3585 Str.push_back('0');
3586 return;
3587 }
3588
3589 // Non-scientific, negative exponents.
3590
3591 // The number of digits to the left of the decimal point.
3592 int NWholeDigits = exp + (int) NDigits;
3593
3594 unsigned I = 0;
3595 if (NWholeDigits > 0) {
3596 for (; I != (unsigned) NWholeDigits; ++I)
3597 Str.push_back(buffer[NDigits-I-1]);
3598 Str.push_back('.');
3599 } else {
3600 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3601
3602 Str.push_back('0');
3603 Str.push_back('.');
3604 for (unsigned Z = 1; Z != NZeros; ++Z)
3605 Str.push_back('0');
3606 }
3607
3608 for (; I != NDigits; ++I)
3609 Str.push_back(buffer[NDigits-I-1]);
3610}
Benjamin Kramer27460002011-03-30 15:42:27 +00003611
3612bool APFloat::getExactInverse(APFloat *inv) const {
Chris Lattner7a2bdde2011-04-15 05:18:47 +00003613 // We can only guarantee the existence of an exact inverse for IEEE floats.
Benjamin Kramer27460002011-03-30 15:42:27 +00003614 if (semantics != &IEEEhalf && semantics != &IEEEsingle &&
3615 semantics != &IEEEdouble && semantics != &IEEEquad)
3616 return false;
3617
3618 // Special floats and denormals have no exact inverse.
3619 if (category != fcNormal)
3620 return false;
3621
3622 // Check that the number is a power of two by making sure that only the
3623 // integer bit is set in the significand.
3624 if (significandLSB() != semantics->precision - 1)
3625 return false;
3626
3627 // Get the inverse.
3628 APFloat reciprocal(*semantics, 1ULL);
3629 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3630 return false;
3631
Benjamin Kramer83985122011-03-30 17:02:54 +00003632 // Avoid multiplication with a denormal, it is not safe on all platforms and
3633 // may be slower than a normal division.
3634 if (reciprocal.significandMSB() + 1 < reciprocal.semantics->precision)
3635 return false;
3636
3637 assert(reciprocal.category == fcNormal &&
3638 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3639
Benjamin Kramer27460002011-03-30 15:42:27 +00003640 if (inv)
3641 *inv = reciprocal;
3642
3643 return true;
3644}