blob: 2e785570113313887dba84484891a0eb5bec1c04 [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"
Erick Tryzelaara15d8902009-08-16 23:36:19 +000016#include "llvm/ADT/StringRef.h"
Ted Kremenek1f801fa2008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000018#include "llvm/Support/ErrorHandling.h"
Dale Johannesend3b51fd2007-08-24 05:08:11 +000019#include "llvm/Support/MathExtras.h"
John McCall8b3f3302010-02-26 22:20:41 +000020#include <limits.h>
Chris Lattnerfad86b02008-08-17 07:19:36 +000021#include <cstring>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000022
23using namespace llvm;
24
25#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
26
Neil Bootha30b0ee2007-10-03 22:26:02 +000027/* Assumed in hexadecimal significand parsing, and conversion to
28 hexadecimal strings. */
Chris Lattner9f17eb02008-08-17 04:58:58 +000029#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerb39cdde2007-08-20 22:49:32 +000030COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
31
32namespace llvm {
33
34 /* Represents floating point arithmetic semantics. */
35 struct fltSemantics {
36 /* The largest E such that 2^E is representable; this matches the
37 definition of IEEE 754. */
38 exponent_t maxExponent;
39
40 /* The smallest E such that 2^E is a normalized number; this
41 matches the definition of IEEE 754. */
42 exponent_t minExponent;
43
44 /* Number of bits in the significand. This includes the integer
45 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000046 unsigned int precision;
Neil Boothcaf19d72007-10-14 10:29:28 +000047
48 /* True if arithmetic is supported. */
49 unsigned int arithmeticOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000050 };
51
Chris Lattnercc4287a2009-10-16 02:13:51 +000052 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11, true };
Neil Boothcaf19d72007-10-14 10:29:28 +000053 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
54 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
55 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
56 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
57 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesena471c2e2007-10-11 18:07:22 +000058
59 // The PowerPC format consists of two doubles. It does not map cleanly
60 // onto the usual format above. For now only storage of constants of
61 // this type is supported, no arithmetic.
Neil Boothcaf19d72007-10-14 10:29:28 +000062 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
Neil Booth96c74712007-10-12 16:02:31 +000063
64 /* A tight upper bound on number of parts required to hold the value
65 pow(5, power) is
66
Neil Booth686700e2007-10-15 15:00:55 +000067 power * 815 / (351 * integerPartWidth) + 1
Dan Gohman16e02092010-03-24 19:38:02 +000068
Neil Booth96c74712007-10-12 16:02:31 +000069 However, whilst the result may require only this many parts,
70 because we are multiplying two values to get it, the
71 multiplication may require an extra part with the excess part
72 being zero (consider the trivial case of 1 * 1, tcFullMultiply
73 requires two parts to hold the single-part result). So we add an
74 extra one to guarantee enough space whilst multiplying. */
75 const unsigned int maxExponent = 16383;
76 const unsigned int maxPrecision = 113;
77 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth686700e2007-10-15 15:00:55 +000078 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
79 / (351 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000080}
81
Chris Lattnere213f3f2009-03-12 23:59:55 +000082/* A bunch of private, handy routines. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +000083
Chris Lattnere213f3f2009-03-12 23:59:55 +000084static inline unsigned int
85partCountForBits(unsigned int bits)
86{
87 return ((bits) + integerPartWidth - 1) / integerPartWidth;
88}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000089
Chris Lattnere213f3f2009-03-12 23:59:55 +000090/* Returns 0U-9U. Return values >= 10U are not digits. */
91static inline unsigned int
92decDigitValue(unsigned int c)
93{
94 return c - '0';
95}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000096
Chris Lattnere213f3f2009-03-12 23:59:55 +000097static unsigned int
98hexDigitValue(unsigned int c)
99{
100 unsigned int r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000101
Chris Lattnere213f3f2009-03-12 23:59:55 +0000102 r = c - '0';
Dan Gohman16e02092010-03-24 19:38:02 +0000103 if (r <= 9)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000104 return r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000105
Chris Lattnere213f3f2009-03-12 23:59:55 +0000106 r = c - 'A';
Dan Gohman16e02092010-03-24 19:38:02 +0000107 if (r <= 5)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000108 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000109
Chris Lattnere213f3f2009-03-12 23:59:55 +0000110 r = c - 'a';
Dan Gohman16e02092010-03-24 19:38:02 +0000111 if (r <= 5)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000112 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000113
Chris Lattnere213f3f2009-03-12 23:59:55 +0000114 return -1U;
115}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000116
Chris Lattnere213f3f2009-03-12 23:59:55 +0000117static inline void
118assertArithmeticOK(const llvm::fltSemantics &semantics) {
Dan Gohman16e02092010-03-24 19:38:02 +0000119 assert(semantics.arithmeticOK &&
120 "Compile-time arithmetic does not support these semantics");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000121}
Neil Boothcaf19d72007-10-14 10:29:28 +0000122
Chris Lattnere213f3f2009-03-12 23:59:55 +0000123/* Return the value of a decimal exponent of the form
124 [+-]ddddddd.
Neil Booth1870f292007-10-14 10:16:12 +0000125
Chris Lattnere213f3f2009-03-12 23:59:55 +0000126 If the exponent overflows, returns a large exponent with the
127 appropriate sign. */
128static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000129readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000130{
131 bool isNegative;
132 unsigned int absExponent;
133 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000134 StringRef::iterator p = begin;
135
136 assert(p != end && "Exponent has no digits");
Neil Booth1870f292007-10-14 10:16:12 +0000137
Chris Lattnere213f3f2009-03-12 23:59:55 +0000138 isNegative = (*p == '-');
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000139 if (*p == '-' || *p == '+') {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000140 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000141 assert(p != end && "Exponent has no digits");
142 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000143
Chris Lattnere213f3f2009-03-12 23:59:55 +0000144 absExponent = decDigitValue(*p++);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000145 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000146
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000147 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000148 unsigned int value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000149
Chris Lattnere213f3f2009-03-12 23:59:55 +0000150 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000151 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000152
Chris Lattnere213f3f2009-03-12 23:59:55 +0000153 value += absExponent * 10;
154 if (absExponent >= overlargeExponent) {
155 absExponent = overlargeExponent;
156 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000157 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000158 absExponent = value;
159 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000160
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000161 assert(p == end && "Invalid exponent in exponent");
162
Chris Lattnere213f3f2009-03-12 23:59:55 +0000163 if (isNegative)
164 return -(int) absExponent;
165 else
166 return (int) absExponent;
167}
168
169/* This is ugly and needs cleaning up, but I don't immediately see
170 how whilst remaining safe. */
171static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000172totalExponent(StringRef::iterator p, StringRef::iterator end,
173 int exponentAdjustment)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000174{
175 int unsignedExponent;
176 bool negative, overflow;
177 int exponent;
178
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000179 assert(p != end && "Exponent has no digits");
180
Chris Lattnere213f3f2009-03-12 23:59:55 +0000181 negative = *p == '-';
Dan Gohman16e02092010-03-24 19:38:02 +0000182 if (*p == '-' || *p == '+') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000183 p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000184 assert(p != end && "Exponent has no digits");
185 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000186
187 unsignedExponent = 0;
188 overflow = false;
Dan Gohman16e02092010-03-24 19:38:02 +0000189 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000190 unsigned int value;
191
192 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000193 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000194
Chris Lattnere213f3f2009-03-12 23:59:55 +0000195 unsignedExponent = unsignedExponent * 10 + value;
Dan Gohman16e02092010-03-24 19:38:02 +0000196 if (unsignedExponent > 65535)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000197 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000198 }
199
Dan Gohman16e02092010-03-24 19:38:02 +0000200 if (exponentAdjustment > 65535 || exponentAdjustment < -65536)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000201 overflow = true;
202
Dan Gohman16e02092010-03-24 19:38:02 +0000203 if (!overflow) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000204 exponent = unsignedExponent;
Dan Gohman16e02092010-03-24 19:38:02 +0000205 if (negative)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000206 exponent = -exponent;
207 exponent += exponentAdjustment;
Dan Gohman16e02092010-03-24 19:38:02 +0000208 if (exponent > 65535 || exponent < -65536)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000209 overflow = true;
210 }
211
Dan Gohman16e02092010-03-24 19:38:02 +0000212 if (overflow)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000213 exponent = negative ? -65536: 65535;
214
215 return exponent;
216}
217
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000218static StringRef::iterator
219skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
220 StringRef::iterator *dot)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000221{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000222 StringRef::iterator p = begin;
223 *dot = end;
Dan Gohman16e02092010-03-24 19:38:02 +0000224 while (*p == '0' && p != end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000225 p++;
226
Dan Gohman16e02092010-03-24 19:38:02 +0000227 if (*p == '.') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000228 *dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000229
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000230 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000231
Dan Gohman16e02092010-03-24 19:38:02 +0000232 while (*p == '0' && p != end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000233 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000234 }
235
Chris Lattnere213f3f2009-03-12 23:59:55 +0000236 return p;
237}
Neil Booth1870f292007-10-14 10:16:12 +0000238
Chris Lattnere213f3f2009-03-12 23:59:55 +0000239/* Given a normal decimal floating point number of the form
Neil Booth1870f292007-10-14 10:16:12 +0000240
Chris Lattnere213f3f2009-03-12 23:59:55 +0000241 dddd.dddd[eE][+-]ddd
Neil Booth686700e2007-10-15 15:00:55 +0000242
Chris Lattnere213f3f2009-03-12 23:59:55 +0000243 where the decimal point and exponent are optional, fill out the
244 structure D. Exponent is appropriate if the significand is
245 treated as an integer, and normalizedExponent if the significand
246 is taken to have the decimal point after a single leading
247 non-zero digit.
Neil Booth1870f292007-10-14 10:16:12 +0000248
Chris Lattnere213f3f2009-03-12 23:59:55 +0000249 If the value is zero, V->firstSigDigit points to a non-digit, and
250 the return exponent is zero.
251*/
252struct decimalInfo {
253 const char *firstSigDigit;
254 const char *lastSigDigit;
255 int exponent;
256 int normalizedExponent;
257};
Neil Booth1870f292007-10-14 10:16:12 +0000258
Chris Lattnere213f3f2009-03-12 23:59:55 +0000259static void
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000260interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
261 decimalInfo *D)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000262{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000263 StringRef::iterator dot = end;
264 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth1870f292007-10-14 10:16:12 +0000265
Chris Lattnere213f3f2009-03-12 23:59:55 +0000266 D->firstSigDigit = p;
267 D->exponent = 0;
268 D->normalizedExponent = 0;
269
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000270 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000271 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000272 assert(dot == end && "String contains multiple dots");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000273 dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000274 if (p == end)
275 break;
Neil Booth1870f292007-10-14 10:16:12 +0000276 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000277 if (decDigitValue(*p) >= 10U)
278 break;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000279 }
Neil Booth1870f292007-10-14 10:16:12 +0000280
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000281 if (p != end) {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000282 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
283 assert(p != begin && "Significand has no digits");
284 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000285
286 /* p points to the first non-digit in the string */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000287 D->exponent = readExponent(p + 1, end);
Neil Booth1870f292007-10-14 10:16:12 +0000288
Chris Lattnere213f3f2009-03-12 23:59:55 +0000289 /* Implied decimal point? */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000290 if (dot == end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000291 dot = p;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000292 }
Neil Booth1870f292007-10-14 10:16:12 +0000293
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000294 /* If number is all zeroes accept any exponent. */
295 if (p != D->firstSigDigit) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000296 /* Drop insignificant trailing zeroes. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000297 if (p != begin) {
Neil Booth1870f292007-10-14 10:16:12 +0000298 do
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000299 do
300 p--;
301 while (p != begin && *p == '0');
302 while (p != begin && *p == '.');
303 }
Neil Booth1870f292007-10-14 10:16:12 +0000304
Chris Lattnere213f3f2009-03-12 23:59:55 +0000305 /* Adjust the exponents for any decimal point. */
306 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
307 D->normalizedExponent = (D->exponent +
308 static_cast<exponent_t>((p - D->firstSigDigit)
309 - (dot > D->firstSigDigit && dot < p)));
Neil Booth1870f292007-10-14 10:16:12 +0000310 }
311
Chris Lattnere213f3f2009-03-12 23:59:55 +0000312 D->lastSigDigit = p;
313}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000314
Chris Lattnere213f3f2009-03-12 23:59:55 +0000315/* Return the trailing fraction of a hexadecimal number.
316 DIGITVALUE is the first hex digit of the fraction, P points to
317 the next digit. */
318static lostFraction
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000319trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
320 unsigned int digitValue)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000321{
322 unsigned int hexDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000323
Chris Lattnere213f3f2009-03-12 23:59:55 +0000324 /* If the first trailing digit isn't 0 or 8 we can work out the
325 fraction immediately. */
Dan Gohman16e02092010-03-24 19:38:02 +0000326 if (digitValue > 8)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000327 return lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000328 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000329 return lfLessThanHalf;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000330
331 /* Otherwise we need to find the first non-zero digit. */
Dan Gohman16e02092010-03-24 19:38:02 +0000332 while (*p == '0')
Chris Lattnere213f3f2009-03-12 23:59:55 +0000333 p++;
334
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000335 assert(p != end && "Invalid trailing hexadecimal fraction!");
336
Chris Lattnere213f3f2009-03-12 23:59:55 +0000337 hexDigit = hexDigitValue(*p);
338
339 /* If we ran off the end it is exactly zero or one-half, otherwise
340 a little more. */
Dan Gohman16e02092010-03-24 19:38:02 +0000341 if (hexDigit == -1U)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000342 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
343 else
344 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
345}
346
347/* Return the fraction lost were a bignum truncated losing the least
348 significant BITS bits. */
349static lostFraction
350lostFractionThroughTruncation(const integerPart *parts,
351 unsigned int partCount,
352 unsigned int bits)
353{
354 unsigned int lsb;
355
356 lsb = APInt::tcLSB(parts, partCount);
357
358 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohman16e02092010-03-24 19:38:02 +0000359 if (bits <= lsb)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000360 return lfExactlyZero;
Dan Gohman16e02092010-03-24 19:38:02 +0000361 if (bits == lsb + 1)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000362 return lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000363 if (bits <= partCount * integerPartWidth &&
364 APInt::tcExtractBit(parts, bits - 1))
Chris Lattnere213f3f2009-03-12 23:59:55 +0000365 return lfMoreThanHalf;
366
367 return lfLessThanHalf;
368}
369
370/* Shift DST right BITS bits noting lost fraction. */
371static lostFraction
372shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
373{
374 lostFraction lost_fraction;
375
376 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
377
378 APInt::tcShiftRight(dst, parts, bits);
379
380 return lost_fraction;
381}
382
383/* Combine the effect of two lost fractions. */
384static lostFraction
385combineLostFractions(lostFraction moreSignificant,
386 lostFraction lessSignificant)
387{
Dan Gohman16e02092010-03-24 19:38:02 +0000388 if (lessSignificant != lfExactlyZero) {
389 if (moreSignificant == lfExactlyZero)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000390 moreSignificant = lfLessThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000391 else if (moreSignificant == lfExactlyHalf)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000392 moreSignificant = lfMoreThanHalf;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000393 }
394
Chris Lattnere213f3f2009-03-12 23:59:55 +0000395 return moreSignificant;
396}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000397
Chris Lattnere213f3f2009-03-12 23:59:55 +0000398/* The error from the true value, in half-ulps, on multiplying two
399 floating point numbers, which differ from the value they
400 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
401 than the returned value.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000402
Chris Lattnere213f3f2009-03-12 23:59:55 +0000403 See "How to Read Floating Point Numbers Accurately" by William D
404 Clinger. */
405static unsigned int
406HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
407{
408 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000409
Chris Lattnere213f3f2009-03-12 23:59:55 +0000410 if (HUerr1 + HUerr2 == 0)
411 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
412 else
413 return inexactMultiply + 2 * (HUerr1 + HUerr2);
414}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000415
Chris Lattnere213f3f2009-03-12 23:59:55 +0000416/* The number of ulps from the boundary (zero, or half if ISNEAREST)
417 when the least significant BITS are truncated. BITS cannot be
418 zero. */
419static integerPart
420ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
421{
422 unsigned int count, partBits;
423 integerPart part, boundary;
Neil Booth33d4c922007-10-07 08:51:21 +0000424
Evan Cheng99ebfa52009-10-27 21:35:42 +0000425 assert(bits != 0);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000426
Chris Lattnere213f3f2009-03-12 23:59:55 +0000427 bits--;
428 count = bits / integerPartWidth;
429 partBits = bits % integerPartWidth + 1;
Neil Booth96c74712007-10-12 16:02:31 +0000430
Chris Lattnere213f3f2009-03-12 23:59:55 +0000431 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Booth96c74712007-10-12 16:02:31 +0000432
Chris Lattnere213f3f2009-03-12 23:59:55 +0000433 if (isNearest)
434 boundary = (integerPart) 1 << (partBits - 1);
435 else
436 boundary = 0;
437
438 if (count == 0) {
439 if (part - boundary <= boundary - part)
440 return part - boundary;
Neil Booth96c74712007-10-12 16:02:31 +0000441 else
Chris Lattnere213f3f2009-03-12 23:59:55 +0000442 return boundary - part;
Neil Booth96c74712007-10-12 16:02:31 +0000443 }
444
Chris Lattnere213f3f2009-03-12 23:59:55 +0000445 if (part == boundary) {
446 while (--count)
447 if (parts[count])
448 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000449
Chris Lattnere213f3f2009-03-12 23:59:55 +0000450 return parts[0];
451 } else if (part == boundary - 1) {
452 while (--count)
453 if (~parts[count])
454 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000455
Chris Lattnere213f3f2009-03-12 23:59:55 +0000456 return -parts[0];
457 }
Neil Booth96c74712007-10-12 16:02:31 +0000458
Chris Lattnere213f3f2009-03-12 23:59:55 +0000459 return ~(integerPart) 0; /* A lot. */
460}
Neil Booth96c74712007-10-12 16:02:31 +0000461
Chris Lattnere213f3f2009-03-12 23:59:55 +0000462/* Place pow(5, power) in DST, and return the number of parts used.
463 DST must be at least one part larger than size of the answer. */
464static unsigned int
465powerOf5(integerPart *dst, unsigned int power)
466{
467 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
468 15625, 78125 };
Chris Lattneree167a72009-03-13 00:24:01 +0000469 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
470 pow5s[0] = 78125 * 5;
Dan Gohman16e02092010-03-24 19:38:02 +0000471
Chris Lattner807926a2009-03-13 00:03:51 +0000472 unsigned int partsCount[16] = { 1 };
Chris Lattnere213f3f2009-03-12 23:59:55 +0000473 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
474 unsigned int result;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000475 assert(power <= maxExponent);
476
477 p1 = dst;
478 p2 = scratch;
479
480 *p1 = firstEightPowers[power & 7];
481 power >>= 3;
482
483 result = 1;
484 pow5 = pow5s;
485
486 for (unsigned int n = 0; power; power >>= 1, n++) {
487 unsigned int pc;
488
489 pc = partsCount[n];
490
491 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
492 if (pc == 0) {
493 pc = partsCount[n - 1];
494 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
495 pc *= 2;
496 if (pow5[pc - 1] == 0)
497 pc--;
498 partsCount[n] = pc;
Neil Booth96c74712007-10-12 16:02:31 +0000499 }
500
Chris Lattnere213f3f2009-03-12 23:59:55 +0000501 if (power & 1) {
502 integerPart *tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000503
Chris Lattnere213f3f2009-03-12 23:59:55 +0000504 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
505 result += pc;
506 if (p2[result - 1] == 0)
507 result--;
Neil Booth96c74712007-10-12 16:02:31 +0000508
Chris Lattnere213f3f2009-03-12 23:59:55 +0000509 /* Now result is in p1 with partsCount parts and p2 is scratch
510 space. */
511 tmp = p1, p1 = p2, p2 = tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000512 }
513
Chris Lattnere213f3f2009-03-12 23:59:55 +0000514 pow5 += pc;
Neil Booth96c74712007-10-12 16:02:31 +0000515 }
516
Chris Lattnere213f3f2009-03-12 23:59:55 +0000517 if (p1 != dst)
518 APInt::tcAssign(dst, p1, result);
Neil Booth96c74712007-10-12 16:02:31 +0000519
Chris Lattnere213f3f2009-03-12 23:59:55 +0000520 return result;
521}
Neil Booth96c74712007-10-12 16:02:31 +0000522
Chris Lattnere213f3f2009-03-12 23:59:55 +0000523/* Zero at the end to avoid modular arithmetic when adding one; used
524 when rounding up during hexadecimal output. */
525static const char hexDigitsLower[] = "0123456789abcdef0";
526static const char hexDigitsUpper[] = "0123456789ABCDEF0";
527static const char infinityL[] = "infinity";
528static const char infinityU[] = "INFINITY";
529static const char NaNL[] = "nan";
530static const char NaNU[] = "NAN";
Neil Booth96c74712007-10-12 16:02:31 +0000531
Chris Lattnere213f3f2009-03-12 23:59:55 +0000532/* Write out an integerPart in hexadecimal, starting with the most
533 significant nibble. Write out exactly COUNT hexdigits, return
534 COUNT. */
535static unsigned int
536partAsHex (char *dst, integerPart part, unsigned int count,
537 const char *hexDigitChars)
538{
539 unsigned int result = count;
Neil Booth96c74712007-10-12 16:02:31 +0000540
Evan Cheng99ebfa52009-10-27 21:35:42 +0000541 assert(count != 0 && count <= integerPartWidth / 4);
Neil Booth96c74712007-10-12 16:02:31 +0000542
Chris Lattnere213f3f2009-03-12 23:59:55 +0000543 part >>= (integerPartWidth - 4 * count);
544 while (count--) {
545 dst[count] = hexDigitChars[part & 0xf];
546 part >>= 4;
Neil Booth96c74712007-10-12 16:02:31 +0000547 }
548
Chris Lattnere213f3f2009-03-12 23:59:55 +0000549 return result;
550}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000551
Chris Lattnere213f3f2009-03-12 23:59:55 +0000552/* Write out an unsigned decimal integer. */
553static char *
554writeUnsignedDecimal (char *dst, unsigned int n)
555{
556 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000557
Chris Lattnere213f3f2009-03-12 23:59:55 +0000558 p = buff;
559 do
560 *p++ = '0' + n % 10;
561 while (n /= 10);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000562
Chris Lattnere213f3f2009-03-12 23:59:55 +0000563 do
564 *dst++ = *--p;
565 while (p != buff);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000566
Chris Lattnere213f3f2009-03-12 23:59:55 +0000567 return dst;
568}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000569
Chris Lattnere213f3f2009-03-12 23:59:55 +0000570/* Write out a signed decimal integer. */
571static char *
572writeSignedDecimal (char *dst, int value)
573{
574 if (value < 0) {
575 *dst++ = '-';
576 dst = writeUnsignedDecimal(dst, -(unsigned) value);
577 } else
578 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000579
Chris Lattnere213f3f2009-03-12 23:59:55 +0000580 return dst;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000581}
582
583/* Constructors. */
584void
585APFloat::initialize(const fltSemantics *ourSemantics)
586{
587 unsigned int count;
588
589 semantics = ourSemantics;
590 count = partCount();
Dan Gohman16e02092010-03-24 19:38:02 +0000591 if (count > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000592 significand.parts = new integerPart[count];
593}
594
595void
596APFloat::freeSignificand()
597{
Dan Gohman16e02092010-03-24 19:38:02 +0000598 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000599 delete [] significand.parts;
600}
601
602void
603APFloat::assign(const APFloat &rhs)
604{
605 assert(semantics == rhs.semantics);
606
607 sign = rhs.sign;
608 category = rhs.category;
609 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000610 sign2 = rhs.sign2;
611 exponent2 = rhs.exponent2;
Dan Gohman16e02092010-03-24 19:38:02 +0000612 if (category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000613 copySignificand(rhs);
614}
615
616void
617APFloat::copySignificand(const APFloat &rhs)
618{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000619 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000620 assert(rhs.partCount() >= partCount());
621
622 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000623 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000624}
625
Neil Boothe5e01942007-10-14 10:39:51 +0000626/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen541ed9f2009-01-21 20:32:55 +0000627 for the significand. If double or longer, this is a signalling NaN,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000628 which may not be ideal. If float, this is QNaN(0). */
John McCalle12b7382010-02-28 02:51:25 +0000629void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Boothe5e01942007-10-14 10:39:51 +0000630{
631 category = fcNaN;
John McCalle12b7382010-02-28 02:51:25 +0000632 sign = Negative;
633
John McCall165e96b2010-02-28 12:49:50 +0000634 integerPart *significand = significandParts();
635 unsigned numParts = partCount();
636
John McCalle12b7382010-02-28 02:51:25 +0000637 // Set the significand bits to the fill.
John McCall165e96b2010-02-28 12:49:50 +0000638 if (!fill || fill->getNumWords() < numParts)
639 APInt::tcSet(significand, 0, numParts);
640 if (fill) {
John McCalld44c6cc2010-03-01 18:38:45 +0000641 APInt::tcAssign(significand, fill->getRawData(),
642 std::min(fill->getNumWords(), numParts));
John McCall165e96b2010-02-28 12:49:50 +0000643
644 // Zero out the excess bits of the significand.
645 unsigned bitsToPreserve = semantics->precision - 1;
646 unsigned part = bitsToPreserve / 64;
647 bitsToPreserve %= 64;
648 significand[part] &= ((1ULL << bitsToPreserve) - 1);
649 for (part++; part != numParts; ++part)
650 significand[part] = 0;
651 }
652
653 unsigned QNaNBit = semantics->precision - 2;
John McCalle12b7382010-02-28 02:51:25 +0000654
655 if (SNaN) {
656 // We always have to clear the QNaN bit to make it an SNaN.
John McCall165e96b2010-02-28 12:49:50 +0000657 APInt::tcClearBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000658
659 // If there are no bits set in the payload, we have to set
660 // *something* to make it a NaN instead of an infinity;
661 // conventionally, this is the next bit down from the QNaN bit.
John McCall165e96b2010-02-28 12:49:50 +0000662 if (APInt::tcIsZero(significand, numParts))
663 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalle12b7382010-02-28 02:51:25 +0000664 } else {
665 // We always have to set the QNaN bit to make it a QNaN.
John McCall165e96b2010-02-28 12:49:50 +0000666 APInt::tcSetBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000667 }
John McCall165e96b2010-02-28 12:49:50 +0000668
669 // For x87 extended precision, we want to make a NaN, not a
670 // pseudo-NaN. Maybe we should expose the ability to make
671 // pseudo-NaNs?
672 if (semantics == &APFloat::x87DoubleExtended)
673 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalle12b7382010-02-28 02:51:25 +0000674}
675
676APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
677 const APInt *fill) {
678 APFloat value(Sem, uninitialized);
679 value.makeNaN(SNaN, Negative, fill);
680 return value;
Neil Boothe5e01942007-10-14 10:39:51 +0000681}
682
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000683APFloat &
684APFloat::operator=(const APFloat &rhs)
685{
Dan Gohman16e02092010-03-24 19:38:02 +0000686 if (this != &rhs) {
687 if (semantics != rhs.semantics) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000688 freeSignificand();
689 initialize(rhs.semantics);
690 }
691 assign(rhs);
692 }
693
694 return *this;
695}
696
Dale Johannesen343e7702007-08-24 00:56:33 +0000697bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000698APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000699 if (this == &rhs)
700 return true;
701 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000702 category != rhs.category ||
703 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000704 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000705 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000706 sign2 != rhs.sign2)
707 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000708 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000709 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000710 else if (category==fcNormal && exponent!=rhs.exponent)
711 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000712 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000713 exponent2!=rhs.exponent2)
714 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000715 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000716 int i= partCount();
717 const integerPart* p=significandParts();
718 const integerPart* q=rhs.significandParts();
719 for (; i>0; i--, p++, q++) {
720 if (*p != *q)
721 return false;
722 }
723 return true;
724 }
725}
726
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000727APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
728{
Neil Boothcaf19d72007-10-14 10:29:28 +0000729 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000730 initialize(&ourSemantics);
731 sign = 0;
732 zeroSignificand();
733 exponent = ourSemantics.precision - 1;
734 significandParts()[0] = value;
735 normalize(rmNearestTiesToEven, lfExactlyZero);
736}
737
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000738APFloat::APFloat(const fltSemantics &ourSemantics) {
739 assertArithmeticOK(ourSemantics);
740 initialize(&ourSemantics);
741 category = fcZero;
742 sign = false;
743}
744
John McCalle12b7382010-02-28 02:51:25 +0000745APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
746 assertArithmeticOK(ourSemantics);
747 // Allocates storage if necessary but does not initialize it.
748 initialize(&ourSemantics);
749}
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000750
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000751APFloat::APFloat(const fltSemantics &ourSemantics,
John McCalle12b7382010-02-28 02:51:25 +0000752 fltCategory ourCategory, bool negative)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000753{
Neil Boothcaf19d72007-10-14 10:29:28 +0000754 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000755 initialize(&ourSemantics);
756 category = ourCategory;
757 sign = negative;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000758 if (category == fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000759 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000760 else if (ourCategory == fcNaN)
John McCalle12b7382010-02-28 02:51:25 +0000761 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000762}
763
Benjamin Kramer38e59892010-07-14 22:38:02 +0000764APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000765{
Neil Boothcaf19d72007-10-14 10:29:28 +0000766 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000767 initialize(&ourSemantics);
768 convertFromString(text, rmNearestTiesToEven);
769}
770
771APFloat::APFloat(const APFloat &rhs)
772{
773 initialize(rhs.semantics);
774 assign(rhs);
775}
776
777APFloat::~APFloat()
778{
779 freeSignificand();
780}
781
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000782// Profile - This method 'profiles' an APFloat for use with FoldingSet.
783void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000784 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000785}
786
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000787unsigned int
788APFloat::partCount() const
789{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000790 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000791}
792
793unsigned int
794APFloat::semanticsPrecision(const fltSemantics &semantics)
795{
796 return semantics.precision;
797}
798
799const integerPart *
800APFloat::significandParts() const
801{
802 return const_cast<APFloat *>(this)->significandParts();
803}
804
805integerPart *
806APFloat::significandParts()
807{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000808 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000809
Evan Cheng99ebfa52009-10-27 21:35:42 +0000810 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000811 return significand.parts;
812 else
813 return &significand.part;
814}
815
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000816void
817APFloat::zeroSignificand()
818{
819 category = fcNormal;
820 APInt::tcSet(significandParts(), 0, partCount());
821}
822
823/* Increment an fcNormal floating point number's significand. */
824void
825APFloat::incrementSignificand()
826{
827 integerPart carry;
828
829 carry = APInt::tcIncrement(significandParts(), partCount());
830
831 /* Our callers should never cause us to overflow. */
832 assert(carry == 0);
833}
834
835/* Add the significand of the RHS. Returns the carry flag. */
836integerPart
837APFloat::addSignificand(const APFloat &rhs)
838{
839 integerPart *parts;
840
841 parts = significandParts();
842
843 assert(semantics == rhs.semantics);
844 assert(exponent == rhs.exponent);
845
846 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
847}
848
849/* Subtract the significand of the RHS with a borrow flag. Returns
850 the borrow flag. */
851integerPart
852APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
853{
854 integerPart *parts;
855
856 parts = significandParts();
857
858 assert(semantics == rhs.semantics);
859 assert(exponent == rhs.exponent);
860
861 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000862 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000863}
864
865/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
866 on to the full-precision result of the multiplication. Returns the
867 lost fraction. */
868lostFraction
869APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
870{
Neil Booth4f881702007-09-26 21:33:42 +0000871 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000872 unsigned int partsCount, newPartsCount, precision;
873 integerPart *lhsSignificand;
874 integerPart scratch[4];
875 integerPart *fullSignificand;
876 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000877 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000878
879 assert(semantics == rhs.semantics);
880
881 precision = semantics->precision;
882 newPartsCount = partCountForBits(precision * 2);
883
Dan Gohman16e02092010-03-24 19:38:02 +0000884 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000885 fullSignificand = new integerPart[newPartsCount];
886 else
887 fullSignificand = scratch;
888
889 lhsSignificand = significandParts();
890 partsCount = partCount();
891
892 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000893 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000894
895 lost_fraction = lfExactlyZero;
896 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
897 exponent += rhs.exponent;
898
Dan Gohman16e02092010-03-24 19:38:02 +0000899 if (addend) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000900 Significand savedSignificand = significand;
901 const fltSemantics *savedSemantics = semantics;
902 fltSemantics extendedSemantics;
903 opStatus status;
904 unsigned int extendedPrecision;
905
906 /* Normalize our MSB. */
907 extendedPrecision = precision + precision - 1;
Dan Gohman16e02092010-03-24 19:38:02 +0000908 if (omsb != extendedPrecision) {
909 APInt::tcShiftLeft(fullSignificand, newPartsCount,
910 extendedPrecision - omsb);
911 exponent -= extendedPrecision - omsb;
912 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000913
914 /* Create new semantics. */
915 extendedSemantics = *semantics;
916 extendedSemantics.precision = extendedPrecision;
917
Dan Gohman16e02092010-03-24 19:38:02 +0000918 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000919 significand.part = fullSignificand[0];
920 else
921 significand.parts = fullSignificand;
922 semantics = &extendedSemantics;
923
924 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000925 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000926 assert(status == opOK);
927 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
928
929 /* Restore our state. */
Dan Gohman16e02092010-03-24 19:38:02 +0000930 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000931 fullSignificand[0] = significand.part;
932 significand = savedSignificand;
933 semantics = savedSemantics;
934
935 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
936 }
937
938 exponent -= (precision - 1);
939
Dan Gohman16e02092010-03-24 19:38:02 +0000940 if (omsb > precision) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000941 unsigned int bits, significantParts;
942 lostFraction lf;
943
944 bits = omsb - precision;
945 significantParts = partCountForBits(omsb);
946 lf = shiftRight(fullSignificand, significantParts, bits);
947 lost_fraction = combineLostFractions(lf, lost_fraction);
948 exponent += bits;
949 }
950
951 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
952
Dan Gohman16e02092010-03-24 19:38:02 +0000953 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000954 delete [] fullSignificand;
955
956 return lost_fraction;
957}
958
959/* Multiply the significands of LHS and RHS to DST. */
960lostFraction
961APFloat::divideSignificand(const APFloat &rhs)
962{
963 unsigned int bit, i, partsCount;
964 const integerPart *rhsSignificand;
965 integerPart *lhsSignificand, *dividend, *divisor;
966 integerPart scratch[4];
967 lostFraction lost_fraction;
968
969 assert(semantics == rhs.semantics);
970
971 lhsSignificand = significandParts();
972 rhsSignificand = rhs.significandParts();
973 partsCount = partCount();
974
Dan Gohman16e02092010-03-24 19:38:02 +0000975 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000976 dividend = new integerPart[partsCount * 2];
977 else
978 dividend = scratch;
979
980 divisor = dividend + partsCount;
981
982 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohman16e02092010-03-24 19:38:02 +0000983 for (i = 0; i < partsCount; i++) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000984 dividend[i] = lhsSignificand[i];
985 divisor[i] = rhsSignificand[i];
986 lhsSignificand[i] = 0;
987 }
988
989 exponent -= rhs.exponent;
990
991 unsigned int precision = semantics->precision;
992
993 /* Normalize the divisor. */
994 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohman16e02092010-03-24 19:38:02 +0000995 if (bit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000996 exponent += bit;
997 APInt::tcShiftLeft(divisor, partsCount, bit);
998 }
999
1000 /* Normalize the dividend. */
1001 bit = precision - APInt::tcMSB(dividend, 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(dividend, partsCount, bit);
1005 }
1006
Neil Booth96c74712007-10-12 16:02:31 +00001007 /* Ensure the dividend >= divisor initially for the loop below.
1008 Incidentally, this means that the division loop below is
1009 guaranteed to set the integer bit to one. */
Dan Gohman16e02092010-03-24 19:38:02 +00001010 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001011 exponent--;
1012 APInt::tcShiftLeft(dividend, partsCount, 1);
1013 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1014 }
1015
1016 /* Long division. */
Dan Gohman16e02092010-03-24 19:38:02 +00001017 for (bit = precision; bit; bit -= 1) {
1018 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001019 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1020 APInt::tcSetBit(lhsSignificand, bit - 1);
1021 }
1022
1023 APInt::tcShiftLeft(dividend, partsCount, 1);
1024 }
1025
1026 /* Figure out the lost fraction. */
1027 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1028
Dan Gohman16e02092010-03-24 19:38:02 +00001029 if (cmp > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001030 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001031 else if (cmp == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001032 lost_fraction = lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001033 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001034 lost_fraction = lfExactlyZero;
1035 else
1036 lost_fraction = lfLessThanHalf;
1037
Dan Gohman16e02092010-03-24 19:38:02 +00001038 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001039 delete [] dividend;
1040
1041 return lost_fraction;
1042}
1043
1044unsigned int
1045APFloat::significandMSB() const
1046{
1047 return APInt::tcMSB(significandParts(), partCount());
1048}
1049
1050unsigned int
1051APFloat::significandLSB() const
1052{
1053 return APInt::tcLSB(significandParts(), partCount());
1054}
1055
1056/* Note that a zero result is NOT normalized to fcZero. */
1057lostFraction
1058APFloat::shiftSignificandRight(unsigned int bits)
1059{
1060 /* Our exponent should not overflow. */
1061 assert((exponent_t) (exponent + bits) >= exponent);
1062
1063 exponent += bits;
1064
1065 return shiftRight(significandParts(), partCount(), bits);
1066}
1067
1068/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1069void
1070APFloat::shiftSignificandLeft(unsigned int bits)
1071{
1072 assert(bits < semantics->precision);
1073
Dan Gohman16e02092010-03-24 19:38:02 +00001074 if (bits) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001075 unsigned int partsCount = partCount();
1076
1077 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1078 exponent -= bits;
1079
1080 assert(!APInt::tcIsZero(significandParts(), partsCount));
1081 }
1082}
1083
1084APFloat::cmpResult
1085APFloat::compareAbsoluteValue(const APFloat &rhs) const
1086{
1087 int compare;
1088
1089 assert(semantics == rhs.semantics);
1090 assert(category == fcNormal);
1091 assert(rhs.category == fcNormal);
1092
1093 compare = exponent - rhs.exponent;
1094
1095 /* If exponents are equal, do an unsigned bignum comparison of the
1096 significands. */
Dan Gohman16e02092010-03-24 19:38:02 +00001097 if (compare == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001098 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001099 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001100
Dan Gohman16e02092010-03-24 19:38:02 +00001101 if (compare > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001102 return cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001103 else if (compare < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001104 return cmpLessThan;
1105 else
1106 return cmpEqual;
1107}
1108
1109/* Handle overflow. Sign is preserved. We either become infinity or
1110 the largest finite number. */
1111APFloat::opStatus
1112APFloat::handleOverflow(roundingMode rounding_mode)
1113{
1114 /* Infinity? */
Dan Gohman16e02092010-03-24 19:38:02 +00001115 if (rounding_mode == rmNearestTiesToEven ||
1116 rounding_mode == rmNearestTiesToAway ||
1117 (rounding_mode == rmTowardPositive && !sign) ||
1118 (rounding_mode == rmTowardNegative && sign)) {
1119 category = fcInfinity;
1120 return (opStatus) (opOverflow | opInexact);
1121 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001122
1123 /* Otherwise we become the largest finite number. */
1124 category = fcNormal;
1125 exponent = semantics->maxExponent;
1126 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001127 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001128
1129 return opInexact;
1130}
1131
Neil Boothb7dea4c2007-10-03 15:16:41 +00001132/* Returns TRUE if, when truncating the current number, with BIT the
1133 new LSB, with the given lost fraction and rounding mode, the result
1134 would need to be rounded away from zero (i.e., by increasing the
1135 signficand). This routine must work for fcZero of both signs, and
1136 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001137bool
1138APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001139 lostFraction lost_fraction,
1140 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001141{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001142 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001143 assert(category == fcNormal || category == fcZero);
1144
Neil Boothb7dea4c2007-10-03 15:16:41 +00001145 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001146 assert(lost_fraction != lfExactlyZero);
1147
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001148 switch (rounding_mode) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001149 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001150 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001151
1152 case rmNearestTiesToAway:
1153 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1154
1155 case rmNearestTiesToEven:
Dan Gohman16e02092010-03-24 19:38:02 +00001156 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001157 return true;
1158
1159 /* Our zeroes don't have a significand to test. */
Dan Gohman16e02092010-03-24 19:38:02 +00001160 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001161 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001162
1163 return false;
1164
1165 case rmTowardZero:
1166 return false;
1167
1168 case rmTowardPositive:
1169 return sign == false;
1170
1171 case rmTowardNegative:
1172 return sign == true;
1173 }
1174}
1175
1176APFloat::opStatus
1177APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001178 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001179{
Neil Booth4f881702007-09-26 21:33:42 +00001180 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001181 int exponentChange;
1182
Dan Gohman16e02092010-03-24 19:38:02 +00001183 if (category != fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001184 return opOK;
1185
1186 /* Before rounding normalize the exponent of fcNormal numbers. */
1187 omsb = significandMSB() + 1;
1188
Dan Gohman16e02092010-03-24 19:38:02 +00001189 if (omsb) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001190 /* OMSB is numbered from 1. We want to place it in the integer
1191 bit numbered PRECISON if possible, with a compensating change in
1192 the exponent. */
1193 exponentChange = omsb - semantics->precision;
1194
1195 /* If the resulting exponent is too high, overflow according to
1196 the rounding mode. */
Dan Gohman16e02092010-03-24 19:38:02 +00001197 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001198 return handleOverflow(rounding_mode);
1199
1200 /* Subnormal numbers have exponent minExponent, and their MSB
1201 is forced based on that. */
Dan Gohman16e02092010-03-24 19:38:02 +00001202 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001203 exponentChange = semantics->minExponent - exponent;
1204
1205 /* Shifting left is easy as we don't lose precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001206 if (exponentChange < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001207 assert(lost_fraction == lfExactlyZero);
1208
1209 shiftSignificandLeft(-exponentChange);
1210
1211 return opOK;
1212 }
1213
Dan Gohman16e02092010-03-24 19:38:02 +00001214 if (exponentChange > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001215 lostFraction lf;
1216
1217 /* Shift right and capture any new lost fraction. */
1218 lf = shiftSignificandRight(exponentChange);
1219
1220 lost_fraction = combineLostFractions(lf, lost_fraction);
1221
1222 /* Keep OMSB up-to-date. */
Dan Gohman16e02092010-03-24 19:38:02 +00001223 if (omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001224 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001225 else
Neil Booth4f881702007-09-26 21:33:42 +00001226 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001227 }
1228 }
1229
1230 /* Now round the number according to rounding_mode given the lost
1231 fraction. */
1232
1233 /* As specified in IEEE 754, since we do not trap we do not report
1234 underflow for exact results. */
Dan Gohman16e02092010-03-24 19:38:02 +00001235 if (lost_fraction == lfExactlyZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001236 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001237 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001238 category = fcZero;
1239
1240 return opOK;
1241 }
1242
1243 /* Increment the significand if we're rounding away from zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001244 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1245 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001246 exponent = semantics->minExponent;
1247
1248 incrementSignificand();
1249 omsb = significandMSB() + 1;
1250
1251 /* Did the significand increment overflow? */
Dan Gohman16e02092010-03-24 19:38:02 +00001252 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001253 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001254 significand right one. However if we already have the
1255 maximum exponent we overflow to infinity. */
Dan Gohman16e02092010-03-24 19:38:02 +00001256 if (exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001257 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001258
Neil Booth4f881702007-09-26 21:33:42 +00001259 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001260 }
1261
1262 shiftSignificandRight(1);
1263
1264 return opInexact;
1265 }
1266 }
1267
1268 /* The normal case - we were and are not denormal, and any
1269 significand increment above didn't overflow. */
Dan Gohman16e02092010-03-24 19:38:02 +00001270 if (omsb == semantics->precision)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001271 return opInexact;
1272
1273 /* We have a non-zero denormal. */
1274 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001275
1276 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001277 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001278 category = fcZero;
1279
1280 /* The fcZero case is a denormal that underflowed to zero. */
1281 return (opStatus) (opUnderflow | opInexact);
1282}
1283
1284APFloat::opStatus
1285APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1286{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001287 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001288 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001289 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001290
Dale Johanneseneaf08942007-08-31 04:03:46 +00001291 case convolve(fcNaN, fcZero):
1292 case convolve(fcNaN, fcNormal):
1293 case convolve(fcNaN, fcInfinity):
1294 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001295 case convolve(fcNormal, fcZero):
1296 case convolve(fcInfinity, fcNormal):
1297 case convolve(fcInfinity, fcZero):
1298 return opOK;
1299
Dale Johanneseneaf08942007-08-31 04:03:46 +00001300 case convolve(fcZero, fcNaN):
1301 case convolve(fcNormal, fcNaN):
1302 case convolve(fcInfinity, fcNaN):
1303 category = fcNaN;
1304 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001305 return opOK;
1306
1307 case convolve(fcNormal, fcInfinity):
1308 case convolve(fcZero, fcInfinity):
1309 category = fcInfinity;
1310 sign = rhs.sign ^ subtract;
1311 return opOK;
1312
1313 case convolve(fcZero, fcNormal):
1314 assign(rhs);
1315 sign = rhs.sign ^ subtract;
1316 return opOK;
1317
1318 case convolve(fcZero, fcZero):
1319 /* Sign depends on rounding mode; handled by caller. */
1320 return opOK;
1321
1322 case convolve(fcInfinity, fcInfinity):
1323 /* Differently signed infinities can only be validly
1324 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001325 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001326 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001327 return opInvalidOp;
1328 }
1329
1330 return opOK;
1331
1332 case convolve(fcNormal, fcNormal):
1333 return opDivByZero;
1334 }
1335}
1336
1337/* Add or subtract two normal numbers. */
1338lostFraction
1339APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1340{
1341 integerPart carry;
1342 lostFraction lost_fraction;
1343 int bits;
1344
1345 /* Determine if the operation on the absolute values is effectively
1346 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001347 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001348
1349 /* Are we bigger exponent-wise than the RHS? */
1350 bits = exponent - rhs.exponent;
1351
1352 /* Subtraction is more subtle than one might naively expect. */
Dan Gohman16e02092010-03-24 19:38:02 +00001353 if (subtract) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001354 APFloat temp_rhs(rhs);
1355 bool reverse;
1356
Chris Lattnerada530b2007-08-24 03:02:34 +00001357 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001358 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1359 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001360 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001361 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1362 shiftSignificandLeft(1);
1363 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001364 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001365 lost_fraction = shiftSignificandRight(-bits - 1);
1366 temp_rhs.shiftSignificandLeft(1);
1367 reverse = true;
1368 }
1369
Chris Lattnerada530b2007-08-24 03:02:34 +00001370 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001371 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001372 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001373 copySignificand(temp_rhs);
1374 sign = !sign;
1375 } else {
1376 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001377 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001378 }
1379
1380 /* Invert the lost fraction - it was on the RHS and
1381 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001382 if (lost_fraction == lfLessThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001383 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001384 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001385 lost_fraction = lfLessThanHalf;
1386
1387 /* The code above is intended to ensure that no borrow is
1388 necessary. */
1389 assert(!carry);
1390 } else {
Dan Gohman16e02092010-03-24 19:38:02 +00001391 if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001392 APFloat temp_rhs(rhs);
1393
1394 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1395 carry = addSignificand(temp_rhs);
1396 } else {
1397 lost_fraction = shiftSignificandRight(-bits);
1398 carry = addSignificand(rhs);
1399 }
1400
1401 /* We have a guard bit; generating a carry cannot happen. */
1402 assert(!carry);
1403 }
1404
1405 return lost_fraction;
1406}
1407
1408APFloat::opStatus
1409APFloat::multiplySpecials(const APFloat &rhs)
1410{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001411 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001412 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001413 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001414
Dale Johanneseneaf08942007-08-31 04:03:46 +00001415 case convolve(fcNaN, fcZero):
1416 case convolve(fcNaN, fcNormal):
1417 case convolve(fcNaN, fcInfinity):
1418 case convolve(fcNaN, fcNaN):
1419 return opOK;
1420
1421 case convolve(fcZero, fcNaN):
1422 case convolve(fcNormal, fcNaN):
1423 case convolve(fcInfinity, fcNaN):
1424 category = fcNaN;
1425 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001426 return opOK;
1427
1428 case convolve(fcNormal, fcInfinity):
1429 case convolve(fcInfinity, fcNormal):
1430 case convolve(fcInfinity, fcInfinity):
1431 category = fcInfinity;
1432 return opOK;
1433
1434 case convolve(fcZero, fcNormal):
1435 case convolve(fcNormal, fcZero):
1436 case convolve(fcZero, fcZero):
1437 category = fcZero;
1438 return opOK;
1439
1440 case convolve(fcZero, fcInfinity):
1441 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001442 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001443 return opInvalidOp;
1444
1445 case convolve(fcNormal, fcNormal):
1446 return opOK;
1447 }
1448}
1449
1450APFloat::opStatus
1451APFloat::divideSpecials(const APFloat &rhs)
1452{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001453 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001454 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001455 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001456
Dale Johanneseneaf08942007-08-31 04:03:46 +00001457 case convolve(fcNaN, fcZero):
1458 case convolve(fcNaN, fcNormal):
1459 case convolve(fcNaN, fcInfinity):
1460 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001461 case convolve(fcInfinity, fcZero):
1462 case convolve(fcInfinity, fcNormal):
1463 case convolve(fcZero, fcInfinity):
1464 case convolve(fcZero, fcNormal):
1465 return opOK;
1466
Dale Johanneseneaf08942007-08-31 04:03:46 +00001467 case convolve(fcZero, fcNaN):
1468 case convolve(fcNormal, fcNaN):
1469 case convolve(fcInfinity, fcNaN):
1470 category = fcNaN;
1471 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001472 return opOK;
1473
1474 case convolve(fcNormal, fcInfinity):
1475 category = fcZero;
1476 return opOK;
1477
1478 case convolve(fcNormal, fcZero):
1479 category = fcInfinity;
1480 return opDivByZero;
1481
1482 case convolve(fcInfinity, fcInfinity):
1483 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001484 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001485 return opInvalidOp;
1486
1487 case convolve(fcNormal, fcNormal):
1488 return opOK;
1489 }
1490}
1491
Dale Johannesened6af242009-01-21 00:35:19 +00001492APFloat::opStatus
1493APFloat::modSpecials(const APFloat &rhs)
1494{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001495 switch (convolve(category, rhs.category)) {
Dale Johannesened6af242009-01-21 00:35:19 +00001496 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001497 llvm_unreachable(0);
Dale Johannesened6af242009-01-21 00:35:19 +00001498
1499 case convolve(fcNaN, fcZero):
1500 case convolve(fcNaN, fcNormal):
1501 case convolve(fcNaN, fcInfinity):
1502 case convolve(fcNaN, fcNaN):
1503 case convolve(fcZero, fcInfinity):
1504 case convolve(fcZero, fcNormal):
1505 case convolve(fcNormal, fcInfinity):
1506 return opOK;
1507
1508 case convolve(fcZero, fcNaN):
1509 case convolve(fcNormal, fcNaN):
1510 case convolve(fcInfinity, fcNaN):
1511 category = fcNaN;
1512 copySignificand(rhs);
1513 return opOK;
1514
1515 case convolve(fcNormal, fcZero):
1516 case convolve(fcInfinity, fcZero):
1517 case convolve(fcInfinity, fcNormal):
1518 case convolve(fcInfinity, fcInfinity):
1519 case convolve(fcZero, fcZero):
1520 makeNaN();
1521 return opInvalidOp;
1522
1523 case convolve(fcNormal, fcNormal):
1524 return opOK;
1525 }
1526}
1527
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001528/* Change sign. */
1529void
1530APFloat::changeSign()
1531{
1532 /* Look mummy, this one's easy. */
1533 sign = !sign;
1534}
1535
Dale Johannesene15c2db2007-08-31 23:35:31 +00001536void
1537APFloat::clearSign()
1538{
1539 /* So is this one. */
1540 sign = 0;
1541}
1542
1543void
1544APFloat::copySign(const APFloat &rhs)
1545{
1546 /* And this one. */
1547 sign = rhs.sign;
1548}
1549
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001550/* Normalized addition or subtraction. */
1551APFloat::opStatus
1552APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001553 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001554{
1555 opStatus fs;
1556
Neil Boothcaf19d72007-10-14 10:29:28 +00001557 assertArithmeticOK(*semantics);
1558
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001559 fs = addOrSubtractSpecials(rhs, subtract);
1560
1561 /* This return code means it was not a simple case. */
Dan Gohman16e02092010-03-24 19:38:02 +00001562 if (fs == opDivByZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001563 lostFraction lost_fraction;
1564
1565 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1566 fs = normalize(rounding_mode, lost_fraction);
1567
1568 /* Can only be zero if we lost no fraction. */
1569 assert(category != fcZero || lost_fraction == lfExactlyZero);
1570 }
1571
1572 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1573 positive zero unless rounding to minus infinity, except that
1574 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001575 if (category == fcZero) {
1576 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001577 sign = (rounding_mode == rmTowardNegative);
1578 }
1579
1580 return fs;
1581}
1582
1583/* Normalized addition. */
1584APFloat::opStatus
1585APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1586{
1587 return addOrSubtract(rhs, rounding_mode, false);
1588}
1589
1590/* Normalized subtraction. */
1591APFloat::opStatus
1592APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1593{
1594 return addOrSubtract(rhs, rounding_mode, true);
1595}
1596
1597/* Normalized multiply. */
1598APFloat::opStatus
1599APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1600{
1601 opStatus fs;
1602
Neil Boothcaf19d72007-10-14 10:29:28 +00001603 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001604 sign ^= rhs.sign;
1605 fs = multiplySpecials(rhs);
1606
Dan Gohman16e02092010-03-24 19:38:02 +00001607 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001608 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1609 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001610 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001611 fs = (opStatus) (fs | opInexact);
1612 }
1613
1614 return fs;
1615}
1616
1617/* Normalized divide. */
1618APFloat::opStatus
1619APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1620{
1621 opStatus fs;
1622
Neil Boothcaf19d72007-10-14 10:29:28 +00001623 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001624 sign ^= rhs.sign;
1625 fs = divideSpecials(rhs);
1626
Dan Gohman16e02092010-03-24 19:38:02 +00001627 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001628 lostFraction lost_fraction = divideSignificand(rhs);
1629 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001630 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001631 fs = (opStatus) (fs | opInexact);
1632 }
1633
1634 return fs;
1635}
1636
Dale Johannesen24b66a82009-01-20 18:35:05 +00001637/* Normalized remainder. This is not currently correct in all cases. */
1638APFloat::opStatus
1639APFloat::remainder(const APFloat &rhs)
1640{
1641 opStatus fs;
1642 APFloat V = *this;
1643 unsigned int origSign = sign;
1644
1645 assertArithmeticOK(*semantics);
1646 fs = V.divide(rhs, rmNearestTiesToEven);
1647 if (fs == opDivByZero)
1648 return fs;
1649
1650 int parts = partCount();
1651 integerPart *x = new integerPart[parts];
1652 bool ignored;
1653 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1654 rmNearestTiesToEven, &ignored);
1655 if (fs==opInvalidOp)
1656 return fs;
1657
1658 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1659 rmNearestTiesToEven);
1660 assert(fs==opOK); // should always work
1661
1662 fs = V.multiply(rhs, rmNearestTiesToEven);
1663 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1664
1665 fs = subtract(V, rmNearestTiesToEven);
1666 assert(fs==opOK || fs==opInexact); // likewise
1667
1668 if (isZero())
1669 sign = origSign; // IEEE754 requires this
1670 delete[] x;
1671 return fs;
1672}
1673
Dan Gohman16e02092010-03-24 19:38:02 +00001674/* Normalized llvm frem (C fmod).
Dale Johannesen24b66a82009-01-20 18:35:05 +00001675 This is not currently correct in all cases. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001676APFloat::opStatus
1677APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1678{
1679 opStatus fs;
Neil Boothcaf19d72007-10-14 10:29:28 +00001680 assertArithmeticOK(*semantics);
Dale Johannesened6af242009-01-21 00:35:19 +00001681 fs = modSpecials(rhs);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001682
Dale Johannesened6af242009-01-21 00:35:19 +00001683 if (category == fcNormal && rhs.category == fcNormal) {
1684 APFloat V = *this;
1685 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001686
Dale Johannesened6af242009-01-21 00:35:19 +00001687 fs = V.divide(rhs, rmNearestTiesToEven);
1688 if (fs == opDivByZero)
1689 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001690
Dale Johannesened6af242009-01-21 00:35:19 +00001691 int parts = partCount();
1692 integerPart *x = new integerPart[parts];
1693 bool ignored;
1694 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1695 rmTowardZero, &ignored);
1696 if (fs==opInvalidOp)
1697 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001698
Dale Johannesened6af242009-01-21 00:35:19 +00001699 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1700 rmNearestTiesToEven);
1701 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001702
Dale Johannesened6af242009-01-21 00:35:19 +00001703 fs = V.multiply(rhs, rounding_mode);
1704 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1705
1706 fs = subtract(V, rounding_mode);
1707 assert(fs==opOK || fs==opInexact); // likewise
1708
1709 if (isZero())
1710 sign = origSign; // IEEE754 requires this
1711 delete[] x;
1712 }
Dale Johannesene15c2db2007-08-31 23:35:31 +00001713 return fs;
1714}
1715
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001716/* Normalized fused-multiply-add. */
1717APFloat::opStatus
1718APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001719 const APFloat &addend,
1720 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001721{
1722 opStatus fs;
1723
Neil Boothcaf19d72007-10-14 10:29:28 +00001724 assertArithmeticOK(*semantics);
1725
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001726 /* Post-multiplication sign, before addition. */
1727 sign ^= multiplicand.sign;
1728
1729 /* If and only if all arguments are normal do we need to do an
1730 extended-precision calculation. */
Dan Gohman16e02092010-03-24 19:38:02 +00001731 if (category == fcNormal &&
1732 multiplicand.category == fcNormal &&
1733 addend.category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001734 lostFraction lost_fraction;
1735
1736 lost_fraction = multiplySignificand(multiplicand, &addend);
1737 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001738 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001739 fs = (opStatus) (fs | opInexact);
1740
1741 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1742 positive zero unless rounding to minus infinity, except that
1743 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001744 if (category == fcZero && sign != addend.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001745 sign = (rounding_mode == rmTowardNegative);
1746 } else {
1747 fs = multiplySpecials(multiplicand);
1748
1749 /* FS can only be opOK or opInvalidOp. There is no more work
1750 to do in the latter case. The IEEE-754R standard says it is
1751 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001752 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001753
1754 If we need to do the addition we can do so with normal
1755 precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001756 if (fs == opOK)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001757 fs = addOrSubtract(addend, rounding_mode, false);
1758 }
1759
1760 return fs;
1761}
1762
1763/* Comparison requires normalized numbers. */
1764APFloat::cmpResult
1765APFloat::compare(const APFloat &rhs) const
1766{
1767 cmpResult result;
1768
Neil Boothcaf19d72007-10-14 10:29:28 +00001769 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001770 assert(semantics == rhs.semantics);
1771
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001772 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001773 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001774 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001775
Dale Johanneseneaf08942007-08-31 04:03:46 +00001776 case convolve(fcNaN, fcZero):
1777 case convolve(fcNaN, fcNormal):
1778 case convolve(fcNaN, fcInfinity):
1779 case convolve(fcNaN, fcNaN):
1780 case convolve(fcZero, fcNaN):
1781 case convolve(fcNormal, fcNaN):
1782 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001783 return cmpUnordered;
1784
1785 case convolve(fcInfinity, fcNormal):
1786 case convolve(fcInfinity, fcZero):
1787 case convolve(fcNormal, fcZero):
Dan Gohman16e02092010-03-24 19:38:02 +00001788 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001789 return cmpLessThan;
1790 else
1791 return cmpGreaterThan;
1792
1793 case convolve(fcNormal, fcInfinity):
1794 case convolve(fcZero, fcInfinity):
1795 case convolve(fcZero, fcNormal):
Dan Gohman16e02092010-03-24 19:38:02 +00001796 if (rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001797 return cmpGreaterThan;
1798 else
1799 return cmpLessThan;
1800
1801 case convolve(fcInfinity, fcInfinity):
Dan Gohman16e02092010-03-24 19:38:02 +00001802 if (sign == rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001803 return cmpEqual;
Dan Gohman16e02092010-03-24 19:38:02 +00001804 else if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001805 return cmpLessThan;
1806 else
1807 return cmpGreaterThan;
1808
1809 case convolve(fcZero, fcZero):
1810 return cmpEqual;
1811
1812 case convolve(fcNormal, fcNormal):
1813 break;
1814 }
1815
1816 /* Two normal numbers. Do they have the same sign? */
Dan Gohman16e02092010-03-24 19:38:02 +00001817 if (sign != rhs.sign) {
1818 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001819 result = cmpLessThan;
1820 else
1821 result = cmpGreaterThan;
1822 } else {
1823 /* Compare absolute values; invert result if negative. */
1824 result = compareAbsoluteValue(rhs);
1825
Dan Gohman16e02092010-03-24 19:38:02 +00001826 if (sign) {
1827 if (result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001828 result = cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001829 else if (result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001830 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001831 }
1832 }
1833
1834 return result;
1835}
1836
Dale Johannesen23a98552008-10-09 23:00:39 +00001837/// APFloat::convert - convert a value of one floating point type to another.
1838/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1839/// records whether the transformation lost information, i.e. whether
1840/// converting the result back to the original type will produce the
1841/// original value (this is almost the same as return value==fsOK, but there
1842/// are edge cases where this is not so).
1843
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001844APFloat::opStatus
1845APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001846 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001847{
Neil Boothc8db43d2007-09-22 02:56:19 +00001848 lostFraction lostFraction;
1849 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001850 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001851
Neil Boothcaf19d72007-10-14 10:29:28 +00001852 assertArithmeticOK(*semantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001853 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001854 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001855 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001856 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001857
Neil Boothc8db43d2007-09-22 02:56:19 +00001858 /* Handle storage complications. If our new form is wider,
1859 re-allocate our bit pattern into wider storage. If it is
1860 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001861 single part we need to free the old storage.
1862 Be careful not to reference significandParts for zeroes
1863 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001864 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001865 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001866 newParts = new integerPart[newPartCount];
1867 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001868 if (category==fcNormal || category==fcNaN)
1869 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001870 freeSignificand();
1871 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001872 } else if (newPartCount < oldPartCount) {
1873 /* Capture any lost fraction through truncation of parts so we get
1874 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001875 if (category==fcNormal)
1876 lostFraction = lostFractionThroughTruncation
1877 (significandParts(), oldPartCount, toSemantics.precision);
1878 if (newPartCount == 1) {
1879 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001880 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001881 newPart = significandParts()[0];
1882 freeSignificand();
1883 significand.part = newPart;
1884 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001885 }
1886
Dan Gohman16e02092010-03-24 19:38:02 +00001887 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001888 /* Re-interpret our bit-pattern. */
1889 exponent += toSemantics.precision - semantics->precision;
1890 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001891 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001892 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001893 } else if (category == fcNaN) {
1894 int shift = toSemantics.precision - semantics->precision;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001895 // Do this now so significandParts gets the right answer
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001896 const fltSemantics *oldSemantics = semantics;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001897 semantics = &toSemantics;
Dale Johannesen23a98552008-10-09 23:00:39 +00001898 *losesInfo = false;
Dale Johannesen902ff942007-09-25 17:25:00 +00001899 // No normalization here, just truncate
1900 if (shift>0)
1901 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001902 else if (shift < 0) {
1903 unsigned ushift = -shift;
Dale Johannesen23a98552008-10-09 23:00:39 +00001904 // Figure out if we are losing information. This happens
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001905 // if are shifting out something other than 0s, or if the x87 long
1906 // double input did not have its integer bit set (pseudo-NaN), or if the
1907 // x87 long double input did not have its QNan bit set (because the x87
1908 // hardware sets this bit when converting a lower-precision NaN to
1909 // x87 long double).
1910 if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
Dale Johannesen23a98552008-10-09 23:00:39 +00001911 *losesInfo = true;
Dan Gohman16e02092010-03-24 19:38:02 +00001912 if (oldSemantics == &APFloat::x87DoubleExtended &&
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001913 (!(*significandParts() & 0x8000000000000000ULL) ||
1914 !(*significandParts() & 0x4000000000000000ULL)))
Dale Johannesen23a98552008-10-09 23:00:39 +00001915 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001916 APInt::tcShiftRight(significandParts(), newPartCount, ushift);
1917 }
Dale Johannesen902ff942007-09-25 17:25:00 +00001918 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1919 // does not give you back the same bits. This is dubious, and we
1920 // don't currently do it. You're really supposed to get
1921 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001922 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001923 } else {
1924 semantics = &toSemantics;
1925 fs = opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001926 *losesInfo = false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001927 }
1928
1929 return fs;
1930}
1931
1932/* Convert a floating point number to an integer according to the
1933 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001934 returns an invalid operation exception and the contents of the
1935 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001936 range but the floating point number is not the exact integer, the C
1937 standard doesn't require an inexact exception to be raised. IEEE
1938 854 does require it so we do that.
1939
1940 Note that for conversions to integer type the C standard requires
1941 round-to-zero to always be used. */
1942APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001943APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1944 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001945 roundingMode rounding_mode,
1946 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001947{
1948 lostFraction lost_fraction;
1949 const integerPart *src;
1950 unsigned int dstPartsCount, truncatedBits;
1951
Evan Cheng794a7db2008-11-26 01:11:57 +00001952 assertArithmeticOK(*semantics);
Neil Boothe3d936a2007-11-02 15:10:05 +00001953
Dale Johannesen23a98552008-10-09 23:00:39 +00001954 *isExact = false;
1955
Neil Boothee7ae382007-11-01 22:43:37 +00001956 /* Handle the three special cases first. */
Dan Gohman16e02092010-03-24 19:38:02 +00001957 if (category == fcInfinity || category == fcNaN)
Neil Boothee7ae382007-11-01 22:43:37 +00001958 return opInvalidOp;
1959
1960 dstPartsCount = partCountForBits(width);
1961
Dan Gohman16e02092010-03-24 19:38:02 +00001962 if (category == fcZero) {
Neil Boothee7ae382007-11-01 22:43:37 +00001963 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00001964 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00001965 *isExact = !sign;
1966 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00001967 }
1968
1969 src = significandParts();
1970
1971 /* Step 1: place our absolute value, with any fraction truncated, in
1972 the destination. */
1973 if (exponent < 0) {
1974 /* Our absolute value is less than one; truncate everything. */
1975 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen1f54f582009-01-19 21:17:05 +00001976 /* For exponent -1 the integer bit represents .5, look at that.
1977 For smaller exponents leftmost truncated bit is 0. */
1978 truncatedBits = semantics->precision -1U - exponent;
Neil Boothee7ae382007-11-01 22:43:37 +00001979 } else {
1980 /* We want the most significant (exponent + 1) bits; the rest are
1981 truncated. */
1982 unsigned int bits = exponent + 1U;
1983
1984 /* Hopelessly large in magnitude? */
1985 if (bits > width)
1986 return opInvalidOp;
1987
1988 if (bits < semantics->precision) {
1989 /* We truncate (semantics->precision - bits) bits. */
1990 truncatedBits = semantics->precision - bits;
1991 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1992 } else {
1993 /* We want at least as many bits as are available. */
1994 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
1995 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
1996 truncatedBits = 0;
1997 }
1998 }
1999
2000 /* Step 2: work out any lost fraction, and increment the absolute
2001 value if we would round away from zero. */
2002 if (truncatedBits) {
2003 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2004 truncatedBits);
Dan Gohman16e02092010-03-24 19:38:02 +00002005 if (lost_fraction != lfExactlyZero &&
2006 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Boothee7ae382007-11-01 22:43:37 +00002007 if (APInt::tcIncrement(parts, dstPartsCount))
2008 return opInvalidOp; /* Overflow. */
2009 }
2010 } else {
2011 lost_fraction = lfExactlyZero;
2012 }
2013
2014 /* Step 3: check if we fit in the destination. */
2015 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2016
2017 if (sign) {
2018 if (!isSigned) {
2019 /* Negative numbers cannot be represented as unsigned. */
2020 if (omsb != 0)
2021 return opInvalidOp;
2022 } else {
2023 /* It takes omsb bits to represent the unsigned integer value.
2024 We lose a bit for the sign, but care is needed as the
2025 maximally negative integer is a special case. */
2026 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2027 return opInvalidOp;
2028
2029 /* This case can happen because of rounding. */
2030 if (omsb > width)
2031 return opInvalidOp;
2032 }
2033
2034 APInt::tcNegate (parts, dstPartsCount);
2035 } else {
2036 if (omsb >= width + !isSigned)
2037 return opInvalidOp;
2038 }
2039
Dale Johannesen23a98552008-10-09 23:00:39 +00002040 if (lost_fraction == lfExactlyZero) {
2041 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00002042 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00002043 } else
Neil Boothee7ae382007-11-01 22:43:37 +00002044 return opInexact;
2045}
2046
2047/* Same as convertToSignExtendedInteger, except we provide
2048 deterministic values in case of an invalid operation exception,
2049 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00002050 for underflow or overflow.
2051 The *isExact output tells whether the result is exact, in the sense
2052 that converting it back to the original floating point type produces
2053 the original value. This is almost equivalent to result==opOK,
2054 except for negative zeroes.
2055*/
Neil Boothee7ae382007-11-01 22:43:37 +00002056APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002057APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00002058 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00002059 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002060{
Neil Boothee7ae382007-11-01 22:43:37 +00002061 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002062
Dan Gohman16e02092010-03-24 19:38:02 +00002063 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen23a98552008-10-09 23:00:39 +00002064 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002065
Neil Boothee7ae382007-11-01 22:43:37 +00002066 if (fs == opInvalidOp) {
2067 unsigned int bits, dstPartsCount;
2068
2069 dstPartsCount = partCountForBits(width);
2070
2071 if (category == fcNaN)
2072 bits = 0;
2073 else if (sign)
2074 bits = isSigned;
2075 else
2076 bits = width - isSigned;
2077
2078 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2079 if (sign && isSigned)
2080 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002081 }
2082
Neil Boothee7ae382007-11-01 22:43:37 +00002083 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002084}
2085
Neil Booth643ce592007-10-07 12:07:53 +00002086/* Convert an unsigned integer SRC to a floating point number,
2087 rounding according to ROUNDING_MODE. The sign of the floating
2088 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002089APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00002090APFloat::convertFromUnsignedParts(const integerPart *src,
2091 unsigned int srcCount,
2092 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002093{
Neil Booth5477f852007-10-08 14:39:42 +00002094 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00002095 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00002096 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002097
Neil Boothcaf19d72007-10-14 10:29:28 +00002098 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002099 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00002100 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00002101 dst = significandParts();
2102 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00002103 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00002104
Neil Booth5477f852007-10-08 14:39:42 +00002105 /* We want the most significant PRECISON bits of SRC. There may not
2106 be that many; extract what we can. */
2107 if (precision <= omsb) {
2108 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00002109 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00002110 omsb - precision);
2111 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2112 } else {
2113 exponent = precision - 1;
2114 lost_fraction = lfExactlyZero;
2115 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00002116 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002117
2118 return normalize(rounding_mode, lost_fraction);
2119}
2120
Dan Gohman93c276e2008-02-29 01:26:11 +00002121APFloat::opStatus
2122APFloat::convertFromAPInt(const APInt &Val,
2123 bool isSigned,
2124 roundingMode rounding_mode)
2125{
2126 unsigned int partCount = Val.getNumWords();
2127 APInt api = Val;
2128
2129 sign = false;
2130 if (isSigned && api.isNegative()) {
2131 sign = true;
2132 api = -api;
2133 }
2134
2135 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2136}
2137
Neil Boothf16c5952007-10-07 12:15:41 +00002138/* Convert a two's complement integer SRC to a floating point number,
2139 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2140 integer is signed, in which case it must be sign-extended. */
2141APFloat::opStatus
2142APFloat::convertFromSignExtendedInteger(const integerPart *src,
2143 unsigned int srcCount,
2144 bool isSigned,
2145 roundingMode rounding_mode)
2146{
2147 opStatus status;
2148
Neil Boothcaf19d72007-10-14 10:29:28 +00002149 assertArithmeticOK(*semantics);
Dan Gohman16e02092010-03-24 19:38:02 +00002150 if (isSigned &&
2151 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Neil Boothf16c5952007-10-07 12:15:41 +00002152 integerPart *copy;
2153
2154 /* If we're signed and negative negate a copy. */
2155 sign = true;
2156 copy = new integerPart[srcCount];
2157 APInt::tcAssign(copy, src, srcCount);
2158 APInt::tcNegate(copy, srcCount);
2159 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2160 delete [] copy;
2161 } else {
2162 sign = false;
2163 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2164 }
2165
2166 return status;
2167}
2168
Neil Boothccf596a2007-10-07 11:45:55 +00002169/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002170APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002171APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2172 unsigned int width, bool isSigned,
2173 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002174{
Dale Johannesen910993e2007-09-21 22:09:37 +00002175 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00002176 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002177
2178 sign = false;
Dan Gohman16e02092010-03-24 19:38:02 +00002179 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesencce23a42007-09-30 18:17:01 +00002180 sign = true;
2181 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002182 }
2183
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002184 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002185}
2186
2187APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002188APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002189{
Erick Tryzelaarf8bc8012009-08-18 18:20:37 +00002190 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002191 integerPart *significand;
2192 unsigned int bitPos, partsCount;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002193 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002194
2195 zeroSignificand();
2196 exponent = 0;
2197 category = fcNormal;
2198
2199 significand = significandParts();
2200 partsCount = partCount();
2201 bitPos = partsCount * integerPartWidth;
2202
Neil Booth33d4c922007-10-07 08:51:21 +00002203 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002204 StringRef::iterator begin = s.begin();
2205 StringRef::iterator end = s.end();
2206 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002207 firstSignificantDigit = p;
2208
Dan Gohman16e02092010-03-24 19:38:02 +00002209 for (; p != end;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002210 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002211
Dan Gohman16e02092010-03-24 19:38:02 +00002212 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002213 assert(dot == end && "String contains multiple dots");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002214 dot = p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002215 if (p == end) {
2216 break;
2217 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002218 }
2219
2220 hex_value = hexDigitValue(*p);
Dan Gohman16e02092010-03-24 19:38:02 +00002221 if (hex_value == -1U) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002222 break;
2223 }
2224
2225 p++;
2226
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002227 if (p == end) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002228 break;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002229 } else {
2230 /* Store the number whilst 4-bit nibbles remain. */
Dan Gohman16e02092010-03-24 19:38:02 +00002231 if (bitPos) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002232 bitPos -= 4;
2233 hex_value <<= bitPos % integerPartWidth;
2234 significand[bitPos / integerPartWidth] |= hex_value;
2235 } else {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002236 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
Dan Gohman16e02092010-03-24 19:38:02 +00002237 while (p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002238 p++;
2239 break;
2240 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002241 }
2242 }
2243
2244 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002245 assert(p != end && "Hex strings require an exponent");
2246 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2247 assert(p != begin && "Significand has no digits");
2248 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002249
2250 /* Ignore the exponent if we are zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00002251 if (p != firstSignificantDigit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002252 int expAdjustment;
2253
2254 /* Implicit hexadecimal point? */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002255 if (dot == end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002256 dot = p;
2257
2258 /* Calculate the exponent adjustment implicit in the number of
2259 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002260 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohman16e02092010-03-24 19:38:02 +00002261 if (expAdjustment < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002262 expAdjustment++;
2263 expAdjustment = expAdjustment * 4 - 1;
2264
2265 /* Adjust for writing the significand starting at the most
2266 significant nibble. */
2267 expAdjustment += semantics->precision;
2268 expAdjustment -= partsCount * integerPartWidth;
2269
2270 /* Adjust for the given exponent. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002271 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002272 }
2273
2274 return normalize(rounding_mode, lost_fraction);
2275}
2276
2277APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002278APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2279 unsigned sigPartCount, int exp,
2280 roundingMode rounding_mode)
2281{
2282 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002283 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002284 integerPart pow5Parts[maxPowerOfFiveParts];
2285 bool isNearest;
2286
Dan Gohman16e02092010-03-24 19:38:02 +00002287 isNearest = (rounding_mode == rmNearestTiesToEven ||
2288 rounding_mode == rmNearestTiesToAway);
Neil Booth96c74712007-10-12 16:02:31 +00002289
2290 parts = partCountForBits(semantics->precision + 11);
2291
2292 /* Calculate pow(5, abs(exp)). */
2293 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2294
2295 for (;; parts *= 2) {
2296 opStatus sigStatus, powStatus;
2297 unsigned int excessPrecision, truncatedBits;
2298
2299 calcSemantics.precision = parts * integerPartWidth - 1;
2300 excessPrecision = calcSemantics.precision - semantics->precision;
2301 truncatedBits = excessPrecision;
2302
2303 APFloat decSig(calcSemantics, fcZero, sign);
2304 APFloat pow5(calcSemantics, fcZero, false);
2305
2306 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2307 rmNearestTiesToEven);
2308 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2309 rmNearestTiesToEven);
2310 /* Add exp, as 10^n = 5^n * 2^n. */
2311 decSig.exponent += exp;
2312
2313 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002314 integerPart HUerr, HUdistance;
2315 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002316
2317 if (exp >= 0) {
2318 /* multiplySignificand leaves the precision-th bit set to 1. */
2319 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2320 powHUerr = powStatus != opOK;
2321 } else {
2322 calcLostFraction = decSig.divideSignificand(pow5);
2323 /* Denormal numbers have less precision. */
2324 if (decSig.exponent < semantics->minExponent) {
2325 excessPrecision += (semantics->minExponent - decSig.exponent);
2326 truncatedBits = excessPrecision;
2327 if (excessPrecision > calcSemantics.precision)
2328 excessPrecision = calcSemantics.precision;
2329 }
2330 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002331 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002332 }
2333
2334 /* Both multiplySignificand and divideSignificand return the
2335 result with the integer bit set. */
Evan Cheng99ebfa52009-10-27 21:35:42 +00002336 assert(APInt::tcExtractBit
2337 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Booth96c74712007-10-12 16:02:31 +00002338
2339 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2340 powHUerr);
2341 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2342 excessPrecision, isNearest);
2343
2344 /* Are we guaranteed to round correctly if we truncate? */
2345 if (HUdistance >= HUerr) {
2346 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2347 calcSemantics.precision - excessPrecision,
2348 excessPrecision);
2349 /* Take the exponent of decSig. If we tcExtract-ed less bits
2350 above we must adjust our exponent to compensate for the
2351 implicit right shift. */
2352 exponent = (decSig.exponent + semantics->precision
2353 - (calcSemantics.precision - excessPrecision));
2354 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2355 decSig.partCount(),
2356 truncatedBits);
2357 return normalize(rounding_mode, calcLostFraction);
2358 }
2359 }
2360}
2361
2362APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002363APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Booth96c74712007-10-12 16:02:31 +00002364{
Neil Booth1870f292007-10-14 10:16:12 +00002365 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002366 opStatus fs;
2367
Neil Booth1870f292007-10-14 10:16:12 +00002368 /* Scan the text. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002369 StringRef::iterator p = str.begin();
2370 interpretDecimal(p, str.end(), &D);
Neil Booth96c74712007-10-12 16:02:31 +00002371
Neil Booth686700e2007-10-15 15:00:55 +00002372 /* Handle the quick cases. First the case of no significant digits,
2373 i.e. zero, and then exponents that are obviously too large or too
2374 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2375 definitely overflows if
2376
2377 (exp - 1) * L >= maxExponent
2378
2379 and definitely underflows to zero where
2380
2381 (exp + 1) * L <= minExponent - precision
2382
2383 With integer arithmetic the tightest bounds for L are
2384
2385 93/28 < L < 196/59 [ numerator <= 256 ]
2386 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2387 */
2388
Neil Boothcc233592007-12-05 13:06:04 +00002389 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002390 category = fcZero;
2391 fs = opOK;
John McCall8b3f3302010-02-26 22:20:41 +00002392
2393 /* Check whether the normalized exponent is high enough to overflow
2394 max during the log-rebasing in the max-exponent check below. */
2395 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2396 fs = handleOverflow(rounding_mode);
2397
2398 /* If it wasn't, then it also wasn't high enough to overflow max
2399 during the log-rebasing in the min-exponent check. Check that it
2400 won't overflow min in either check, then perform the min-exponent
2401 check. */
2402 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2403 (D.normalizedExponent + 1) * 28738 <=
2404 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth686700e2007-10-15 15:00:55 +00002405 /* Underflow to zero and round. */
2406 zeroSignificand();
2407 fs = normalize(rounding_mode, lfLessThanHalf);
John McCall8b3f3302010-02-26 22:20:41 +00002408
2409 /* We can finally safely perform the max-exponent check. */
Neil Booth686700e2007-10-15 15:00:55 +00002410 } else if ((D.normalizedExponent - 1) * 42039
2411 >= 12655 * semantics->maxExponent) {
2412 /* Overflow and round. */
2413 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002414 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002415 integerPart *decSignificand;
2416 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002417
Neil Booth1870f292007-10-14 10:16:12 +00002418 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002419 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002420 to hold the full significand, and an extra part required by
2421 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002422 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002423 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002424 decSignificand = new integerPart[partCount + 1];
2425 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002426
Neil Booth1870f292007-10-14 10:16:12 +00002427 /* Convert to binary efficiently - we do almost all multiplication
2428 in an integerPart. When this would overflow do we do a single
2429 bignum multiplication, and then revert again to multiplication
2430 in an integerPart. */
2431 do {
2432 integerPart decValue, val, multiplier;
2433
2434 val = 0;
2435 multiplier = 1;
2436
2437 do {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002438 if (*p == '.') {
Neil Booth1870f292007-10-14 10:16:12 +00002439 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002440 if (p == str.end()) {
2441 break;
2442 }
2443 }
Neil Booth1870f292007-10-14 10:16:12 +00002444 decValue = decDigitValue(*p++);
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002445 assert(decValue < 10U && "Invalid character in significand");
Neil Booth1870f292007-10-14 10:16:12 +00002446 multiplier *= 10;
2447 val = val * 10 + decValue;
2448 /* The maximum number that can be multiplied by ten with any
2449 digit added without overflowing an integerPart. */
2450 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2451
2452 /* Multiply out the current part. */
2453 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2454 partCount, partCount + 1, false);
2455
2456 /* If we used another part (likely but not guaranteed), increase
2457 the count. */
2458 if (decSignificand[partCount])
2459 partCount++;
2460 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002461
Neil Booth43a4b282007-11-01 22:51:07 +00002462 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002463 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002464 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002465
Neil Booth1870f292007-10-14 10:16:12 +00002466 delete [] decSignificand;
2467 }
Neil Booth96c74712007-10-12 16:02:31 +00002468
2469 return fs;
2470}
2471
2472APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002473APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth4f881702007-09-26 21:33:42 +00002474{
Neil Boothcaf19d72007-10-14 10:29:28 +00002475 assertArithmeticOK(*semantics);
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002476 assert(!str.empty() && "Invalid string length");
Neil Boothcaf19d72007-10-14 10:29:28 +00002477
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002478 /* Handle a leading minus sign. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002479 StringRef::iterator p = str.begin();
2480 size_t slen = str.size();
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002481 sign = *p == '-' ? 1 : 0;
Dan Gohman16e02092010-03-24 19:38:02 +00002482 if (*p == '-' || *p == '+') {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002483 p++;
2484 slen--;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002485 assert(slen && "String has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002486 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002487
Dan Gohman16e02092010-03-24 19:38:02 +00002488 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002489 assert(slen - 2 && "Invalid string");
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002490 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002491 rounding_mode);
2492 }
Bill Wendlingb7c0d942008-11-27 08:00:12 +00002493
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002494 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002495}
Dale Johannesen343e7702007-08-24 00:56:33 +00002496
Neil Bootha30b0ee2007-10-03 22:26:02 +00002497/* Write out a hexadecimal representation of the floating point value
2498 to DST, which must be of sufficient size, in the C99 form
2499 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2500 excluding the terminating NUL.
2501
2502 If UPPERCASE, the output is in upper case, otherwise in lower case.
2503
2504 HEXDIGITS digits appear altogether, rounding the value if
2505 necessary. If HEXDIGITS is 0, the minimal precision to display the
2506 number precisely is used instead. If nothing would appear after
2507 the decimal point it is suppressed.
2508
2509 The decimal exponent is always printed and has at least one digit.
2510 Zero values display an exponent of zero. Infinities and NaNs
2511 appear as "infinity" or "nan" respectively.
2512
2513 The above rules are as specified by C99. There is ambiguity about
2514 what the leading hexadecimal digit should be. This implementation
2515 uses whatever is necessary so that the exponent is displayed as
2516 stored. This implies the exponent will fall within the IEEE format
2517 range, and the leading hexadecimal digit will be 0 (for denormals),
2518 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2519 any other digits zero).
2520*/
2521unsigned int
2522APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2523 bool upperCase, roundingMode rounding_mode) const
2524{
2525 char *p;
2526
Neil Boothcaf19d72007-10-14 10:29:28 +00002527 assertArithmeticOK(*semantics);
2528
Neil Bootha30b0ee2007-10-03 22:26:02 +00002529 p = dst;
2530 if (sign)
2531 *dst++ = '-';
2532
2533 switch (category) {
2534 case fcInfinity:
2535 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2536 dst += sizeof infinityL - 1;
2537 break;
2538
2539 case fcNaN:
2540 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2541 dst += sizeof NaNU - 1;
2542 break;
2543
2544 case fcZero:
2545 *dst++ = '0';
2546 *dst++ = upperCase ? 'X': 'x';
2547 *dst++ = '0';
2548 if (hexDigits > 1) {
2549 *dst++ = '.';
2550 memset (dst, '0', hexDigits - 1);
2551 dst += hexDigits - 1;
2552 }
2553 *dst++ = upperCase ? 'P': 'p';
2554 *dst++ = '0';
2555 break;
2556
2557 case fcNormal:
2558 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2559 break;
2560 }
2561
2562 *dst = 0;
2563
Evan Cheng48e8c802008-05-02 21:15:08 +00002564 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002565}
2566
2567/* Does the hard work of outputting the correctly rounded hexadecimal
2568 form of a normal floating point number with the specified number of
2569 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2570 digits necessary to print the value precisely is output. */
2571char *
2572APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2573 bool upperCase,
2574 roundingMode rounding_mode) const
2575{
2576 unsigned int count, valueBits, shift, partsCount, outputDigits;
2577 const char *hexDigitChars;
2578 const integerPart *significand;
2579 char *p;
2580 bool roundUp;
2581
2582 *dst++ = '0';
2583 *dst++ = upperCase ? 'X': 'x';
2584
2585 roundUp = false;
2586 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2587
2588 significand = significandParts();
2589 partsCount = partCount();
2590
2591 /* +3 because the first digit only uses the single integer bit, so
2592 we have 3 virtual zero most-significant-bits. */
2593 valueBits = semantics->precision + 3;
2594 shift = integerPartWidth - valueBits % integerPartWidth;
2595
2596 /* The natural number of digits required ignoring trailing
2597 insignificant zeroes. */
2598 outputDigits = (valueBits - significandLSB () + 3) / 4;
2599
2600 /* hexDigits of zero means use the required number for the
2601 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002602 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002603 if (hexDigits) {
2604 if (hexDigits < outputDigits) {
2605 /* We are dropping non-zero bits, so need to check how to round.
2606 "bits" is the number of dropped bits. */
2607 unsigned int bits;
2608 lostFraction fraction;
2609
2610 bits = valueBits - hexDigits * 4;
2611 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2612 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2613 }
2614 outputDigits = hexDigits;
2615 }
2616
2617 /* Write the digits consecutively, and start writing in the location
2618 of the hexadecimal point. We move the most significant digit
2619 left and add the hexadecimal point later. */
2620 p = ++dst;
2621
2622 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2623
2624 while (outputDigits && count) {
2625 integerPart part;
2626
2627 /* Put the most significant integerPartWidth bits in "part". */
2628 if (--count == partsCount)
2629 part = 0; /* An imaginary higher zero part. */
2630 else
2631 part = significand[count] << shift;
2632
2633 if (count && shift)
2634 part |= significand[count - 1] >> (integerPartWidth - shift);
2635
2636 /* Convert as much of "part" to hexdigits as we can. */
2637 unsigned int curDigits = integerPartWidth / 4;
2638
2639 if (curDigits > outputDigits)
2640 curDigits = outputDigits;
2641 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2642 outputDigits -= curDigits;
2643 }
2644
2645 if (roundUp) {
2646 char *q = dst;
2647
2648 /* Note that hexDigitChars has a trailing '0'. */
2649 do {
2650 q--;
2651 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002652 } while (*q == '0');
Evan Cheng99ebfa52009-10-27 21:35:42 +00002653 assert(q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002654 } else {
2655 /* Add trailing zeroes. */
2656 memset (dst, '0', outputDigits);
2657 dst += outputDigits;
2658 }
2659
2660 /* Move the most significant digit to before the point, and if there
2661 is something after the decimal point add it. This must come
2662 after rounding above. */
2663 p[-1] = p[0];
2664 if (dst -1 == p)
2665 dst--;
2666 else
2667 p[0] = '.';
2668
2669 /* Finally output the exponent. */
2670 *dst++ = upperCase ? 'P': 'p';
2671
Neil Booth92f7e8d2007-10-06 07:29:25 +00002672 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002673}
2674
Dale Johannesen343e7702007-08-24 00:56:33 +00002675// For good performance it is desirable for different APFloats
2676// to produce different integers.
2677uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00002678APFloat::getHashValue() const
2679{
Dale Johannesen343e7702007-08-24 00:56:33 +00002680 if (category==fcZero) return sign<<8 | semantics->precision ;
2681 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002682 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00002683 else {
2684 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2685 const integerPart* p = significandParts();
2686 for (int i=partCount(); i>0; i--, p++)
Evan Cheng48e8c802008-05-02 21:15:08 +00002687 hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
Dale Johannesen343e7702007-08-24 00:56:33 +00002688 return hash;
2689 }
2690}
2691
2692// Conversion from APFloat to/from host float/double. It may eventually be
2693// possible to eliminate these and have everybody deal with APFloats, but that
2694// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002695// Current implementation requires integerPartWidth==64, which is correct at
2696// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002697
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002698// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002699// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002700
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002701APInt
Neil Booth4f881702007-09-26 21:33:42 +00002702APFloat::convertF80LongDoubleAPFloatToAPInt() const
2703{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002704 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002705 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002706
2707 uint64_t myexponent, mysignificand;
2708
2709 if (category==fcNormal) {
2710 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002711 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002712 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2713 myexponent = 0; // denormal
2714 } else if (category==fcZero) {
2715 myexponent = 0;
2716 mysignificand = 0;
2717 } else if (category==fcInfinity) {
2718 myexponent = 0x7fff;
2719 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002720 } else {
2721 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002722 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002723 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002724 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002725
2726 uint64_t words[2];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002727 words[0] = mysignificand;
2728 words[1] = ((uint64_t)(sign & 1) << 15) |
2729 (myexponent & 0x7fffLL);
Chris Lattnera11ef822007-10-06 06:13:42 +00002730 return APInt(80, 2, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002731}
2732
2733APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002734APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2735{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002736 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002737 assert(partCount()==2);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002738
2739 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2740
2741 if (category==fcNormal) {
2742 myexponent = exponent + 1023; //bias
2743 myexponent2 = exponent2 + 1023;
2744 mysignificand = significandParts()[0];
2745 mysignificand2 = significandParts()[1];
2746 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2747 myexponent = 0; // denormal
2748 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2749 myexponent2 = 0; // denormal
2750 } else if (category==fcZero) {
2751 myexponent = 0;
2752 mysignificand = 0;
2753 myexponent2 = 0;
2754 mysignificand2 = 0;
2755 } else if (category==fcInfinity) {
2756 myexponent = 0x7ff;
2757 myexponent2 = 0;
2758 mysignificand = 0;
2759 mysignificand2 = 0;
2760 } else {
2761 assert(category == fcNaN && "Unknown category");
2762 myexponent = 0x7ff;
2763 mysignificand = significandParts()[0];
2764 myexponent2 = exponent2;
2765 mysignificand2 = significandParts()[1];
2766 }
2767
2768 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002769 words[0] = ((uint64_t)(sign & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002770 ((myexponent & 0x7ff) << 52) |
2771 (mysignificand & 0xfffffffffffffLL);
Evan Cheng48e8c802008-05-02 21:15:08 +00002772 words[1] = ((uint64_t)(sign2 & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002773 ((myexponent2 & 0x7ff) << 52) |
2774 (mysignificand2 & 0xfffffffffffffLL);
2775 return APInt(128, 2, words);
2776}
2777
2778APInt
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002779APFloat::convertQuadrupleAPFloatToAPInt() const
2780{
2781 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002782 assert(partCount()==2);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002783
2784 uint64_t myexponent, mysignificand, mysignificand2;
2785
2786 if (category==fcNormal) {
2787 myexponent = exponent+16383; //bias
2788 mysignificand = significandParts()[0];
2789 mysignificand2 = significandParts()[1];
2790 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2791 myexponent = 0; // denormal
2792 } else if (category==fcZero) {
2793 myexponent = 0;
2794 mysignificand = mysignificand2 = 0;
2795 } else if (category==fcInfinity) {
2796 myexponent = 0x7fff;
2797 mysignificand = mysignificand2 = 0;
2798 } else {
2799 assert(category == fcNaN && "Unknown category!");
2800 myexponent = 0x7fff;
2801 mysignificand = significandParts()[0];
2802 mysignificand2 = significandParts()[1];
2803 }
2804
2805 uint64_t words[2];
2806 words[0] = mysignificand;
2807 words[1] = ((uint64_t)(sign & 1) << 63) |
2808 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov4755e992009-08-21 23:09:47 +00002809 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002810
2811 return APInt(128, 2, words);
2812}
2813
2814APInt
Neil Booth4f881702007-09-26 21:33:42 +00002815APFloat::convertDoubleAPFloatToAPInt() const
2816{
Dan Gohmancb648f92007-09-14 20:08:19 +00002817 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002818 assert(partCount()==1);
Dale Johannesen343e7702007-08-24 00:56:33 +00002819
Dale Johanneseneaf08942007-08-31 04:03:46 +00002820 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002821
2822 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002823 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002824 mysignificand = *significandParts();
2825 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2826 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002827 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002828 myexponent = 0;
2829 mysignificand = 0;
2830 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002831 myexponent = 0x7ff;
2832 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002833 } else {
2834 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002835 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002836 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002837 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002838
Evan Cheng48e8c802008-05-02 21:15:08 +00002839 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002840 ((myexponent & 0x7ff) << 52) |
2841 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002842}
2843
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002844APInt
Neil Booth4f881702007-09-26 21:33:42 +00002845APFloat::convertFloatAPFloatToAPInt() const
2846{
Dan Gohmancb648f92007-09-14 20:08:19 +00002847 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002848 assert(partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002849
Dale Johanneseneaf08942007-08-31 04:03:46 +00002850 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002851
2852 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002853 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002854 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002855 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002856 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002857 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002858 myexponent = 0;
2859 mysignificand = 0;
2860 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002861 myexponent = 0xff;
2862 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002863 } else {
2864 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002865 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002866 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002867 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002868
Chris Lattnera11ef822007-10-06 06:13:42 +00002869 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2870 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002871}
2872
Chris Lattnercc4287a2009-10-16 02:13:51 +00002873APInt
2874APFloat::convertHalfAPFloatToAPInt() const
2875{
2876 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002877 assert(partCount()==1);
Chris Lattnercc4287a2009-10-16 02:13:51 +00002878
2879 uint32_t myexponent, mysignificand;
2880
2881 if (category==fcNormal) {
2882 myexponent = exponent+15; //bias
2883 mysignificand = (uint32_t)*significandParts();
2884 if (myexponent == 1 && !(mysignificand & 0x400))
2885 myexponent = 0; // denormal
2886 } else if (category==fcZero) {
2887 myexponent = 0;
2888 mysignificand = 0;
2889 } else if (category==fcInfinity) {
Dale Johannesena223aed2009-10-23 04:02:51 +00002890 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002891 mysignificand = 0;
2892 } else {
2893 assert(category == fcNaN && "Unknown category!");
Dale Johannesena223aed2009-10-23 04:02:51 +00002894 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002895 mysignificand = (uint32_t)*significandParts();
2896 }
2897
2898 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2899 (mysignificand & 0x3ff)));
2900}
2901
Dale Johannesena471c2e2007-10-11 18:07:22 +00002902// This function creates an APInt that is just a bit map of the floating
2903// point constant as it would appear in memory. It is not a conversion,
2904// and treating the result as a normal integer is unlikely to be useful.
2905
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002906APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002907APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002908{
Chris Lattnercc4287a2009-10-16 02:13:51 +00002909 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2910 return convertHalfAPFloatToAPInt();
2911
Dan Gohmanb10abe12008-01-29 12:08:20 +00002912 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002913 return convertFloatAPFloatToAPInt();
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002914
Dan Gohmanb10abe12008-01-29 12:08:20 +00002915 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002916 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002917
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002918 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2919 return convertQuadrupleAPFloatToAPInt();
2920
Dan Gohmanb10abe12008-01-29 12:08:20 +00002921 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002922 return convertPPCDoubleDoubleAPFloatToAPInt();
2923
Dan Gohmanb10abe12008-01-29 12:08:20 +00002924 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002925 "unknown format!");
2926 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002927}
2928
Neil Booth4f881702007-09-26 21:33:42 +00002929float
2930APFloat::convertToFloat() const
2931{
Chris Lattnerad785002009-09-24 21:44:20 +00002932 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2933 "Float semantics are not IEEEsingle");
Dale Johannesen7111b022008-10-09 18:53:47 +00002934 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002935 return api.bitsToFloat();
2936}
2937
Neil Booth4f881702007-09-26 21:33:42 +00002938double
2939APFloat::convertToDouble() const
2940{
Chris Lattnerad785002009-09-24 21:44:20 +00002941 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2942 "Float semantics are not IEEEdouble");
Dale Johannesen7111b022008-10-09 18:53:47 +00002943 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002944 return api.bitsToDouble();
2945}
2946
Dale Johannesend3d8ce32008-10-06 18:22:29 +00002947/// Integer bit is explicit in this format. Intel hardware (387 and later)
2948/// does not support these bit patterns:
2949/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2950/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2951/// exponent = 0, integer bit 1 ("pseudodenormal")
2952/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2953/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002954void
Neil Booth4f881702007-09-26 21:33:42 +00002955APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2956{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002957 assert(api.getBitWidth()==80);
2958 uint64_t i1 = api.getRawData()[0];
2959 uint64_t i2 = api.getRawData()[1];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002960 uint64_t myexponent = (i2 & 0x7fff);
2961 uint64_t mysignificand = i1;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002962
2963 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002964 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002965
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002966 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002967 if (myexponent==0 && mysignificand==0) {
2968 // exponent, significand meaningless
2969 category = fcZero;
2970 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2971 // exponent, significand meaningless
2972 category = fcInfinity;
2973 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2974 // exponent meaningless
2975 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002976 significandParts()[0] = mysignificand;
2977 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002978 } else {
2979 category = fcNormal;
2980 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002981 significandParts()[0] = mysignificand;
2982 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002983 if (myexponent==0) // denormal
2984 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00002985 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002986}
2987
2988void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002989APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2990{
2991 assert(api.getBitWidth()==128);
2992 uint64_t i1 = api.getRawData()[0];
2993 uint64_t i2 = api.getRawData()[1];
2994 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2995 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2996 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2997 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2998
2999 initialize(&APFloat::PPCDoubleDouble);
3000 assert(partCount()==2);
3001
Evan Cheng48e8c802008-05-02 21:15:08 +00003002 sign = static_cast<unsigned int>(i1>>63);
3003 sign2 = static_cast<unsigned int>(i2>>63);
Dale Johannesena471c2e2007-10-11 18:07:22 +00003004 if (myexponent==0 && mysignificand==0) {
3005 // exponent, significand meaningless
3006 // exponent2 and significand2 are required to be 0; we don't check
3007 category = fcZero;
3008 } else if (myexponent==0x7ff && mysignificand==0) {
3009 // exponent, significand meaningless
3010 // exponent2 and significand2 are required to be 0; we don't check
3011 category = fcInfinity;
3012 } else if (myexponent==0x7ff && mysignificand!=0) {
Dan Gohman16e02092010-03-24 19:38:02 +00003013 // exponent meaningless. So is the whole second word, but keep it
Dale Johannesena471c2e2007-10-11 18:07:22 +00003014 // for determinism.
3015 category = fcNaN;
3016 exponent2 = myexponent2;
3017 significandParts()[0] = mysignificand;
3018 significandParts()[1] = mysignificand2;
3019 } else {
3020 category = fcNormal;
3021 // Note there is no category2; the second word is treated as if it is
3022 // fcNormal, although it might be something else considered by itself.
3023 exponent = myexponent - 1023;
3024 exponent2 = myexponent2 - 1023;
3025 significandParts()[0] = mysignificand;
3026 significandParts()[1] = mysignificand2;
3027 if (myexponent==0) // denormal
3028 exponent = -1022;
3029 else
3030 significandParts()[0] |= 0x10000000000000LL; // integer bit
Dan Gohman16e02092010-03-24 19:38:02 +00003031 if (myexponent2==0)
Dale Johannesena471c2e2007-10-11 18:07:22 +00003032 exponent2 = -1022;
3033 else
3034 significandParts()[1] |= 0x10000000000000LL; // integer bit
3035 }
3036}
3037
3038void
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003039APFloat::initFromQuadrupleAPInt(const APInt &api)
3040{
3041 assert(api.getBitWidth()==128);
3042 uint64_t i1 = api.getRawData()[0];
3043 uint64_t i2 = api.getRawData()[1];
3044 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3045 uint64_t mysignificand = i1;
3046 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3047
3048 initialize(&APFloat::IEEEquad);
3049 assert(partCount()==2);
3050
3051 sign = static_cast<unsigned int>(i2>>63);
3052 if (myexponent==0 &&
3053 (mysignificand==0 && mysignificand2==0)) {
3054 // exponent, significand meaningless
3055 category = fcZero;
3056 } else if (myexponent==0x7fff &&
3057 (mysignificand==0 && mysignificand2==0)) {
3058 // exponent, significand meaningless
3059 category = fcInfinity;
3060 } else if (myexponent==0x7fff &&
3061 (mysignificand!=0 || mysignificand2 !=0)) {
3062 // exponent meaningless
3063 category = fcNaN;
3064 significandParts()[0] = mysignificand;
3065 significandParts()[1] = mysignificand2;
3066 } else {
3067 category = fcNormal;
3068 exponent = myexponent - 16383;
3069 significandParts()[0] = mysignificand;
3070 significandParts()[1] = mysignificand2;
3071 if (myexponent==0) // denormal
3072 exponent = -16382;
3073 else
3074 significandParts()[1] |= 0x1000000000000LL; // integer bit
3075 }
3076}
3077
3078void
Neil Booth4f881702007-09-26 21:33:42 +00003079APFloat::initFromDoubleAPInt(const APInt &api)
3080{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003081 assert(api.getBitWidth()==64);
3082 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003083 uint64_t myexponent = (i >> 52) & 0x7ff;
3084 uint64_t mysignificand = i & 0xfffffffffffffLL;
3085
Dale Johannesen343e7702007-08-24 00:56:33 +00003086 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00003087 assert(partCount()==1);
3088
Evan Cheng48e8c802008-05-02 21:15:08 +00003089 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00003090 if (myexponent==0 && mysignificand==0) {
3091 // exponent, significand meaningless
3092 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003093 } else if (myexponent==0x7ff && mysignificand==0) {
3094 // exponent, significand meaningless
3095 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00003096 } else if (myexponent==0x7ff && mysignificand!=0) {
3097 // exponent meaningless
3098 category = fcNaN;
3099 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003100 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00003101 category = fcNormal;
3102 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003103 *significandParts() = mysignificand;
3104 if (myexponent==0) // denormal
3105 exponent = -1022;
3106 else
3107 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00003108 }
Dale Johannesen343e7702007-08-24 00:56:33 +00003109}
3110
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003111void
Neil Booth4f881702007-09-26 21:33:42 +00003112APFloat::initFromFloatAPInt(const APInt & api)
3113{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003114 assert(api.getBitWidth()==32);
3115 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003116 uint32_t myexponent = (i >> 23) & 0xff;
3117 uint32_t mysignificand = i & 0x7fffff;
3118
Dale Johannesen343e7702007-08-24 00:56:33 +00003119 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00003120 assert(partCount()==1);
3121
Dale Johanneseneaf08942007-08-31 04:03:46 +00003122 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00003123 if (myexponent==0 && mysignificand==0) {
3124 // exponent, significand meaningless
3125 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003126 } else if (myexponent==0xff && mysignificand==0) {
3127 // exponent, significand meaningless
3128 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00003129 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00003130 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00003131 category = fcNaN;
3132 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003133 } else {
3134 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00003135 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003136 *significandParts() = mysignificand;
3137 if (myexponent==0) // denormal
3138 exponent = -126;
3139 else
3140 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00003141 }
3142}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003143
Chris Lattnercc4287a2009-10-16 02:13:51 +00003144void
3145APFloat::initFromHalfAPInt(const APInt & api)
3146{
3147 assert(api.getBitWidth()==16);
3148 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesena223aed2009-10-23 04:02:51 +00003149 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00003150 uint32_t mysignificand = i & 0x3ff;
3151
3152 initialize(&APFloat::IEEEhalf);
3153 assert(partCount()==1);
3154
3155 sign = i >> 15;
3156 if (myexponent==0 && mysignificand==0) {
3157 // exponent, significand meaningless
3158 category = fcZero;
3159 } else if (myexponent==0x1f && mysignificand==0) {
3160 // exponent, significand meaningless
3161 category = fcInfinity;
3162 } else if (myexponent==0x1f && mysignificand!=0) {
3163 // sign, exponent, significand meaningless
3164 category = fcNaN;
3165 *significandParts() = mysignificand;
3166 } else {
3167 category = fcNormal;
3168 exponent = myexponent - 15; //bias
3169 *significandParts() = mysignificand;
3170 if (myexponent==0) // denormal
3171 exponent = -14;
3172 else
3173 *significandParts() |= 0x400; // integer bit
3174 }
3175}
3176
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003177/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00003178/// we infer the floating point type from the size of the APInt. The
3179/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3180/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003181void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003182APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003183{
Chris Lattnercc4287a2009-10-16 02:13:51 +00003184 if (api.getBitWidth() == 16)
3185 return initFromHalfAPInt(api);
3186 else if (api.getBitWidth() == 32)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003187 return initFromFloatAPInt(api);
3188 else if (api.getBitWidth()==64)
3189 return initFromDoubleAPInt(api);
3190 else if (api.getBitWidth()==80)
3191 return initFromF80LongDoubleAPInt(api);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003192 else if (api.getBitWidth()==128)
3193 return (isIEEE ?
3194 initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003195 else
Torok Edwinc23197a2009-07-14 16:55:14 +00003196 llvm_unreachable(0);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003197}
3198
John McCall00e65de2009-12-24 08:56:26 +00003199APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3200 APFloat Val(Sem, fcNormal, Negative);
3201
3202 // We want (in interchange format):
3203 // sign = {Negative}
3204 // exponent = 1..10
3205 // significand = 1..1
3206
3207 Val.exponent = Sem.maxExponent; // unbiased
3208
3209 // 1-initialize all bits....
3210 Val.zeroSignificand();
3211 integerPart *significand = Val.significandParts();
3212 unsigned N = partCountForBits(Sem.precision);
3213 for (unsigned i = 0; i != N; ++i)
3214 significand[i] = ~((integerPart) 0);
3215
3216 // ...and then clear the top bits for internal consistency.
Dan Gohman16e02092010-03-24 19:38:02 +00003217 significand[N-1] &=
3218 (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1)) - 1;
John McCall00e65de2009-12-24 08:56:26 +00003219
3220 return Val;
3221}
3222
3223APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3224 APFloat Val(Sem, fcNormal, Negative);
3225
3226 // We want (in interchange format):
3227 // sign = {Negative}
3228 // exponent = 0..0
3229 // significand = 0..01
3230
3231 Val.exponent = Sem.minExponent; // unbiased
3232 Val.zeroSignificand();
3233 Val.significandParts()[0] = 1;
3234 return Val;
3235}
3236
3237APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3238 APFloat Val(Sem, fcNormal, Negative);
3239
3240 // We want (in interchange format):
3241 // sign = {Negative}
3242 // exponent = 0..0
3243 // significand = 10..0
3244
3245 Val.exponent = Sem.minExponent;
3246 Val.zeroSignificand();
Dan Gohman16e02092010-03-24 19:38:02 +00003247 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
3248 (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1));
John McCall00e65de2009-12-24 08:56:26 +00003249
3250 return Val;
3251}
3252
Dale Johannesena471c2e2007-10-11 18:07:22 +00003253APFloat::APFloat(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003254{
Dale Johannesena471c2e2007-10-11 18:07:22 +00003255 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003256}
3257
Neil Booth4f881702007-09-26 21:33:42 +00003258APFloat::APFloat(float f)
3259{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003260 APInt api = APInt(32, 0);
3261 initFromAPInt(api.floatToBits(f));
3262}
3263
Neil Booth4f881702007-09-26 21:33:42 +00003264APFloat::APFloat(double d)
3265{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003266 APInt api = APInt(64, 0);
3267 initFromAPInt(api.doubleToBits(d));
3268}
John McCall00e65de2009-12-24 08:56:26 +00003269
3270namespace {
3271 static void append(SmallVectorImpl<char> &Buffer,
3272 unsigned N, const char *Str) {
3273 unsigned Start = Buffer.size();
3274 Buffer.set_size(Start + N);
3275 memcpy(&Buffer[Start], Str, N);
3276 }
3277
3278 template <unsigned N>
3279 void append(SmallVectorImpl<char> &Buffer, const char (&Str)[N]) {
3280 append(Buffer, N, Str);
3281 }
3282
John McCall003a09c2009-12-24 12:16:56 +00003283 /// Removes data from the given significand until it is no more
3284 /// precise than is required for the desired precision.
3285 void AdjustToPrecision(APInt &significand,
3286 int &exp, unsigned FormatPrecision) {
3287 unsigned bits = significand.getActiveBits();
3288
3289 // 196/59 is a very slight overestimate of lg_2(10).
3290 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3291
3292 if (bits <= bitsRequired) return;
3293
3294 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3295 if (!tensRemovable) return;
3296
3297 exp += tensRemovable;
3298
3299 APInt divisor(significand.getBitWidth(), 1);
3300 APInt powten(significand.getBitWidth(), 10);
3301 while (true) {
3302 if (tensRemovable & 1)
3303 divisor *= powten;
3304 tensRemovable >>= 1;
3305 if (!tensRemovable) break;
3306 powten *= powten;
3307 }
3308
3309 significand = significand.udiv(divisor);
3310
3311 // Truncate the significand down to its active bit count, but
3312 // don't try to drop below 32.
John McCall6a09aff2009-12-24 23:18:09 +00003313 unsigned newPrecision = std::max(32U, significand.getActiveBits());
John McCall003a09c2009-12-24 12:16:56 +00003314 significand.trunc(newPrecision);
3315 }
3316
3317
John McCall00e65de2009-12-24 08:56:26 +00003318 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3319 int &exp, unsigned FormatPrecision) {
3320 unsigned N = buffer.size();
3321 if (N <= FormatPrecision) return;
3322
3323 // The most significant figures are the last ones in the buffer.
3324 unsigned FirstSignificant = N - FormatPrecision;
3325
3326 // Round.
3327 // FIXME: this probably shouldn't use 'round half up'.
3328
3329 // Rounding down is just a truncation, except we also want to drop
3330 // trailing zeros from the new result.
3331 if (buffer[FirstSignificant - 1] < '5') {
3332 while (buffer[FirstSignificant] == '0')
3333 FirstSignificant++;
3334
3335 exp += FirstSignificant;
3336 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3337 return;
3338 }
3339
3340 // Rounding up requires a decimal add-with-carry. If we continue
3341 // the carry, the newly-introduced zeros will just be truncated.
3342 for (unsigned I = FirstSignificant; I != N; ++I) {
3343 if (buffer[I] == '9') {
3344 FirstSignificant++;
3345 } else {
3346 buffer[I]++;
3347 break;
3348 }
3349 }
3350
3351 // If we carried through, we have exactly one digit of precision.
3352 if (FirstSignificant == N) {
3353 exp += FirstSignificant;
3354 buffer.clear();
3355 buffer.push_back('1');
3356 return;
3357 }
3358
3359 exp += FirstSignificant;
3360 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3361 }
3362}
3363
3364void APFloat::toString(SmallVectorImpl<char> &Str,
3365 unsigned FormatPrecision,
Chris Lattner0ddda3b2010-03-06 19:20:13 +00003366 unsigned FormatMaxPadding) const {
John McCall00e65de2009-12-24 08:56:26 +00003367 switch (category) {
3368 case fcInfinity:
3369 if (isNegative())
3370 return append(Str, "-Inf");
3371 else
3372 return append(Str, "+Inf");
3373
3374 case fcNaN: return append(Str, "NaN");
3375
3376 case fcZero:
3377 if (isNegative())
3378 Str.push_back('-');
3379
3380 if (!FormatMaxPadding)
3381 append(Str, "0.0E+0");
3382 else
3383 Str.push_back('0');
3384 return;
3385
3386 case fcNormal:
3387 break;
3388 }
3389
3390 if (isNegative())
3391 Str.push_back('-');
3392
3393 // Decompose the number into an APInt and an exponent.
3394 int exp = exponent - ((int) semantics->precision - 1);
3395 APInt significand(semantics->precision,
3396 partCountForBits(semantics->precision),
3397 significandParts());
3398
John McCall6a09aff2009-12-24 23:18:09 +00003399 // Set FormatPrecision if zero. We want to do this before we
3400 // truncate trailing zeros, as those are part of the precision.
3401 if (!FormatPrecision) {
3402 // It's an interesting question whether to use the nominal
3403 // precision or the active precision here for denormals.
3404
3405 // FormatPrecision = ceil(significandBits / lg_2(10))
3406 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3407 }
3408
John McCall00e65de2009-12-24 08:56:26 +00003409 // Ignore trailing binary zeros.
3410 int trailingZeros = significand.countTrailingZeros();
3411 exp += trailingZeros;
3412 significand = significand.lshr(trailingZeros);
3413
3414 // Change the exponent from 2^e to 10^e.
3415 if (exp == 0) {
3416 // Nothing to do.
3417 } else if (exp > 0) {
3418 // Just shift left.
3419 significand.zext(semantics->precision + exp);
3420 significand <<= exp;
3421 exp = 0;
3422 } else { /* exp < 0 */
3423 int texp = -exp;
3424
3425 // We transform this using the identity:
3426 // (N)(2^-e) == (N)(5^e)(10^-e)
3427 // This means we have to multiply N (the significand) by 5^e.
3428 // To avoid overflow, we have to operate on numbers large
3429 // enough to store N * 5^e:
3430 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCall6a09aff2009-12-24 23:18:09 +00003431 // <= semantics->precision + e * 137 / 59
3432 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohman16e02092010-03-24 19:38:02 +00003433
John McCall6a09aff2009-12-24 23:18:09 +00003434 unsigned precision = semantics->precision + 137 * texp / 59;
John McCall00e65de2009-12-24 08:56:26 +00003435
3436 // Multiply significand by 5^e.
3437 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
3438 significand.zext(precision);
3439 APInt five_to_the_i(precision, 5);
3440 while (true) {
3441 if (texp & 1) significand *= five_to_the_i;
Dan Gohman16e02092010-03-24 19:38:02 +00003442
John McCall00e65de2009-12-24 08:56:26 +00003443 texp >>= 1;
3444 if (!texp) break;
3445 five_to_the_i *= five_to_the_i;
3446 }
3447 }
3448
John McCall003a09c2009-12-24 12:16:56 +00003449 AdjustToPrecision(significand, exp, FormatPrecision);
3450
John McCall00e65de2009-12-24 08:56:26 +00003451 llvm::SmallVector<char, 256> buffer;
3452
3453 // Fill the buffer.
3454 unsigned precision = significand.getBitWidth();
3455 APInt ten(precision, 10);
3456 APInt digit(precision, 0);
3457
3458 bool inTrail = true;
3459 while (significand != 0) {
3460 // digit <- significand % 10
3461 // significand <- significand / 10
3462 APInt::udivrem(significand, ten, significand, digit);
3463
3464 unsigned d = digit.getZExtValue();
3465
3466 // Drop trailing zeros.
3467 if (inTrail && !d) exp++;
3468 else {
3469 buffer.push_back((char) ('0' + d));
3470 inTrail = false;
3471 }
3472 }
3473
3474 assert(!buffer.empty() && "no characters in buffer!");
3475
3476 // Drop down to FormatPrecision.
3477 // TODO: don't do more precise calculations above than are required.
3478 AdjustToPrecision(buffer, exp, FormatPrecision);
3479
3480 unsigned NDigits = buffer.size();
3481
John McCall6a09aff2009-12-24 23:18:09 +00003482 // Check whether we should use scientific notation.
John McCall00e65de2009-12-24 08:56:26 +00003483 bool FormatScientific;
3484 if (!FormatMaxPadding)
3485 FormatScientific = true;
3486 else {
John McCall00e65de2009-12-24 08:56:26 +00003487 if (exp >= 0) {
John McCall6a09aff2009-12-24 23:18:09 +00003488 // 765e3 --> 765000
3489 // ^^^
3490 // But we shouldn't make the number look more precise than it is.
3491 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3492 NDigits + (unsigned) exp > FormatPrecision);
John McCall00e65de2009-12-24 08:56:26 +00003493 } else {
John McCall6a09aff2009-12-24 23:18:09 +00003494 // Power of the most significant digit.
3495 int MSD = exp + (int) (NDigits - 1);
3496 if (MSD >= 0) {
John McCall00e65de2009-12-24 08:56:26 +00003497 // 765e-2 == 7.65
John McCall6a09aff2009-12-24 23:18:09 +00003498 FormatScientific = false;
John McCall00e65de2009-12-24 08:56:26 +00003499 } else {
3500 // 765e-5 == 0.00765
3501 // ^ ^^
John McCall6a09aff2009-12-24 23:18:09 +00003502 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall00e65de2009-12-24 08:56:26 +00003503 }
3504 }
John McCall00e65de2009-12-24 08:56:26 +00003505 }
3506
3507 // Scientific formatting is pretty straightforward.
3508 if (FormatScientific) {
3509 exp += (NDigits - 1);
3510
3511 Str.push_back(buffer[NDigits-1]);
3512 Str.push_back('.');
3513 if (NDigits == 1)
3514 Str.push_back('0');
3515 else
3516 for (unsigned I = 1; I != NDigits; ++I)
3517 Str.push_back(buffer[NDigits-1-I]);
3518 Str.push_back('E');
3519
3520 Str.push_back(exp >= 0 ? '+' : '-');
3521 if (exp < 0) exp = -exp;
3522 SmallVector<char, 6> expbuf;
3523 do {
3524 expbuf.push_back((char) ('0' + (exp % 10)));
3525 exp /= 10;
3526 } while (exp);
3527 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3528 Str.push_back(expbuf[E-1-I]);
3529 return;
3530 }
3531
3532 // Non-scientific, positive exponents.
3533 if (exp >= 0) {
3534 for (unsigned I = 0; I != NDigits; ++I)
3535 Str.push_back(buffer[NDigits-1-I]);
3536 for (unsigned I = 0; I != (unsigned) exp; ++I)
3537 Str.push_back('0');
3538 return;
3539 }
3540
3541 // Non-scientific, negative exponents.
3542
3543 // The number of digits to the left of the decimal point.
3544 int NWholeDigits = exp + (int) NDigits;
3545
3546 unsigned I = 0;
3547 if (NWholeDigits > 0) {
3548 for (; I != (unsigned) NWholeDigits; ++I)
3549 Str.push_back(buffer[NDigits-I-1]);
3550 Str.push_back('.');
3551 } else {
3552 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3553
3554 Str.push_back('0');
3555 Str.push_back('.');
3556 for (unsigned Z = 1; Z != NZeros; ++Z)
3557 Str.push_back('0');
3558 }
3559
3560 for (; I != NDigits; ++I)
3561 Str.push_back(buffer[NDigits-I-1]);
3562}