blob: f90973feab8f2cbca7939adef12aa19d3f573769 [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
Neil Booth96c74712007-10-12 16:02:31 +000068
69 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';
103 if(r <= 9)
104 return r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000105
Chris Lattnere213f3f2009-03-12 23:59:55 +0000106 r = c - 'A';
107 if(r <= 5)
108 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000109
Chris Lattnere213f3f2009-03-12 23:59:55 +0000110 r = c - 'a';
111 if(r <= 5)
112 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) {
119 assert(semantics.arithmeticOK
120 && "Compile-time arithmetic does not support these semantics");
121}
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 == '-';
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +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;
Erick Tryzelaara15d8902009-08-16 23:36:19 +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;
196 if(unsignedExponent > 65535)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000197 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000198 }
199
Chris Lattnere213f3f2009-03-12 23:59:55 +0000200 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
201 overflow = true;
202
203 if(!overflow) {
204 exponent = unsignedExponent;
205 if(negative)
206 exponent = -exponent;
207 exponent += exponentAdjustment;
208 if(exponent > 65535 || exponent < -65536)
209 overflow = true;
210 }
211
212 if(overflow)
213 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;
224 while(*p == '0' && p != end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000225 p++;
226
227 if(*p == '.') {
228 *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
232 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. */
326 if(digitValue > 8)
327 return lfMoreThanHalf;
328 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. */
332 while(*p == '0')
333 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. */
341 if(hexDigit == -1U)
342 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. */
359 if(bits <= lsb)
360 return lfExactlyZero;
361 if(bits == lsb + 1)
362 return lfExactlyHalf;
363 if(bits <= partCount * integerPartWidth
364 && APInt::tcExtractBit(parts, bits - 1))
365 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{
388 if(lessSignificant != lfExactlyZero) {
389 if(moreSignificant == lfExactlyZero)
390 moreSignificant = lfLessThanHalf;
391 else if(moreSignificant == lfExactlyHalf)
392 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;
471
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();
591 if(count > 1)
592 significand.parts = new integerPart[count];
593}
594
595void
596APFloat::freeSignificand()
597{
598 if(partCount() > 1)
599 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;
Dale Johanneseneaf08942007-08-31 04:03:46 +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). */
Neil Boothe5e01942007-10-14 10:39:51 +0000629void
Mike Stumpc5ca7132009-05-30 03:49:43 +0000630APFloat::makeNaN(unsigned type)
Neil Boothe5e01942007-10-14 10:39:51 +0000631{
632 category = fcNaN;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000633 // FIXME: Add double and long double support for QNaN(0).
634 if (semantics->precision == 24 && semantics->maxExponent == 127) {
635 type |= 0x7fc00000U;
636 type &= ~0x80000000U;
637 } else
638 type = ~0U;
639 APInt::tcSet(significandParts(), type, partCount());
Neil Boothe5e01942007-10-14 10:39:51 +0000640}
641
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000642APFloat &
643APFloat::operator=(const APFloat &rhs)
644{
645 if(this != &rhs) {
646 if(semantics != rhs.semantics) {
647 freeSignificand();
648 initialize(rhs.semantics);
649 }
650 assign(rhs);
651 }
652
653 return *this;
654}
655
Dale Johannesen343e7702007-08-24 00:56:33 +0000656bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000657APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000658 if (this == &rhs)
659 return true;
660 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000661 category != rhs.category ||
662 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000663 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000664 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000665 sign2 != rhs.sign2)
666 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000667 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000668 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000669 else if (category==fcNormal && exponent!=rhs.exponent)
670 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000671 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000672 exponent2!=rhs.exponent2)
673 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000674 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000675 int i= partCount();
676 const integerPart* p=significandParts();
677 const integerPart* q=rhs.significandParts();
678 for (; i>0; i--, p++, q++) {
679 if (*p != *q)
680 return false;
681 }
682 return true;
683 }
684}
685
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000686APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
687{
Neil Boothcaf19d72007-10-14 10:29:28 +0000688 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000689 initialize(&ourSemantics);
690 sign = 0;
691 zeroSignificand();
692 exponent = ourSemantics.precision - 1;
693 significandParts()[0] = value;
694 normalize(rmNearestTiesToEven, lfExactlyZero);
695}
696
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000697APFloat::APFloat(const fltSemantics &ourSemantics) {
698 assertArithmeticOK(ourSemantics);
699 initialize(&ourSemantics);
700 category = fcZero;
701 sign = false;
702}
703
704
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000705APFloat::APFloat(const fltSemantics &ourSemantics,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000706 fltCategory ourCategory, bool negative, unsigned type)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000707{
Neil Boothcaf19d72007-10-14 10:29:28 +0000708 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000709 initialize(&ourSemantics);
710 category = ourCategory;
711 sign = negative;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000712 if (category == fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000713 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000714 else if (ourCategory == fcNaN)
Mike Stumpc5ca7132009-05-30 03:49:43 +0000715 makeNaN(type);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000716}
717
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000718APFloat::APFloat(const fltSemantics &ourSemantics, const StringRef& text)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000719{
Neil Boothcaf19d72007-10-14 10:29:28 +0000720 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000721 initialize(&ourSemantics);
722 convertFromString(text, rmNearestTiesToEven);
723}
724
725APFloat::APFloat(const APFloat &rhs)
726{
727 initialize(rhs.semantics);
728 assign(rhs);
729}
730
731APFloat::~APFloat()
732{
733 freeSignificand();
734}
735
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000736// Profile - This method 'profiles' an APFloat for use with FoldingSet.
737void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000738 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000739}
740
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000741unsigned int
742APFloat::partCount() const
743{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000744 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000745}
746
747unsigned int
748APFloat::semanticsPrecision(const fltSemantics &semantics)
749{
750 return semantics.precision;
751}
752
753const integerPart *
754APFloat::significandParts() const
755{
756 return const_cast<APFloat *>(this)->significandParts();
757}
758
759integerPart *
760APFloat::significandParts()
761{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000762 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000763
Evan Cheng99ebfa52009-10-27 21:35:42 +0000764 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000765 return significand.parts;
766 else
767 return &significand.part;
768}
769
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000770void
771APFloat::zeroSignificand()
772{
773 category = fcNormal;
774 APInt::tcSet(significandParts(), 0, partCount());
775}
776
777/* Increment an fcNormal floating point number's significand. */
778void
779APFloat::incrementSignificand()
780{
781 integerPart carry;
782
783 carry = APInt::tcIncrement(significandParts(), partCount());
784
785 /* Our callers should never cause us to overflow. */
786 assert(carry == 0);
787}
788
789/* Add the significand of the RHS. Returns the carry flag. */
790integerPart
791APFloat::addSignificand(const APFloat &rhs)
792{
793 integerPart *parts;
794
795 parts = significandParts();
796
797 assert(semantics == rhs.semantics);
798 assert(exponent == rhs.exponent);
799
800 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
801}
802
803/* Subtract the significand of the RHS with a borrow flag. Returns
804 the borrow flag. */
805integerPart
806APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
807{
808 integerPart *parts;
809
810 parts = significandParts();
811
812 assert(semantics == rhs.semantics);
813 assert(exponent == rhs.exponent);
814
815 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000816 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000817}
818
819/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
820 on to the full-precision result of the multiplication. Returns the
821 lost fraction. */
822lostFraction
823APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
824{
Neil Booth4f881702007-09-26 21:33:42 +0000825 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000826 unsigned int partsCount, newPartsCount, precision;
827 integerPart *lhsSignificand;
828 integerPart scratch[4];
829 integerPart *fullSignificand;
830 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000831 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000832
833 assert(semantics == rhs.semantics);
834
835 precision = semantics->precision;
836 newPartsCount = partCountForBits(precision * 2);
837
838 if(newPartsCount > 4)
839 fullSignificand = new integerPart[newPartsCount];
840 else
841 fullSignificand = scratch;
842
843 lhsSignificand = significandParts();
844 partsCount = partCount();
845
846 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000847 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000848
849 lost_fraction = lfExactlyZero;
850 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
851 exponent += rhs.exponent;
852
853 if(addend) {
854 Significand savedSignificand = significand;
855 const fltSemantics *savedSemantics = semantics;
856 fltSemantics extendedSemantics;
857 opStatus status;
858 unsigned int extendedPrecision;
859
860 /* Normalize our MSB. */
861 extendedPrecision = precision + precision - 1;
862 if(omsb != extendedPrecision)
863 {
Neil Booth4f881702007-09-26 21:33:42 +0000864 APInt::tcShiftLeft(fullSignificand, newPartsCount,
865 extendedPrecision - omsb);
866 exponent -= extendedPrecision - omsb;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000867 }
868
869 /* Create new semantics. */
870 extendedSemantics = *semantics;
871 extendedSemantics.precision = extendedPrecision;
872
873 if(newPartsCount == 1)
874 significand.part = fullSignificand[0];
875 else
876 significand.parts = fullSignificand;
877 semantics = &extendedSemantics;
878
879 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000880 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000881 assert(status == opOK);
882 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
883
884 /* Restore our state. */
885 if(newPartsCount == 1)
886 fullSignificand[0] = significand.part;
887 significand = savedSignificand;
888 semantics = savedSemantics;
889
890 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
891 }
892
893 exponent -= (precision - 1);
894
895 if(omsb > precision) {
896 unsigned int bits, significantParts;
897 lostFraction lf;
898
899 bits = omsb - precision;
900 significantParts = partCountForBits(omsb);
901 lf = shiftRight(fullSignificand, significantParts, bits);
902 lost_fraction = combineLostFractions(lf, lost_fraction);
903 exponent += bits;
904 }
905
906 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
907
908 if(newPartsCount > 4)
909 delete [] fullSignificand;
910
911 return lost_fraction;
912}
913
914/* Multiply the significands of LHS and RHS to DST. */
915lostFraction
916APFloat::divideSignificand(const APFloat &rhs)
917{
918 unsigned int bit, i, partsCount;
919 const integerPart *rhsSignificand;
920 integerPart *lhsSignificand, *dividend, *divisor;
921 integerPart scratch[4];
922 lostFraction lost_fraction;
923
924 assert(semantics == rhs.semantics);
925
926 lhsSignificand = significandParts();
927 rhsSignificand = rhs.significandParts();
928 partsCount = partCount();
929
930 if(partsCount > 2)
931 dividend = new integerPart[partsCount * 2];
932 else
933 dividend = scratch;
934
935 divisor = dividend + partsCount;
936
937 /* Copy the dividend and divisor as they will be modified in-place. */
938 for(i = 0; i < partsCount; i++) {
939 dividend[i] = lhsSignificand[i];
940 divisor[i] = rhsSignificand[i];
941 lhsSignificand[i] = 0;
942 }
943
944 exponent -= rhs.exponent;
945
946 unsigned int precision = semantics->precision;
947
948 /* Normalize the divisor. */
949 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
950 if(bit) {
951 exponent += bit;
952 APInt::tcShiftLeft(divisor, partsCount, bit);
953 }
954
955 /* Normalize the dividend. */
956 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
957 if(bit) {
958 exponent -= bit;
959 APInt::tcShiftLeft(dividend, partsCount, bit);
960 }
961
Neil Booth96c74712007-10-12 16:02:31 +0000962 /* Ensure the dividend >= divisor initially for the loop below.
963 Incidentally, this means that the division loop below is
964 guaranteed to set the integer bit to one. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000965 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
966 exponent--;
967 APInt::tcShiftLeft(dividend, partsCount, 1);
968 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
969 }
970
971 /* Long division. */
972 for(bit = precision; bit; bit -= 1) {
973 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
974 APInt::tcSubtract(dividend, divisor, 0, partsCount);
975 APInt::tcSetBit(lhsSignificand, bit - 1);
976 }
977
978 APInt::tcShiftLeft(dividend, partsCount, 1);
979 }
980
981 /* Figure out the lost fraction. */
982 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
983
984 if(cmp > 0)
985 lost_fraction = lfMoreThanHalf;
986 else if(cmp == 0)
987 lost_fraction = lfExactlyHalf;
988 else if(APInt::tcIsZero(dividend, partsCount))
989 lost_fraction = lfExactlyZero;
990 else
991 lost_fraction = lfLessThanHalf;
992
993 if(partsCount > 2)
994 delete [] dividend;
995
996 return lost_fraction;
997}
998
999unsigned int
1000APFloat::significandMSB() const
1001{
1002 return APInt::tcMSB(significandParts(), partCount());
1003}
1004
1005unsigned int
1006APFloat::significandLSB() const
1007{
1008 return APInt::tcLSB(significandParts(), partCount());
1009}
1010
1011/* Note that a zero result is NOT normalized to fcZero. */
1012lostFraction
1013APFloat::shiftSignificandRight(unsigned int bits)
1014{
1015 /* Our exponent should not overflow. */
1016 assert((exponent_t) (exponent + bits) >= exponent);
1017
1018 exponent += bits;
1019
1020 return shiftRight(significandParts(), partCount(), bits);
1021}
1022
1023/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1024void
1025APFloat::shiftSignificandLeft(unsigned int bits)
1026{
1027 assert(bits < semantics->precision);
1028
1029 if(bits) {
1030 unsigned int partsCount = partCount();
1031
1032 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1033 exponent -= bits;
1034
1035 assert(!APInt::tcIsZero(significandParts(), partsCount));
1036 }
1037}
1038
1039APFloat::cmpResult
1040APFloat::compareAbsoluteValue(const APFloat &rhs) const
1041{
1042 int compare;
1043
1044 assert(semantics == rhs.semantics);
1045 assert(category == fcNormal);
1046 assert(rhs.category == fcNormal);
1047
1048 compare = exponent - rhs.exponent;
1049
1050 /* If exponents are equal, do an unsigned bignum comparison of the
1051 significands. */
1052 if(compare == 0)
1053 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001054 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001055
1056 if(compare > 0)
1057 return cmpGreaterThan;
1058 else if(compare < 0)
1059 return cmpLessThan;
1060 else
1061 return cmpEqual;
1062}
1063
1064/* Handle overflow. Sign is preserved. We either become infinity or
1065 the largest finite number. */
1066APFloat::opStatus
1067APFloat::handleOverflow(roundingMode rounding_mode)
1068{
1069 /* Infinity? */
1070 if(rounding_mode == rmNearestTiesToEven
1071 || rounding_mode == rmNearestTiesToAway
1072 || (rounding_mode == rmTowardPositive && !sign)
1073 || (rounding_mode == rmTowardNegative && sign))
1074 {
1075 category = fcInfinity;
1076 return (opStatus) (opOverflow | opInexact);
1077 }
1078
1079 /* Otherwise we become the largest finite number. */
1080 category = fcNormal;
1081 exponent = semantics->maxExponent;
1082 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001083 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001084
1085 return opInexact;
1086}
1087
Neil Boothb7dea4c2007-10-03 15:16:41 +00001088/* Returns TRUE if, when truncating the current number, with BIT the
1089 new LSB, with the given lost fraction and rounding mode, the result
1090 would need to be rounded away from zero (i.e., by increasing the
1091 signficand). This routine must work for fcZero of both signs, and
1092 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001093bool
1094APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001095 lostFraction lost_fraction,
1096 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001097{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001098 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001099 assert(category == fcNormal || category == fcZero);
1100
Neil Boothb7dea4c2007-10-03 15:16:41 +00001101 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001102 assert(lost_fraction != lfExactlyZero);
1103
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001104 switch (rounding_mode) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001105 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001106 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001107
1108 case rmNearestTiesToAway:
1109 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1110
1111 case rmNearestTiesToEven:
1112 if(lost_fraction == lfMoreThanHalf)
1113 return true;
1114
1115 /* Our zeroes don't have a significand to test. */
1116 if(lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001117 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001118
1119 return false;
1120
1121 case rmTowardZero:
1122 return false;
1123
1124 case rmTowardPositive:
1125 return sign == false;
1126
1127 case rmTowardNegative:
1128 return sign == true;
1129 }
1130}
1131
1132APFloat::opStatus
1133APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001134 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001135{
Neil Booth4f881702007-09-26 21:33:42 +00001136 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001137 int exponentChange;
1138
1139 if(category != fcNormal)
1140 return opOK;
1141
1142 /* Before rounding normalize the exponent of fcNormal numbers. */
1143 omsb = significandMSB() + 1;
1144
1145 if(omsb) {
1146 /* OMSB is numbered from 1. We want to place it in the integer
1147 bit numbered PRECISON if possible, with a compensating change in
1148 the exponent. */
1149 exponentChange = omsb - semantics->precision;
1150
1151 /* If the resulting exponent is too high, overflow according to
1152 the rounding mode. */
1153 if(exponent + exponentChange > semantics->maxExponent)
1154 return handleOverflow(rounding_mode);
1155
1156 /* Subnormal numbers have exponent minExponent, and their MSB
1157 is forced based on that. */
1158 if(exponent + exponentChange < semantics->minExponent)
1159 exponentChange = semantics->minExponent - exponent;
1160
1161 /* Shifting left is easy as we don't lose precision. */
1162 if(exponentChange < 0) {
1163 assert(lost_fraction == lfExactlyZero);
1164
1165 shiftSignificandLeft(-exponentChange);
1166
1167 return opOK;
1168 }
1169
1170 if(exponentChange > 0) {
1171 lostFraction lf;
1172
1173 /* Shift right and capture any new lost fraction. */
1174 lf = shiftSignificandRight(exponentChange);
1175
1176 lost_fraction = combineLostFractions(lf, lost_fraction);
1177
1178 /* Keep OMSB up-to-date. */
1179 if(omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001180 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001181 else
Neil Booth4f881702007-09-26 21:33:42 +00001182 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001183 }
1184 }
1185
1186 /* Now round the number according to rounding_mode given the lost
1187 fraction. */
1188
1189 /* As specified in IEEE 754, since we do not trap we do not report
1190 underflow for exact results. */
1191 if(lost_fraction == lfExactlyZero) {
1192 /* Canonicalize zeroes. */
1193 if(omsb == 0)
1194 category = fcZero;
1195
1196 return opOK;
1197 }
1198
1199 /* Increment the significand if we're rounding away from zero. */
Neil Boothb7dea4c2007-10-03 15:16:41 +00001200 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001201 if(omsb == 0)
1202 exponent = semantics->minExponent;
1203
1204 incrementSignificand();
1205 omsb = significandMSB() + 1;
1206
1207 /* Did the significand increment overflow? */
1208 if(omsb == (unsigned) semantics->precision + 1) {
1209 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001210 significand right one. However if we already have the
1211 maximum exponent we overflow to infinity. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001212 if(exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001213 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001214
Neil Booth4f881702007-09-26 21:33:42 +00001215 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001216 }
1217
1218 shiftSignificandRight(1);
1219
1220 return opInexact;
1221 }
1222 }
1223
1224 /* The normal case - we were and are not denormal, and any
1225 significand increment above didn't overflow. */
1226 if(omsb == semantics->precision)
1227 return opInexact;
1228
1229 /* We have a non-zero denormal. */
1230 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001231
1232 /* Canonicalize zeroes. */
1233 if(omsb == 0)
1234 category = fcZero;
1235
1236 /* The fcZero case is a denormal that underflowed to zero. */
1237 return (opStatus) (opUnderflow | opInexact);
1238}
1239
1240APFloat::opStatus
1241APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1242{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001243 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001244 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001245 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001246
Dale Johanneseneaf08942007-08-31 04:03:46 +00001247 case convolve(fcNaN, fcZero):
1248 case convolve(fcNaN, fcNormal):
1249 case convolve(fcNaN, fcInfinity):
1250 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001251 case convolve(fcNormal, fcZero):
1252 case convolve(fcInfinity, fcNormal):
1253 case convolve(fcInfinity, fcZero):
1254 return opOK;
1255
Dale Johanneseneaf08942007-08-31 04:03:46 +00001256 case convolve(fcZero, fcNaN):
1257 case convolve(fcNormal, fcNaN):
1258 case convolve(fcInfinity, fcNaN):
1259 category = fcNaN;
1260 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001261 return opOK;
1262
1263 case convolve(fcNormal, fcInfinity):
1264 case convolve(fcZero, fcInfinity):
1265 category = fcInfinity;
1266 sign = rhs.sign ^ subtract;
1267 return opOK;
1268
1269 case convolve(fcZero, fcNormal):
1270 assign(rhs);
1271 sign = rhs.sign ^ subtract;
1272 return opOK;
1273
1274 case convolve(fcZero, fcZero):
1275 /* Sign depends on rounding mode; handled by caller. */
1276 return opOK;
1277
1278 case convolve(fcInfinity, fcInfinity):
1279 /* Differently signed infinities can only be validly
1280 subtracted. */
Cedric Venetaff9c272009-02-14 16:06:42 +00001281 if(((sign ^ rhs.sign)!=0) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001282 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001283 return opInvalidOp;
1284 }
1285
1286 return opOK;
1287
1288 case convolve(fcNormal, fcNormal):
1289 return opDivByZero;
1290 }
1291}
1292
1293/* Add or subtract two normal numbers. */
1294lostFraction
1295APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1296{
1297 integerPart carry;
1298 lostFraction lost_fraction;
1299 int bits;
1300
1301 /* Determine if the operation on the absolute values is effectively
1302 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001303 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001304
1305 /* Are we bigger exponent-wise than the RHS? */
1306 bits = exponent - rhs.exponent;
1307
1308 /* Subtraction is more subtle than one might naively expect. */
1309 if(subtract) {
1310 APFloat temp_rhs(rhs);
1311 bool reverse;
1312
Chris Lattnerada530b2007-08-24 03:02:34 +00001313 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001314 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1315 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001316 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001317 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1318 shiftSignificandLeft(1);
1319 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001320 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001321 lost_fraction = shiftSignificandRight(-bits - 1);
1322 temp_rhs.shiftSignificandLeft(1);
1323 reverse = true;
1324 }
1325
Chris Lattnerada530b2007-08-24 03:02:34 +00001326 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001327 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001328 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001329 copySignificand(temp_rhs);
1330 sign = !sign;
1331 } else {
1332 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001333 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001334 }
1335
1336 /* Invert the lost fraction - it was on the RHS and
1337 subtracted. */
1338 if(lost_fraction == lfLessThanHalf)
1339 lost_fraction = lfMoreThanHalf;
1340 else if(lost_fraction == lfMoreThanHalf)
1341 lost_fraction = lfLessThanHalf;
1342
1343 /* The code above is intended to ensure that no borrow is
1344 necessary. */
1345 assert(!carry);
1346 } else {
1347 if(bits > 0) {
1348 APFloat temp_rhs(rhs);
1349
1350 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1351 carry = addSignificand(temp_rhs);
1352 } else {
1353 lost_fraction = shiftSignificandRight(-bits);
1354 carry = addSignificand(rhs);
1355 }
1356
1357 /* We have a guard bit; generating a carry cannot happen. */
1358 assert(!carry);
1359 }
1360
1361 return lost_fraction;
1362}
1363
1364APFloat::opStatus
1365APFloat::multiplySpecials(const APFloat &rhs)
1366{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001367 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001368 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001369 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001370
Dale Johanneseneaf08942007-08-31 04:03:46 +00001371 case convolve(fcNaN, fcZero):
1372 case convolve(fcNaN, fcNormal):
1373 case convolve(fcNaN, fcInfinity):
1374 case convolve(fcNaN, fcNaN):
1375 return opOK;
1376
1377 case convolve(fcZero, fcNaN):
1378 case convolve(fcNormal, fcNaN):
1379 case convolve(fcInfinity, fcNaN):
1380 category = fcNaN;
1381 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001382 return opOK;
1383
1384 case convolve(fcNormal, fcInfinity):
1385 case convolve(fcInfinity, fcNormal):
1386 case convolve(fcInfinity, fcInfinity):
1387 category = fcInfinity;
1388 return opOK;
1389
1390 case convolve(fcZero, fcNormal):
1391 case convolve(fcNormal, fcZero):
1392 case convolve(fcZero, fcZero):
1393 category = fcZero;
1394 return opOK;
1395
1396 case convolve(fcZero, fcInfinity):
1397 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001398 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001399 return opInvalidOp;
1400
1401 case convolve(fcNormal, fcNormal):
1402 return opOK;
1403 }
1404}
1405
1406APFloat::opStatus
1407APFloat::divideSpecials(const APFloat &rhs)
1408{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001409 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001410 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001411 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001412
Dale Johanneseneaf08942007-08-31 04:03:46 +00001413 case convolve(fcNaN, fcZero):
1414 case convolve(fcNaN, fcNormal):
1415 case convolve(fcNaN, fcInfinity):
1416 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001417 case convolve(fcInfinity, fcZero):
1418 case convolve(fcInfinity, fcNormal):
1419 case convolve(fcZero, fcInfinity):
1420 case convolve(fcZero, fcNormal):
1421 return opOK;
1422
Dale Johanneseneaf08942007-08-31 04:03:46 +00001423 case convolve(fcZero, fcNaN):
1424 case convolve(fcNormal, fcNaN):
1425 case convolve(fcInfinity, fcNaN):
1426 category = fcNaN;
1427 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001428 return opOK;
1429
1430 case convolve(fcNormal, fcInfinity):
1431 category = fcZero;
1432 return opOK;
1433
1434 case convolve(fcNormal, fcZero):
1435 category = fcInfinity;
1436 return opDivByZero;
1437
1438 case convolve(fcInfinity, fcInfinity):
1439 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001440 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001441 return opInvalidOp;
1442
1443 case convolve(fcNormal, fcNormal):
1444 return opOK;
1445 }
1446}
1447
Dale Johannesened6af242009-01-21 00:35:19 +00001448APFloat::opStatus
1449APFloat::modSpecials(const APFloat &rhs)
1450{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001451 switch (convolve(category, rhs.category)) {
Dale Johannesened6af242009-01-21 00:35:19 +00001452 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001453 llvm_unreachable(0);
Dale Johannesened6af242009-01-21 00:35:19 +00001454
1455 case convolve(fcNaN, fcZero):
1456 case convolve(fcNaN, fcNormal):
1457 case convolve(fcNaN, fcInfinity):
1458 case convolve(fcNaN, fcNaN):
1459 case convolve(fcZero, fcInfinity):
1460 case convolve(fcZero, fcNormal):
1461 case convolve(fcNormal, fcInfinity):
1462 return opOK;
1463
1464 case convolve(fcZero, fcNaN):
1465 case convolve(fcNormal, fcNaN):
1466 case convolve(fcInfinity, fcNaN):
1467 category = fcNaN;
1468 copySignificand(rhs);
1469 return opOK;
1470
1471 case convolve(fcNormal, fcZero):
1472 case convolve(fcInfinity, fcZero):
1473 case convolve(fcInfinity, fcNormal):
1474 case convolve(fcInfinity, fcInfinity):
1475 case convolve(fcZero, fcZero):
1476 makeNaN();
1477 return opInvalidOp;
1478
1479 case convolve(fcNormal, fcNormal):
1480 return opOK;
1481 }
1482}
1483
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001484/* Change sign. */
1485void
1486APFloat::changeSign()
1487{
1488 /* Look mummy, this one's easy. */
1489 sign = !sign;
1490}
1491
Dale Johannesene15c2db2007-08-31 23:35:31 +00001492void
1493APFloat::clearSign()
1494{
1495 /* So is this one. */
1496 sign = 0;
1497}
1498
1499void
1500APFloat::copySign(const APFloat &rhs)
1501{
1502 /* And this one. */
1503 sign = rhs.sign;
1504}
1505
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001506/* Normalized addition or subtraction. */
1507APFloat::opStatus
1508APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001509 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001510{
1511 opStatus fs;
1512
Neil Boothcaf19d72007-10-14 10:29:28 +00001513 assertArithmeticOK(*semantics);
1514
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001515 fs = addOrSubtractSpecials(rhs, subtract);
1516
1517 /* This return code means it was not a simple case. */
1518 if(fs == opDivByZero) {
1519 lostFraction lost_fraction;
1520
1521 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1522 fs = normalize(rounding_mode, lost_fraction);
1523
1524 /* Can only be zero if we lost no fraction. */
1525 assert(category != fcZero || lost_fraction == lfExactlyZero);
1526 }
1527
1528 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1529 positive zero unless rounding to minus infinity, except that
1530 adding two like-signed zeroes gives that zero. */
1531 if(category == fcZero) {
1532 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1533 sign = (rounding_mode == rmTowardNegative);
1534 }
1535
1536 return fs;
1537}
1538
1539/* Normalized addition. */
1540APFloat::opStatus
1541APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1542{
1543 return addOrSubtract(rhs, rounding_mode, false);
1544}
1545
1546/* Normalized subtraction. */
1547APFloat::opStatus
1548APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1549{
1550 return addOrSubtract(rhs, rounding_mode, true);
1551}
1552
1553/* Normalized multiply. */
1554APFloat::opStatus
1555APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1556{
1557 opStatus fs;
1558
Neil Boothcaf19d72007-10-14 10:29:28 +00001559 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001560 sign ^= rhs.sign;
1561 fs = multiplySpecials(rhs);
1562
1563 if(category == fcNormal) {
1564 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1565 fs = normalize(rounding_mode, lost_fraction);
1566 if(lost_fraction != lfExactlyZero)
1567 fs = (opStatus) (fs | opInexact);
1568 }
1569
1570 return fs;
1571}
1572
1573/* Normalized divide. */
1574APFloat::opStatus
1575APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1576{
1577 opStatus fs;
1578
Neil Boothcaf19d72007-10-14 10:29:28 +00001579 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001580 sign ^= rhs.sign;
1581 fs = divideSpecials(rhs);
1582
1583 if(category == fcNormal) {
1584 lostFraction lost_fraction = divideSignificand(rhs);
1585 fs = normalize(rounding_mode, lost_fraction);
1586 if(lost_fraction != lfExactlyZero)
1587 fs = (opStatus) (fs | opInexact);
1588 }
1589
1590 return fs;
1591}
1592
Dale Johannesen24b66a82009-01-20 18:35:05 +00001593/* Normalized remainder. This is not currently correct in all cases. */
1594APFloat::opStatus
1595APFloat::remainder(const APFloat &rhs)
1596{
1597 opStatus fs;
1598 APFloat V = *this;
1599 unsigned int origSign = sign;
1600
1601 assertArithmeticOK(*semantics);
1602 fs = V.divide(rhs, rmNearestTiesToEven);
1603 if (fs == opDivByZero)
1604 return fs;
1605
1606 int parts = partCount();
1607 integerPart *x = new integerPart[parts];
1608 bool ignored;
1609 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1610 rmNearestTiesToEven, &ignored);
1611 if (fs==opInvalidOp)
1612 return fs;
1613
1614 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1615 rmNearestTiesToEven);
1616 assert(fs==opOK); // should always work
1617
1618 fs = V.multiply(rhs, rmNearestTiesToEven);
1619 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1620
1621 fs = subtract(V, rmNearestTiesToEven);
1622 assert(fs==opOK || fs==opInexact); // likewise
1623
1624 if (isZero())
1625 sign = origSign; // IEEE754 requires this
1626 delete[] x;
1627 return fs;
1628}
1629
1630/* Normalized llvm frem (C fmod).
1631 This is not currently correct in all cases. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001632APFloat::opStatus
1633APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1634{
1635 opStatus fs;
Neil Boothcaf19d72007-10-14 10:29:28 +00001636 assertArithmeticOK(*semantics);
Dale Johannesened6af242009-01-21 00:35:19 +00001637 fs = modSpecials(rhs);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001638
Dale Johannesened6af242009-01-21 00:35:19 +00001639 if (category == fcNormal && rhs.category == fcNormal) {
1640 APFloat V = *this;
1641 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001642
Dale Johannesened6af242009-01-21 00:35:19 +00001643 fs = V.divide(rhs, rmNearestTiesToEven);
1644 if (fs == opDivByZero)
1645 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001646
Dale Johannesened6af242009-01-21 00:35:19 +00001647 int parts = partCount();
1648 integerPart *x = new integerPart[parts];
1649 bool ignored;
1650 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1651 rmTowardZero, &ignored);
1652 if (fs==opInvalidOp)
1653 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001654
Dale Johannesened6af242009-01-21 00:35:19 +00001655 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1656 rmNearestTiesToEven);
1657 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001658
Dale Johannesened6af242009-01-21 00:35:19 +00001659 fs = V.multiply(rhs, rounding_mode);
1660 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1661
1662 fs = subtract(V, rounding_mode);
1663 assert(fs==opOK || fs==opInexact); // likewise
1664
1665 if (isZero())
1666 sign = origSign; // IEEE754 requires this
1667 delete[] x;
1668 }
Dale Johannesene15c2db2007-08-31 23:35:31 +00001669 return fs;
1670}
1671
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001672/* Normalized fused-multiply-add. */
1673APFloat::opStatus
1674APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001675 const APFloat &addend,
1676 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001677{
1678 opStatus fs;
1679
Neil Boothcaf19d72007-10-14 10:29:28 +00001680 assertArithmeticOK(*semantics);
1681
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001682 /* Post-multiplication sign, before addition. */
1683 sign ^= multiplicand.sign;
1684
1685 /* If and only if all arguments are normal do we need to do an
1686 extended-precision calculation. */
1687 if(category == fcNormal
1688 && multiplicand.category == fcNormal
1689 && addend.category == fcNormal) {
1690 lostFraction lost_fraction;
1691
1692 lost_fraction = multiplySignificand(multiplicand, &addend);
1693 fs = normalize(rounding_mode, lost_fraction);
1694 if(lost_fraction != lfExactlyZero)
1695 fs = (opStatus) (fs | opInexact);
1696
1697 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1698 positive zero unless rounding to minus infinity, except that
1699 adding two like-signed zeroes gives that zero. */
1700 if(category == fcZero && sign != addend.sign)
1701 sign = (rounding_mode == rmTowardNegative);
1702 } else {
1703 fs = multiplySpecials(multiplicand);
1704
1705 /* FS can only be opOK or opInvalidOp. There is no more work
1706 to do in the latter case. The IEEE-754R standard says it is
1707 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001708 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001709
1710 If we need to do the addition we can do so with normal
1711 precision. */
1712 if(fs == opOK)
1713 fs = addOrSubtract(addend, rounding_mode, false);
1714 }
1715
1716 return fs;
1717}
1718
1719/* Comparison requires normalized numbers. */
1720APFloat::cmpResult
1721APFloat::compare(const APFloat &rhs) const
1722{
1723 cmpResult result;
1724
Neil Boothcaf19d72007-10-14 10:29:28 +00001725 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001726 assert(semantics == rhs.semantics);
1727
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001728 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001729 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001730 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001731
Dale Johanneseneaf08942007-08-31 04:03:46 +00001732 case convolve(fcNaN, fcZero):
1733 case convolve(fcNaN, fcNormal):
1734 case convolve(fcNaN, fcInfinity):
1735 case convolve(fcNaN, fcNaN):
1736 case convolve(fcZero, fcNaN):
1737 case convolve(fcNormal, fcNaN):
1738 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001739 return cmpUnordered;
1740
1741 case convolve(fcInfinity, fcNormal):
1742 case convolve(fcInfinity, fcZero):
1743 case convolve(fcNormal, fcZero):
1744 if(sign)
1745 return cmpLessThan;
1746 else
1747 return cmpGreaterThan;
1748
1749 case convolve(fcNormal, fcInfinity):
1750 case convolve(fcZero, fcInfinity):
1751 case convolve(fcZero, fcNormal):
1752 if(rhs.sign)
1753 return cmpGreaterThan;
1754 else
1755 return cmpLessThan;
1756
1757 case convolve(fcInfinity, fcInfinity):
1758 if(sign == rhs.sign)
1759 return cmpEqual;
1760 else if(sign)
1761 return cmpLessThan;
1762 else
1763 return cmpGreaterThan;
1764
1765 case convolve(fcZero, fcZero):
1766 return cmpEqual;
1767
1768 case convolve(fcNormal, fcNormal):
1769 break;
1770 }
1771
1772 /* Two normal numbers. Do they have the same sign? */
1773 if(sign != rhs.sign) {
1774 if(sign)
1775 result = cmpLessThan;
1776 else
1777 result = cmpGreaterThan;
1778 } else {
1779 /* Compare absolute values; invert result if negative. */
1780 result = compareAbsoluteValue(rhs);
1781
1782 if(sign) {
1783 if(result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001784 result = cmpGreaterThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001785 else if(result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001786 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001787 }
1788 }
1789
1790 return result;
1791}
1792
Dale Johannesen23a98552008-10-09 23:00:39 +00001793/// APFloat::convert - convert a value of one floating point type to another.
1794/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1795/// records whether the transformation lost information, i.e. whether
1796/// converting the result back to the original type will produce the
1797/// original value (this is almost the same as return value==fsOK, but there
1798/// are edge cases where this is not so).
1799
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001800APFloat::opStatus
1801APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001802 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001803{
Neil Boothc8db43d2007-09-22 02:56:19 +00001804 lostFraction lostFraction;
1805 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001806 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001807
Neil Boothcaf19d72007-10-14 10:29:28 +00001808 assertArithmeticOK(*semantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001809 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001810 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001811 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001812 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001813
Neil Boothc8db43d2007-09-22 02:56:19 +00001814 /* Handle storage complications. If our new form is wider,
1815 re-allocate our bit pattern into wider storage. If it is
1816 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001817 single part we need to free the old storage.
1818 Be careful not to reference significandParts for zeroes
1819 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001820 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001821 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001822 newParts = new integerPart[newPartCount];
1823 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001824 if (category==fcNormal || category==fcNaN)
1825 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001826 freeSignificand();
1827 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001828 } else if (newPartCount < oldPartCount) {
1829 /* Capture any lost fraction through truncation of parts so we get
1830 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001831 if (category==fcNormal)
1832 lostFraction = lostFractionThroughTruncation
1833 (significandParts(), oldPartCount, toSemantics.precision);
1834 if (newPartCount == 1) {
1835 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001836 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001837 newPart = significandParts()[0];
1838 freeSignificand();
1839 significand.part = newPart;
1840 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001841 }
1842
1843 if(category == fcNormal) {
1844 /* Re-interpret our bit-pattern. */
1845 exponent += toSemantics.precision - semantics->precision;
1846 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001847 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001848 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001849 } else if (category == fcNaN) {
1850 int shift = toSemantics.precision - semantics->precision;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001851 // Do this now so significandParts gets the right answer
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001852 const fltSemantics *oldSemantics = semantics;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001853 semantics = &toSemantics;
Dale Johannesen23a98552008-10-09 23:00:39 +00001854 *losesInfo = false;
Dale Johannesen902ff942007-09-25 17:25:00 +00001855 // No normalization here, just truncate
1856 if (shift>0)
1857 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001858 else if (shift < 0) {
1859 unsigned ushift = -shift;
Dale Johannesen23a98552008-10-09 23:00:39 +00001860 // Figure out if we are losing information. This happens
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001861 // if are shifting out something other than 0s, or if the x87 long
1862 // double input did not have its integer bit set (pseudo-NaN), or if the
1863 // x87 long double input did not have its QNan bit set (because the x87
1864 // hardware sets this bit when converting a lower-precision NaN to
1865 // x87 long double).
1866 if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
Dale Johannesen23a98552008-10-09 23:00:39 +00001867 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001868 if (oldSemantics == &APFloat::x87DoubleExtended &&
1869 (!(*significandParts() & 0x8000000000000000ULL) ||
1870 !(*significandParts() & 0x4000000000000000ULL)))
Dale Johannesen23a98552008-10-09 23:00:39 +00001871 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001872 APInt::tcShiftRight(significandParts(), newPartCount, ushift);
1873 }
Dale Johannesen902ff942007-09-25 17:25:00 +00001874 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1875 // does not give you back the same bits. This is dubious, and we
1876 // don't currently do it. You're really supposed to get
1877 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001878 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001879 } else {
1880 semantics = &toSemantics;
1881 fs = opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001882 *losesInfo = false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001883 }
1884
1885 return fs;
1886}
1887
1888/* Convert a floating point number to an integer according to the
1889 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001890 returns an invalid operation exception and the contents of the
1891 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001892 range but the floating point number is not the exact integer, the C
1893 standard doesn't require an inexact exception to be raised. IEEE
1894 854 does require it so we do that.
1895
1896 Note that for conversions to integer type the C standard requires
1897 round-to-zero to always be used. */
1898APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001899APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1900 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001901 roundingMode rounding_mode,
1902 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001903{
1904 lostFraction lost_fraction;
1905 const integerPart *src;
1906 unsigned int dstPartsCount, truncatedBits;
1907
Evan Cheng794a7db2008-11-26 01:11:57 +00001908 assertArithmeticOK(*semantics);
Neil Boothe3d936a2007-11-02 15:10:05 +00001909
Dale Johannesen23a98552008-10-09 23:00:39 +00001910 *isExact = false;
1911
Neil Boothee7ae382007-11-01 22:43:37 +00001912 /* Handle the three special cases first. */
1913 if(category == fcInfinity || category == fcNaN)
1914 return opInvalidOp;
1915
1916 dstPartsCount = partCountForBits(width);
1917
1918 if(category == fcZero) {
1919 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00001920 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00001921 *isExact = !sign;
1922 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00001923 }
1924
1925 src = significandParts();
1926
1927 /* Step 1: place our absolute value, with any fraction truncated, in
1928 the destination. */
1929 if (exponent < 0) {
1930 /* Our absolute value is less than one; truncate everything. */
1931 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen1f54f582009-01-19 21:17:05 +00001932 /* For exponent -1 the integer bit represents .5, look at that.
1933 For smaller exponents leftmost truncated bit is 0. */
1934 truncatedBits = semantics->precision -1U - exponent;
Neil Boothee7ae382007-11-01 22:43:37 +00001935 } else {
1936 /* We want the most significant (exponent + 1) bits; the rest are
1937 truncated. */
1938 unsigned int bits = exponent + 1U;
1939
1940 /* Hopelessly large in magnitude? */
1941 if (bits > width)
1942 return opInvalidOp;
1943
1944 if (bits < semantics->precision) {
1945 /* We truncate (semantics->precision - bits) bits. */
1946 truncatedBits = semantics->precision - bits;
1947 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1948 } else {
1949 /* We want at least as many bits as are available. */
1950 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
1951 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
1952 truncatedBits = 0;
1953 }
1954 }
1955
1956 /* Step 2: work out any lost fraction, and increment the absolute
1957 value if we would round away from zero. */
1958 if (truncatedBits) {
1959 lost_fraction = lostFractionThroughTruncation(src, partCount(),
1960 truncatedBits);
1961 if (lost_fraction != lfExactlyZero
1962 && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
1963 if (APInt::tcIncrement(parts, dstPartsCount))
1964 return opInvalidOp; /* Overflow. */
1965 }
1966 } else {
1967 lost_fraction = lfExactlyZero;
1968 }
1969
1970 /* Step 3: check if we fit in the destination. */
1971 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
1972
1973 if (sign) {
1974 if (!isSigned) {
1975 /* Negative numbers cannot be represented as unsigned. */
1976 if (omsb != 0)
1977 return opInvalidOp;
1978 } else {
1979 /* It takes omsb bits to represent the unsigned integer value.
1980 We lose a bit for the sign, but care is needed as the
1981 maximally negative integer is a special case. */
1982 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
1983 return opInvalidOp;
1984
1985 /* This case can happen because of rounding. */
1986 if (omsb > width)
1987 return opInvalidOp;
1988 }
1989
1990 APInt::tcNegate (parts, dstPartsCount);
1991 } else {
1992 if (omsb >= width + !isSigned)
1993 return opInvalidOp;
1994 }
1995
Dale Johannesen23a98552008-10-09 23:00:39 +00001996 if (lost_fraction == lfExactlyZero) {
1997 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00001998 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001999 } else
Neil Boothee7ae382007-11-01 22:43:37 +00002000 return opInexact;
2001}
2002
2003/* Same as convertToSignExtendedInteger, except we provide
2004 deterministic values in case of an invalid operation exception,
2005 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00002006 for underflow or overflow.
2007 The *isExact output tells whether the result is exact, in the sense
2008 that converting it back to the original floating point type produces
2009 the original value. This is almost equivalent to result==opOK,
2010 except for negative zeroes.
2011*/
Neil Boothee7ae382007-11-01 22:43:37 +00002012APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002013APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00002014 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00002015 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002016{
Neil Boothee7ae382007-11-01 22:43:37 +00002017 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002018
Dale Johannesen23a98552008-10-09 23:00:39 +00002019 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
2020 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002021
Neil Boothee7ae382007-11-01 22:43:37 +00002022 if (fs == opInvalidOp) {
2023 unsigned int bits, dstPartsCount;
2024
2025 dstPartsCount = partCountForBits(width);
2026
2027 if (category == fcNaN)
2028 bits = 0;
2029 else if (sign)
2030 bits = isSigned;
2031 else
2032 bits = width - isSigned;
2033
2034 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2035 if (sign && isSigned)
2036 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002037 }
2038
Neil Boothee7ae382007-11-01 22:43:37 +00002039 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002040}
2041
Neil Booth643ce592007-10-07 12:07:53 +00002042/* Convert an unsigned integer SRC to a floating point number,
2043 rounding according to ROUNDING_MODE. The sign of the floating
2044 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002045APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00002046APFloat::convertFromUnsignedParts(const integerPart *src,
2047 unsigned int srcCount,
2048 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002049{
Neil Booth5477f852007-10-08 14:39:42 +00002050 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00002051 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00002052 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002053
Neil Boothcaf19d72007-10-14 10:29:28 +00002054 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002055 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00002056 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00002057 dst = significandParts();
2058 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00002059 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00002060
Neil Booth5477f852007-10-08 14:39:42 +00002061 /* We want the most significant PRECISON bits of SRC. There may not
2062 be that many; extract what we can. */
2063 if (precision <= omsb) {
2064 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00002065 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00002066 omsb - precision);
2067 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2068 } else {
2069 exponent = precision - 1;
2070 lost_fraction = lfExactlyZero;
2071 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00002072 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002073
2074 return normalize(rounding_mode, lost_fraction);
2075}
2076
Dan Gohman93c276e2008-02-29 01:26:11 +00002077APFloat::opStatus
2078APFloat::convertFromAPInt(const APInt &Val,
2079 bool isSigned,
2080 roundingMode rounding_mode)
2081{
2082 unsigned int partCount = Val.getNumWords();
2083 APInt api = Val;
2084
2085 sign = false;
2086 if (isSigned && api.isNegative()) {
2087 sign = true;
2088 api = -api;
2089 }
2090
2091 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2092}
2093
Neil Boothf16c5952007-10-07 12:15:41 +00002094/* Convert a two's complement integer SRC to a floating point number,
2095 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2096 integer is signed, in which case it must be sign-extended. */
2097APFloat::opStatus
2098APFloat::convertFromSignExtendedInteger(const integerPart *src,
2099 unsigned int srcCount,
2100 bool isSigned,
2101 roundingMode rounding_mode)
2102{
2103 opStatus status;
2104
Neil Boothcaf19d72007-10-14 10:29:28 +00002105 assertArithmeticOK(*semantics);
Neil Boothf16c5952007-10-07 12:15:41 +00002106 if (isSigned
2107 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
2108 integerPart *copy;
2109
2110 /* If we're signed and negative negate a copy. */
2111 sign = true;
2112 copy = new integerPart[srcCount];
2113 APInt::tcAssign(copy, src, srcCount);
2114 APInt::tcNegate(copy, srcCount);
2115 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2116 delete [] copy;
2117 } else {
2118 sign = false;
2119 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2120 }
2121
2122 return status;
2123}
2124
Neil Boothccf596a2007-10-07 11:45:55 +00002125/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002126APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002127APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2128 unsigned int width, bool isSigned,
2129 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002130{
Dale Johannesen910993e2007-09-21 22:09:37 +00002131 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00002132 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002133
2134 sign = false;
Dale Johannesencce23a42007-09-30 18:17:01 +00002135 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
2136 sign = true;
2137 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002138 }
2139
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002140 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002141}
2142
2143APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002144APFloat::convertFromHexadecimalString(const StringRef &s,
Neil Booth4f881702007-09-26 21:33:42 +00002145 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002146{
Erick Tryzelaarf8bc8012009-08-18 18:20:37 +00002147 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002148 integerPart *significand;
2149 unsigned int bitPos, partsCount;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002150 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002151
2152 zeroSignificand();
2153 exponent = 0;
2154 category = fcNormal;
2155
2156 significand = significandParts();
2157 partsCount = partCount();
2158 bitPos = partsCount * integerPartWidth;
2159
Neil Booth33d4c922007-10-07 08:51:21 +00002160 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002161 StringRef::iterator begin = s.begin();
2162 StringRef::iterator end = s.end();
2163 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002164 firstSignificantDigit = p;
2165
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002166 for(; p != end;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002167 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002168
2169 if(*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002170 assert(dot == end && "String contains multiple dots");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002171 dot = p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002172 if (p == end) {
2173 break;
2174 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002175 }
2176
2177 hex_value = hexDigitValue(*p);
2178 if(hex_value == -1U) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002179 break;
2180 }
2181
2182 p++;
2183
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002184 if (p == end) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002185 break;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002186 } else {
2187 /* Store the number whilst 4-bit nibbles remain. */
2188 if(bitPos) {
2189 bitPos -= 4;
2190 hex_value <<= bitPos % integerPartWidth;
2191 significand[bitPos / integerPartWidth] |= hex_value;
2192 } else {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002193 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2194 while(p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002195 p++;
2196 break;
2197 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002198 }
2199 }
2200
2201 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002202 assert(p != end && "Hex strings require an exponent");
2203 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2204 assert(p != begin && "Significand has no digits");
2205 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002206
2207 /* Ignore the exponent if we are zero. */
2208 if(p != firstSignificantDigit) {
2209 int expAdjustment;
2210
2211 /* Implicit hexadecimal point? */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002212 if (dot == end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002213 dot = p;
2214
2215 /* Calculate the exponent adjustment implicit in the number of
2216 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002217 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002218 if(expAdjustment < 0)
2219 expAdjustment++;
2220 expAdjustment = expAdjustment * 4 - 1;
2221
2222 /* Adjust for writing the significand starting at the most
2223 significant nibble. */
2224 expAdjustment += semantics->precision;
2225 expAdjustment -= partsCount * integerPartWidth;
2226
2227 /* Adjust for the given exponent. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002228 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002229 }
2230
2231 return normalize(rounding_mode, lost_fraction);
2232}
2233
2234APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002235APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2236 unsigned sigPartCount, int exp,
2237 roundingMode rounding_mode)
2238{
2239 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002240 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002241 integerPart pow5Parts[maxPowerOfFiveParts];
2242 bool isNearest;
2243
2244 isNearest = (rounding_mode == rmNearestTiesToEven
2245 || rounding_mode == rmNearestTiesToAway);
2246
2247 parts = partCountForBits(semantics->precision + 11);
2248
2249 /* Calculate pow(5, abs(exp)). */
2250 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2251
2252 for (;; parts *= 2) {
2253 opStatus sigStatus, powStatus;
2254 unsigned int excessPrecision, truncatedBits;
2255
2256 calcSemantics.precision = parts * integerPartWidth - 1;
2257 excessPrecision = calcSemantics.precision - semantics->precision;
2258 truncatedBits = excessPrecision;
2259
2260 APFloat decSig(calcSemantics, fcZero, sign);
2261 APFloat pow5(calcSemantics, fcZero, false);
2262
2263 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2264 rmNearestTiesToEven);
2265 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2266 rmNearestTiesToEven);
2267 /* Add exp, as 10^n = 5^n * 2^n. */
2268 decSig.exponent += exp;
2269
2270 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002271 integerPart HUerr, HUdistance;
2272 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002273
2274 if (exp >= 0) {
2275 /* multiplySignificand leaves the precision-th bit set to 1. */
2276 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2277 powHUerr = powStatus != opOK;
2278 } else {
2279 calcLostFraction = decSig.divideSignificand(pow5);
2280 /* Denormal numbers have less precision. */
2281 if (decSig.exponent < semantics->minExponent) {
2282 excessPrecision += (semantics->minExponent - decSig.exponent);
2283 truncatedBits = excessPrecision;
2284 if (excessPrecision > calcSemantics.precision)
2285 excessPrecision = calcSemantics.precision;
2286 }
2287 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002288 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002289 }
2290
2291 /* Both multiplySignificand and divideSignificand return the
2292 result with the integer bit set. */
Evan Cheng99ebfa52009-10-27 21:35:42 +00002293 assert(APInt::tcExtractBit
2294 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Booth96c74712007-10-12 16:02:31 +00002295
2296 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2297 powHUerr);
2298 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2299 excessPrecision, isNearest);
2300
2301 /* Are we guaranteed to round correctly if we truncate? */
2302 if (HUdistance >= HUerr) {
2303 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2304 calcSemantics.precision - excessPrecision,
2305 excessPrecision);
2306 /* Take the exponent of decSig. If we tcExtract-ed less bits
2307 above we must adjust our exponent to compensate for the
2308 implicit right shift. */
2309 exponent = (decSig.exponent + semantics->precision
2310 - (calcSemantics.precision - excessPrecision));
2311 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2312 decSig.partCount(),
2313 truncatedBits);
2314 return normalize(rounding_mode, calcLostFraction);
2315 }
2316 }
2317}
2318
2319APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002320APFloat::convertFromDecimalString(const StringRef &str, roundingMode rounding_mode)
Neil Booth96c74712007-10-12 16:02:31 +00002321{
Neil Booth1870f292007-10-14 10:16:12 +00002322 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002323 opStatus fs;
2324
Neil Booth1870f292007-10-14 10:16:12 +00002325 /* Scan the text. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002326 StringRef::iterator p = str.begin();
2327 interpretDecimal(p, str.end(), &D);
Neil Booth96c74712007-10-12 16:02:31 +00002328
Neil Booth686700e2007-10-15 15:00:55 +00002329 /* Handle the quick cases. First the case of no significant digits,
2330 i.e. zero, and then exponents that are obviously too large or too
2331 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2332 definitely overflows if
2333
2334 (exp - 1) * L >= maxExponent
2335
2336 and definitely underflows to zero where
2337
2338 (exp + 1) * L <= minExponent - precision
2339
2340 With integer arithmetic the tightest bounds for L are
2341
2342 93/28 < L < 196/59 [ numerator <= 256 ]
2343 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2344 */
2345
Neil Boothcc233592007-12-05 13:06:04 +00002346 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002347 category = fcZero;
2348 fs = opOK;
John McCall8b3f3302010-02-26 22:20:41 +00002349
2350 /* Check whether the normalized exponent is high enough to overflow
2351 max during the log-rebasing in the max-exponent check below. */
2352 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2353 fs = handleOverflow(rounding_mode);
2354
2355 /* If it wasn't, then it also wasn't high enough to overflow max
2356 during the log-rebasing in the min-exponent check. Check that it
2357 won't overflow min in either check, then perform the min-exponent
2358 check. */
2359 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2360 (D.normalizedExponent + 1) * 28738 <=
2361 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth686700e2007-10-15 15:00:55 +00002362 /* Underflow to zero and round. */
2363 zeroSignificand();
2364 fs = normalize(rounding_mode, lfLessThanHalf);
John McCall8b3f3302010-02-26 22:20:41 +00002365
2366 /* We can finally safely perform the max-exponent check. */
Neil Booth686700e2007-10-15 15:00:55 +00002367 } else if ((D.normalizedExponent - 1) * 42039
2368 >= 12655 * semantics->maxExponent) {
2369 /* Overflow and round. */
2370 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002371 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002372 integerPart *decSignificand;
2373 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002374
Neil Booth1870f292007-10-14 10:16:12 +00002375 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002376 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002377 to hold the full significand, and an extra part required by
2378 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002379 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002380 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002381 decSignificand = new integerPart[partCount + 1];
2382 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002383
Neil Booth1870f292007-10-14 10:16:12 +00002384 /* Convert to binary efficiently - we do almost all multiplication
2385 in an integerPart. When this would overflow do we do a single
2386 bignum multiplication, and then revert again to multiplication
2387 in an integerPart. */
2388 do {
2389 integerPart decValue, val, multiplier;
2390
2391 val = 0;
2392 multiplier = 1;
2393
2394 do {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002395 if (*p == '.') {
Neil Booth1870f292007-10-14 10:16:12 +00002396 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002397 if (p == str.end()) {
2398 break;
2399 }
2400 }
Neil Booth1870f292007-10-14 10:16:12 +00002401 decValue = decDigitValue(*p++);
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002402 assert(decValue < 10U && "Invalid character in significand");
Neil Booth1870f292007-10-14 10:16:12 +00002403 multiplier *= 10;
2404 val = val * 10 + decValue;
2405 /* The maximum number that can be multiplied by ten with any
2406 digit added without overflowing an integerPart. */
2407 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2408
2409 /* Multiply out the current part. */
2410 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2411 partCount, partCount + 1, false);
2412
2413 /* If we used another part (likely but not guaranteed), increase
2414 the count. */
2415 if (decSignificand[partCount])
2416 partCount++;
2417 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002418
Neil Booth43a4b282007-11-01 22:51:07 +00002419 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002420 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002421 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002422
Neil Booth1870f292007-10-14 10:16:12 +00002423 delete [] decSignificand;
2424 }
Neil Booth96c74712007-10-12 16:02:31 +00002425
2426 return fs;
2427}
2428
2429APFloat::opStatus
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002430APFloat::convertFromString(const StringRef &str, roundingMode rounding_mode)
Neil Booth4f881702007-09-26 21:33:42 +00002431{
Neil Boothcaf19d72007-10-14 10:29:28 +00002432 assertArithmeticOK(*semantics);
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002433 assert(!str.empty() && "Invalid string length");
Neil Boothcaf19d72007-10-14 10:29:28 +00002434
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002435 /* Handle a leading minus sign. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002436 StringRef::iterator p = str.begin();
2437 size_t slen = str.size();
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002438 sign = *p == '-' ? 1 : 0;
2439 if(*p == '-' || *p == '+') {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002440 p++;
2441 slen--;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002442 assert(slen && "String has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002443 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002444
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002445 if(slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
2446 assert(slen - 2 && "Invalid string");
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002447 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002448 rounding_mode);
2449 }
Bill Wendlingb7c0d942008-11-27 08:00:12 +00002450
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002451 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002452}
Dale Johannesen343e7702007-08-24 00:56:33 +00002453
Neil Bootha30b0ee2007-10-03 22:26:02 +00002454/* Write out a hexadecimal representation of the floating point value
2455 to DST, which must be of sufficient size, in the C99 form
2456 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2457 excluding the terminating NUL.
2458
2459 If UPPERCASE, the output is in upper case, otherwise in lower case.
2460
2461 HEXDIGITS digits appear altogether, rounding the value if
2462 necessary. If HEXDIGITS is 0, the minimal precision to display the
2463 number precisely is used instead. If nothing would appear after
2464 the decimal point it is suppressed.
2465
2466 The decimal exponent is always printed and has at least one digit.
2467 Zero values display an exponent of zero. Infinities and NaNs
2468 appear as "infinity" or "nan" respectively.
2469
2470 The above rules are as specified by C99. There is ambiguity about
2471 what the leading hexadecimal digit should be. This implementation
2472 uses whatever is necessary so that the exponent is displayed as
2473 stored. This implies the exponent will fall within the IEEE format
2474 range, and the leading hexadecimal digit will be 0 (for denormals),
2475 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2476 any other digits zero).
2477*/
2478unsigned int
2479APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2480 bool upperCase, roundingMode rounding_mode) const
2481{
2482 char *p;
2483
Neil Boothcaf19d72007-10-14 10:29:28 +00002484 assertArithmeticOK(*semantics);
2485
Neil Bootha30b0ee2007-10-03 22:26:02 +00002486 p = dst;
2487 if (sign)
2488 *dst++ = '-';
2489
2490 switch (category) {
2491 case fcInfinity:
2492 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2493 dst += sizeof infinityL - 1;
2494 break;
2495
2496 case fcNaN:
2497 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2498 dst += sizeof NaNU - 1;
2499 break;
2500
2501 case fcZero:
2502 *dst++ = '0';
2503 *dst++ = upperCase ? 'X': 'x';
2504 *dst++ = '0';
2505 if (hexDigits > 1) {
2506 *dst++ = '.';
2507 memset (dst, '0', hexDigits - 1);
2508 dst += hexDigits - 1;
2509 }
2510 *dst++ = upperCase ? 'P': 'p';
2511 *dst++ = '0';
2512 break;
2513
2514 case fcNormal:
2515 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2516 break;
2517 }
2518
2519 *dst = 0;
2520
Evan Cheng48e8c802008-05-02 21:15:08 +00002521 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002522}
2523
2524/* Does the hard work of outputting the correctly rounded hexadecimal
2525 form of a normal floating point number with the specified number of
2526 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2527 digits necessary to print the value precisely is output. */
2528char *
2529APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2530 bool upperCase,
2531 roundingMode rounding_mode) const
2532{
2533 unsigned int count, valueBits, shift, partsCount, outputDigits;
2534 const char *hexDigitChars;
2535 const integerPart *significand;
2536 char *p;
2537 bool roundUp;
2538
2539 *dst++ = '0';
2540 *dst++ = upperCase ? 'X': 'x';
2541
2542 roundUp = false;
2543 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2544
2545 significand = significandParts();
2546 partsCount = partCount();
2547
2548 /* +3 because the first digit only uses the single integer bit, so
2549 we have 3 virtual zero most-significant-bits. */
2550 valueBits = semantics->precision + 3;
2551 shift = integerPartWidth - valueBits % integerPartWidth;
2552
2553 /* The natural number of digits required ignoring trailing
2554 insignificant zeroes. */
2555 outputDigits = (valueBits - significandLSB () + 3) / 4;
2556
2557 /* hexDigits of zero means use the required number for the
2558 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002559 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002560 if (hexDigits) {
2561 if (hexDigits < outputDigits) {
2562 /* We are dropping non-zero bits, so need to check how to round.
2563 "bits" is the number of dropped bits. */
2564 unsigned int bits;
2565 lostFraction fraction;
2566
2567 bits = valueBits - hexDigits * 4;
2568 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2569 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2570 }
2571 outputDigits = hexDigits;
2572 }
2573
2574 /* Write the digits consecutively, and start writing in the location
2575 of the hexadecimal point. We move the most significant digit
2576 left and add the hexadecimal point later. */
2577 p = ++dst;
2578
2579 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2580
2581 while (outputDigits && count) {
2582 integerPart part;
2583
2584 /* Put the most significant integerPartWidth bits in "part". */
2585 if (--count == partsCount)
2586 part = 0; /* An imaginary higher zero part. */
2587 else
2588 part = significand[count] << shift;
2589
2590 if (count && shift)
2591 part |= significand[count - 1] >> (integerPartWidth - shift);
2592
2593 /* Convert as much of "part" to hexdigits as we can. */
2594 unsigned int curDigits = integerPartWidth / 4;
2595
2596 if (curDigits > outputDigits)
2597 curDigits = outputDigits;
2598 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2599 outputDigits -= curDigits;
2600 }
2601
2602 if (roundUp) {
2603 char *q = dst;
2604
2605 /* Note that hexDigitChars has a trailing '0'. */
2606 do {
2607 q--;
2608 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002609 } while (*q == '0');
Evan Cheng99ebfa52009-10-27 21:35:42 +00002610 assert(q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002611 } else {
2612 /* Add trailing zeroes. */
2613 memset (dst, '0', outputDigits);
2614 dst += outputDigits;
2615 }
2616
2617 /* Move the most significant digit to before the point, and if there
2618 is something after the decimal point add it. This must come
2619 after rounding above. */
2620 p[-1] = p[0];
2621 if (dst -1 == p)
2622 dst--;
2623 else
2624 p[0] = '.';
2625
2626 /* Finally output the exponent. */
2627 *dst++ = upperCase ? 'P': 'p';
2628
Neil Booth92f7e8d2007-10-06 07:29:25 +00002629 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002630}
2631
Dale Johannesen343e7702007-08-24 00:56:33 +00002632// For good performance it is desirable for different APFloats
2633// to produce different integers.
2634uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00002635APFloat::getHashValue() const
2636{
Dale Johannesen343e7702007-08-24 00:56:33 +00002637 if (category==fcZero) return sign<<8 | semantics->precision ;
2638 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002639 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00002640 else {
2641 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2642 const integerPart* p = significandParts();
2643 for (int i=partCount(); i>0; i--, p++)
Evan Cheng48e8c802008-05-02 21:15:08 +00002644 hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
Dale Johannesen343e7702007-08-24 00:56:33 +00002645 return hash;
2646 }
2647}
2648
2649// Conversion from APFloat to/from host float/double. It may eventually be
2650// possible to eliminate these and have everybody deal with APFloats, but that
2651// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002652// Current implementation requires integerPartWidth==64, which is correct at
2653// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002654
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002655// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002656// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002657
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002658APInt
Neil Booth4f881702007-09-26 21:33:42 +00002659APFloat::convertF80LongDoubleAPFloatToAPInt() const
2660{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002661 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002662 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002663
2664 uint64_t myexponent, mysignificand;
2665
2666 if (category==fcNormal) {
2667 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002668 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002669 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2670 myexponent = 0; // denormal
2671 } else if (category==fcZero) {
2672 myexponent = 0;
2673 mysignificand = 0;
2674 } else if (category==fcInfinity) {
2675 myexponent = 0x7fff;
2676 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002677 } else {
2678 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002679 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002680 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002681 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002682
2683 uint64_t words[2];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002684 words[0] = mysignificand;
2685 words[1] = ((uint64_t)(sign & 1) << 15) |
2686 (myexponent & 0x7fffLL);
Chris Lattnera11ef822007-10-06 06:13:42 +00002687 return APInt(80, 2, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002688}
2689
2690APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002691APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2692{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002693 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002694 assert(partCount()==2);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002695
2696 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2697
2698 if (category==fcNormal) {
2699 myexponent = exponent + 1023; //bias
2700 myexponent2 = exponent2 + 1023;
2701 mysignificand = significandParts()[0];
2702 mysignificand2 = significandParts()[1];
2703 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2704 myexponent = 0; // denormal
2705 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2706 myexponent2 = 0; // denormal
2707 } else if (category==fcZero) {
2708 myexponent = 0;
2709 mysignificand = 0;
2710 myexponent2 = 0;
2711 mysignificand2 = 0;
2712 } else if (category==fcInfinity) {
2713 myexponent = 0x7ff;
2714 myexponent2 = 0;
2715 mysignificand = 0;
2716 mysignificand2 = 0;
2717 } else {
2718 assert(category == fcNaN && "Unknown category");
2719 myexponent = 0x7ff;
2720 mysignificand = significandParts()[0];
2721 myexponent2 = exponent2;
2722 mysignificand2 = significandParts()[1];
2723 }
2724
2725 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002726 words[0] = ((uint64_t)(sign & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002727 ((myexponent & 0x7ff) << 52) |
2728 (mysignificand & 0xfffffffffffffLL);
Evan Cheng48e8c802008-05-02 21:15:08 +00002729 words[1] = ((uint64_t)(sign2 & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002730 ((myexponent2 & 0x7ff) << 52) |
2731 (mysignificand2 & 0xfffffffffffffLL);
2732 return APInt(128, 2, words);
2733}
2734
2735APInt
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002736APFloat::convertQuadrupleAPFloatToAPInt() const
2737{
2738 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002739 assert(partCount()==2);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002740
2741 uint64_t myexponent, mysignificand, mysignificand2;
2742
2743 if (category==fcNormal) {
2744 myexponent = exponent+16383; //bias
2745 mysignificand = significandParts()[0];
2746 mysignificand2 = significandParts()[1];
2747 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2748 myexponent = 0; // denormal
2749 } else if (category==fcZero) {
2750 myexponent = 0;
2751 mysignificand = mysignificand2 = 0;
2752 } else if (category==fcInfinity) {
2753 myexponent = 0x7fff;
2754 mysignificand = mysignificand2 = 0;
2755 } else {
2756 assert(category == fcNaN && "Unknown category!");
2757 myexponent = 0x7fff;
2758 mysignificand = significandParts()[0];
2759 mysignificand2 = significandParts()[1];
2760 }
2761
2762 uint64_t words[2];
2763 words[0] = mysignificand;
2764 words[1] = ((uint64_t)(sign & 1) << 63) |
2765 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov4755e992009-08-21 23:09:47 +00002766 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002767
2768 return APInt(128, 2, words);
2769}
2770
2771APInt
Neil Booth4f881702007-09-26 21:33:42 +00002772APFloat::convertDoubleAPFloatToAPInt() const
2773{
Dan Gohmancb648f92007-09-14 20:08:19 +00002774 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002775 assert(partCount()==1);
Dale Johannesen343e7702007-08-24 00:56:33 +00002776
Dale Johanneseneaf08942007-08-31 04:03:46 +00002777 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002778
2779 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002780 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002781 mysignificand = *significandParts();
2782 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2783 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002784 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002785 myexponent = 0;
2786 mysignificand = 0;
2787 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002788 myexponent = 0x7ff;
2789 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002790 } else {
2791 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002792 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002793 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002794 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002795
Evan Cheng48e8c802008-05-02 21:15:08 +00002796 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002797 ((myexponent & 0x7ff) << 52) |
2798 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002799}
2800
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002801APInt
Neil Booth4f881702007-09-26 21:33:42 +00002802APFloat::convertFloatAPFloatToAPInt() const
2803{
Dan Gohmancb648f92007-09-14 20:08:19 +00002804 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002805 assert(partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002806
Dale Johanneseneaf08942007-08-31 04:03:46 +00002807 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002808
2809 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002810 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002811 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002812 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002813 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002814 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002815 myexponent = 0;
2816 mysignificand = 0;
2817 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002818 myexponent = 0xff;
2819 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002820 } else {
2821 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002822 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002823 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002824 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002825
Chris Lattnera11ef822007-10-06 06:13:42 +00002826 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2827 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002828}
2829
Chris Lattnercc4287a2009-10-16 02:13:51 +00002830APInt
2831APFloat::convertHalfAPFloatToAPInt() const
2832{
2833 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002834 assert(partCount()==1);
Chris Lattnercc4287a2009-10-16 02:13:51 +00002835
2836 uint32_t myexponent, mysignificand;
2837
2838 if (category==fcNormal) {
2839 myexponent = exponent+15; //bias
2840 mysignificand = (uint32_t)*significandParts();
2841 if (myexponent == 1 && !(mysignificand & 0x400))
2842 myexponent = 0; // denormal
2843 } else if (category==fcZero) {
2844 myexponent = 0;
2845 mysignificand = 0;
2846 } else if (category==fcInfinity) {
Dale Johannesena223aed2009-10-23 04:02:51 +00002847 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002848 mysignificand = 0;
2849 } else {
2850 assert(category == fcNaN && "Unknown category!");
Dale Johannesena223aed2009-10-23 04:02:51 +00002851 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002852 mysignificand = (uint32_t)*significandParts();
2853 }
2854
2855 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2856 (mysignificand & 0x3ff)));
2857}
2858
Dale Johannesena471c2e2007-10-11 18:07:22 +00002859// This function creates an APInt that is just a bit map of the floating
2860// point constant as it would appear in memory. It is not a conversion,
2861// and treating the result as a normal integer is unlikely to be useful.
2862
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002863APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002864APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002865{
Chris Lattnercc4287a2009-10-16 02:13:51 +00002866 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2867 return convertHalfAPFloatToAPInt();
2868
Dan Gohmanb10abe12008-01-29 12:08:20 +00002869 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002870 return convertFloatAPFloatToAPInt();
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002871
Dan Gohmanb10abe12008-01-29 12:08:20 +00002872 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002873 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002874
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002875 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2876 return convertQuadrupleAPFloatToAPInt();
2877
Dan Gohmanb10abe12008-01-29 12:08:20 +00002878 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002879 return convertPPCDoubleDoubleAPFloatToAPInt();
2880
Dan Gohmanb10abe12008-01-29 12:08:20 +00002881 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002882 "unknown format!");
2883 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002884}
2885
Neil Booth4f881702007-09-26 21:33:42 +00002886float
2887APFloat::convertToFloat() const
2888{
Chris Lattnerad785002009-09-24 21:44:20 +00002889 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2890 "Float semantics are not IEEEsingle");
Dale Johannesen7111b022008-10-09 18:53:47 +00002891 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002892 return api.bitsToFloat();
2893}
2894
Neil Booth4f881702007-09-26 21:33:42 +00002895double
2896APFloat::convertToDouble() const
2897{
Chris Lattnerad785002009-09-24 21:44:20 +00002898 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2899 "Float semantics are not IEEEdouble");
Dale Johannesen7111b022008-10-09 18:53:47 +00002900 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002901 return api.bitsToDouble();
2902}
2903
Dale Johannesend3d8ce32008-10-06 18:22:29 +00002904/// Integer bit is explicit in this format. Intel hardware (387 and later)
2905/// does not support these bit patterns:
2906/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2907/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2908/// exponent = 0, integer bit 1 ("pseudodenormal")
2909/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2910/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002911void
Neil Booth4f881702007-09-26 21:33:42 +00002912APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2913{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002914 assert(api.getBitWidth()==80);
2915 uint64_t i1 = api.getRawData()[0];
2916 uint64_t i2 = api.getRawData()[1];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002917 uint64_t myexponent = (i2 & 0x7fff);
2918 uint64_t mysignificand = i1;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002919
2920 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002921 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002922
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002923 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002924 if (myexponent==0 && mysignificand==0) {
2925 // exponent, significand meaningless
2926 category = fcZero;
2927 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2928 // exponent, significand meaningless
2929 category = fcInfinity;
2930 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2931 // exponent meaningless
2932 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002933 significandParts()[0] = mysignificand;
2934 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002935 } else {
2936 category = fcNormal;
2937 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002938 significandParts()[0] = mysignificand;
2939 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002940 if (myexponent==0) // denormal
2941 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00002942 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002943}
2944
2945void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002946APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2947{
2948 assert(api.getBitWidth()==128);
2949 uint64_t i1 = api.getRawData()[0];
2950 uint64_t i2 = api.getRawData()[1];
2951 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2952 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2953 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2954 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2955
2956 initialize(&APFloat::PPCDoubleDouble);
2957 assert(partCount()==2);
2958
Evan Cheng48e8c802008-05-02 21:15:08 +00002959 sign = static_cast<unsigned int>(i1>>63);
2960 sign2 = static_cast<unsigned int>(i2>>63);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002961 if (myexponent==0 && mysignificand==0) {
2962 // exponent, significand meaningless
2963 // exponent2 and significand2 are required to be 0; we don't check
2964 category = fcZero;
2965 } else if (myexponent==0x7ff && mysignificand==0) {
2966 // exponent, significand meaningless
2967 // exponent2 and significand2 are required to be 0; we don't check
2968 category = fcInfinity;
2969 } else if (myexponent==0x7ff && mysignificand!=0) {
2970 // exponent meaningless. So is the whole second word, but keep it
2971 // for determinism.
2972 category = fcNaN;
2973 exponent2 = myexponent2;
2974 significandParts()[0] = mysignificand;
2975 significandParts()[1] = mysignificand2;
2976 } else {
2977 category = fcNormal;
2978 // Note there is no category2; the second word is treated as if it is
2979 // fcNormal, although it might be something else considered by itself.
2980 exponent = myexponent - 1023;
2981 exponent2 = myexponent2 - 1023;
2982 significandParts()[0] = mysignificand;
2983 significandParts()[1] = mysignificand2;
2984 if (myexponent==0) // denormal
2985 exponent = -1022;
2986 else
2987 significandParts()[0] |= 0x10000000000000LL; // integer bit
2988 if (myexponent2==0)
2989 exponent2 = -1022;
2990 else
2991 significandParts()[1] |= 0x10000000000000LL; // integer bit
2992 }
2993}
2994
2995void
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002996APFloat::initFromQuadrupleAPInt(const APInt &api)
2997{
2998 assert(api.getBitWidth()==128);
2999 uint64_t i1 = api.getRawData()[0];
3000 uint64_t i2 = api.getRawData()[1];
3001 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3002 uint64_t mysignificand = i1;
3003 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3004
3005 initialize(&APFloat::IEEEquad);
3006 assert(partCount()==2);
3007
3008 sign = static_cast<unsigned int>(i2>>63);
3009 if (myexponent==0 &&
3010 (mysignificand==0 && mysignificand2==0)) {
3011 // exponent, significand meaningless
3012 category = fcZero;
3013 } else if (myexponent==0x7fff &&
3014 (mysignificand==0 && mysignificand2==0)) {
3015 // exponent, significand meaningless
3016 category = fcInfinity;
3017 } else if (myexponent==0x7fff &&
3018 (mysignificand!=0 || mysignificand2 !=0)) {
3019 // exponent meaningless
3020 category = fcNaN;
3021 significandParts()[0] = mysignificand;
3022 significandParts()[1] = mysignificand2;
3023 } else {
3024 category = fcNormal;
3025 exponent = myexponent - 16383;
3026 significandParts()[0] = mysignificand;
3027 significandParts()[1] = mysignificand2;
3028 if (myexponent==0) // denormal
3029 exponent = -16382;
3030 else
3031 significandParts()[1] |= 0x1000000000000LL; // integer bit
3032 }
3033}
3034
3035void
Neil Booth4f881702007-09-26 21:33:42 +00003036APFloat::initFromDoubleAPInt(const APInt &api)
3037{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003038 assert(api.getBitWidth()==64);
3039 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003040 uint64_t myexponent = (i >> 52) & 0x7ff;
3041 uint64_t mysignificand = i & 0xfffffffffffffLL;
3042
Dale Johannesen343e7702007-08-24 00:56:33 +00003043 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00003044 assert(partCount()==1);
3045
Evan Cheng48e8c802008-05-02 21:15:08 +00003046 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00003047 if (myexponent==0 && mysignificand==0) {
3048 // exponent, significand meaningless
3049 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003050 } else if (myexponent==0x7ff && mysignificand==0) {
3051 // exponent, significand meaningless
3052 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00003053 } else if (myexponent==0x7ff && mysignificand!=0) {
3054 // exponent meaningless
3055 category = fcNaN;
3056 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003057 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00003058 category = fcNormal;
3059 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003060 *significandParts() = mysignificand;
3061 if (myexponent==0) // denormal
3062 exponent = -1022;
3063 else
3064 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00003065 }
Dale Johannesen343e7702007-08-24 00:56:33 +00003066}
3067
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003068void
Neil Booth4f881702007-09-26 21:33:42 +00003069APFloat::initFromFloatAPInt(const APInt & api)
3070{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003071 assert(api.getBitWidth()==32);
3072 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003073 uint32_t myexponent = (i >> 23) & 0xff;
3074 uint32_t mysignificand = i & 0x7fffff;
3075
Dale Johannesen343e7702007-08-24 00:56:33 +00003076 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00003077 assert(partCount()==1);
3078
Dale Johanneseneaf08942007-08-31 04:03:46 +00003079 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00003080 if (myexponent==0 && mysignificand==0) {
3081 // exponent, significand meaningless
3082 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003083 } else if (myexponent==0xff && mysignificand==0) {
3084 // exponent, significand meaningless
3085 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00003086 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00003087 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00003088 category = fcNaN;
3089 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003090 } else {
3091 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00003092 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003093 *significandParts() = mysignificand;
3094 if (myexponent==0) // denormal
3095 exponent = -126;
3096 else
3097 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00003098 }
3099}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003100
Chris Lattnercc4287a2009-10-16 02:13:51 +00003101void
3102APFloat::initFromHalfAPInt(const APInt & api)
3103{
3104 assert(api.getBitWidth()==16);
3105 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesena223aed2009-10-23 04:02:51 +00003106 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00003107 uint32_t mysignificand = i & 0x3ff;
3108
3109 initialize(&APFloat::IEEEhalf);
3110 assert(partCount()==1);
3111
3112 sign = i >> 15;
3113 if (myexponent==0 && mysignificand==0) {
3114 // exponent, significand meaningless
3115 category = fcZero;
3116 } else if (myexponent==0x1f && mysignificand==0) {
3117 // exponent, significand meaningless
3118 category = fcInfinity;
3119 } else if (myexponent==0x1f && mysignificand!=0) {
3120 // sign, exponent, significand meaningless
3121 category = fcNaN;
3122 *significandParts() = mysignificand;
3123 } else {
3124 category = fcNormal;
3125 exponent = myexponent - 15; //bias
3126 *significandParts() = mysignificand;
3127 if (myexponent==0) // denormal
3128 exponent = -14;
3129 else
3130 *significandParts() |= 0x400; // integer bit
3131 }
3132}
3133
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003134/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00003135/// we infer the floating point type from the size of the APInt. The
3136/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3137/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003138void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003139APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003140{
Chris Lattnercc4287a2009-10-16 02:13:51 +00003141 if (api.getBitWidth() == 16)
3142 return initFromHalfAPInt(api);
3143 else if (api.getBitWidth() == 32)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003144 return initFromFloatAPInt(api);
3145 else if (api.getBitWidth()==64)
3146 return initFromDoubleAPInt(api);
3147 else if (api.getBitWidth()==80)
3148 return initFromF80LongDoubleAPInt(api);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003149 else if (api.getBitWidth()==128)
3150 return (isIEEE ?
3151 initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003152 else
Torok Edwinc23197a2009-07-14 16:55:14 +00003153 llvm_unreachable(0);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003154}
3155
John McCall00e65de2009-12-24 08:56:26 +00003156APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3157 APFloat Val(Sem, fcNormal, Negative);
3158
3159 // We want (in interchange format):
3160 // sign = {Negative}
3161 // exponent = 1..10
3162 // significand = 1..1
3163
3164 Val.exponent = Sem.maxExponent; // unbiased
3165
3166 // 1-initialize all bits....
3167 Val.zeroSignificand();
3168 integerPart *significand = Val.significandParts();
3169 unsigned N = partCountForBits(Sem.precision);
3170 for (unsigned i = 0; i != N; ++i)
3171 significand[i] = ~((integerPart) 0);
3172
3173 // ...and then clear the top bits for internal consistency.
3174 significand[N-1]
3175 &= (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1)) - 1;
3176
3177 return Val;
3178}
3179
3180APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3181 APFloat Val(Sem, fcNormal, Negative);
3182
3183 // We want (in interchange format):
3184 // sign = {Negative}
3185 // exponent = 0..0
3186 // significand = 0..01
3187
3188 Val.exponent = Sem.minExponent; // unbiased
3189 Val.zeroSignificand();
3190 Val.significandParts()[0] = 1;
3191 return Val;
3192}
3193
3194APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3195 APFloat Val(Sem, fcNormal, Negative);
3196
3197 // We want (in interchange format):
3198 // sign = {Negative}
3199 // exponent = 0..0
3200 // significand = 10..0
3201
3202 Val.exponent = Sem.minExponent;
3203 Val.zeroSignificand();
3204 Val.significandParts()[partCountForBits(Sem.precision)-1]
3205 |= (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1));
3206
3207 return Val;
3208}
3209
Dale Johannesena471c2e2007-10-11 18:07:22 +00003210APFloat::APFloat(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003211{
Dale Johannesena471c2e2007-10-11 18:07:22 +00003212 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003213}
3214
Neil Booth4f881702007-09-26 21:33:42 +00003215APFloat::APFloat(float f)
3216{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003217 APInt api = APInt(32, 0);
3218 initFromAPInt(api.floatToBits(f));
3219}
3220
Neil Booth4f881702007-09-26 21:33:42 +00003221APFloat::APFloat(double d)
3222{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003223 APInt api = APInt(64, 0);
3224 initFromAPInt(api.doubleToBits(d));
3225}
John McCall00e65de2009-12-24 08:56:26 +00003226
3227namespace {
3228 static void append(SmallVectorImpl<char> &Buffer,
3229 unsigned N, const char *Str) {
3230 unsigned Start = Buffer.size();
3231 Buffer.set_size(Start + N);
3232 memcpy(&Buffer[Start], Str, N);
3233 }
3234
3235 template <unsigned N>
3236 void append(SmallVectorImpl<char> &Buffer, const char (&Str)[N]) {
3237 append(Buffer, N, Str);
3238 }
3239
John McCall003a09c2009-12-24 12:16:56 +00003240 /// Removes data from the given significand until it is no more
3241 /// precise than is required for the desired precision.
3242 void AdjustToPrecision(APInt &significand,
3243 int &exp, unsigned FormatPrecision) {
3244 unsigned bits = significand.getActiveBits();
3245
3246 // 196/59 is a very slight overestimate of lg_2(10).
3247 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3248
3249 if (bits <= bitsRequired) return;
3250
3251 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3252 if (!tensRemovable) return;
3253
3254 exp += tensRemovable;
3255
3256 APInt divisor(significand.getBitWidth(), 1);
3257 APInt powten(significand.getBitWidth(), 10);
3258 while (true) {
3259 if (tensRemovable & 1)
3260 divisor *= powten;
3261 tensRemovable >>= 1;
3262 if (!tensRemovable) break;
3263 powten *= powten;
3264 }
3265
3266 significand = significand.udiv(divisor);
3267
3268 // Truncate the significand down to its active bit count, but
3269 // don't try to drop below 32.
John McCall6a09aff2009-12-24 23:18:09 +00003270 unsigned newPrecision = std::max(32U, significand.getActiveBits());
John McCall003a09c2009-12-24 12:16:56 +00003271 significand.trunc(newPrecision);
3272 }
3273
3274
John McCall00e65de2009-12-24 08:56:26 +00003275 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3276 int &exp, unsigned FormatPrecision) {
3277 unsigned N = buffer.size();
3278 if (N <= FormatPrecision) return;
3279
3280 // The most significant figures are the last ones in the buffer.
3281 unsigned FirstSignificant = N - FormatPrecision;
3282
3283 // Round.
3284 // FIXME: this probably shouldn't use 'round half up'.
3285
3286 // Rounding down is just a truncation, except we also want to drop
3287 // trailing zeros from the new result.
3288 if (buffer[FirstSignificant - 1] < '5') {
3289 while (buffer[FirstSignificant] == '0')
3290 FirstSignificant++;
3291
3292 exp += FirstSignificant;
3293 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3294 return;
3295 }
3296
3297 // Rounding up requires a decimal add-with-carry. If we continue
3298 // the carry, the newly-introduced zeros will just be truncated.
3299 for (unsigned I = FirstSignificant; I != N; ++I) {
3300 if (buffer[I] == '9') {
3301 FirstSignificant++;
3302 } else {
3303 buffer[I]++;
3304 break;
3305 }
3306 }
3307
3308 // If we carried through, we have exactly one digit of precision.
3309 if (FirstSignificant == N) {
3310 exp += FirstSignificant;
3311 buffer.clear();
3312 buffer.push_back('1');
3313 return;
3314 }
3315
3316 exp += FirstSignificant;
3317 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3318 }
3319}
3320
3321void APFloat::toString(SmallVectorImpl<char> &Str,
3322 unsigned FormatPrecision,
3323 unsigned FormatMaxPadding) {
3324 switch (category) {
3325 case fcInfinity:
3326 if (isNegative())
3327 return append(Str, "-Inf");
3328 else
3329 return append(Str, "+Inf");
3330
3331 case fcNaN: return append(Str, "NaN");
3332
3333 case fcZero:
3334 if (isNegative())
3335 Str.push_back('-');
3336
3337 if (!FormatMaxPadding)
3338 append(Str, "0.0E+0");
3339 else
3340 Str.push_back('0');
3341 return;
3342
3343 case fcNormal:
3344 break;
3345 }
3346
3347 if (isNegative())
3348 Str.push_back('-');
3349
3350 // Decompose the number into an APInt and an exponent.
3351 int exp = exponent - ((int) semantics->precision - 1);
3352 APInt significand(semantics->precision,
3353 partCountForBits(semantics->precision),
3354 significandParts());
3355
John McCall6a09aff2009-12-24 23:18:09 +00003356 // Set FormatPrecision if zero. We want to do this before we
3357 // truncate trailing zeros, as those are part of the precision.
3358 if (!FormatPrecision) {
3359 // It's an interesting question whether to use the nominal
3360 // precision or the active precision here for denormals.
3361
3362 // FormatPrecision = ceil(significandBits / lg_2(10))
3363 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3364 }
3365
John McCall00e65de2009-12-24 08:56:26 +00003366 // Ignore trailing binary zeros.
3367 int trailingZeros = significand.countTrailingZeros();
3368 exp += trailingZeros;
3369 significand = significand.lshr(trailingZeros);
3370
3371 // Change the exponent from 2^e to 10^e.
3372 if (exp == 0) {
3373 // Nothing to do.
3374 } else if (exp > 0) {
3375 // Just shift left.
3376 significand.zext(semantics->precision + exp);
3377 significand <<= exp;
3378 exp = 0;
3379 } else { /* exp < 0 */
3380 int texp = -exp;
3381
3382 // We transform this using the identity:
3383 // (N)(2^-e) == (N)(5^e)(10^-e)
3384 // This means we have to multiply N (the significand) by 5^e.
3385 // To avoid overflow, we have to operate on numbers large
3386 // enough to store N * 5^e:
3387 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCall6a09aff2009-12-24 23:18:09 +00003388 // <= semantics->precision + e * 137 / 59
3389 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
3390
3391 unsigned precision = semantics->precision + 137 * texp / 59;
John McCall00e65de2009-12-24 08:56:26 +00003392
3393 // Multiply significand by 5^e.
3394 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
3395 significand.zext(precision);
3396 APInt five_to_the_i(precision, 5);
3397 while (true) {
3398 if (texp & 1) significand *= five_to_the_i;
3399
3400 texp >>= 1;
3401 if (!texp) break;
3402 five_to_the_i *= five_to_the_i;
3403 }
3404 }
3405
John McCall003a09c2009-12-24 12:16:56 +00003406 AdjustToPrecision(significand, exp, FormatPrecision);
3407
John McCall00e65de2009-12-24 08:56:26 +00003408 llvm::SmallVector<char, 256> buffer;
3409
3410 // Fill the buffer.
3411 unsigned precision = significand.getBitWidth();
3412 APInt ten(precision, 10);
3413 APInt digit(precision, 0);
3414
3415 bool inTrail = true;
3416 while (significand != 0) {
3417 // digit <- significand % 10
3418 // significand <- significand / 10
3419 APInt::udivrem(significand, ten, significand, digit);
3420
3421 unsigned d = digit.getZExtValue();
3422
3423 // Drop trailing zeros.
3424 if (inTrail && !d) exp++;
3425 else {
3426 buffer.push_back((char) ('0' + d));
3427 inTrail = false;
3428 }
3429 }
3430
3431 assert(!buffer.empty() && "no characters in buffer!");
3432
3433 // Drop down to FormatPrecision.
3434 // TODO: don't do more precise calculations above than are required.
3435 AdjustToPrecision(buffer, exp, FormatPrecision);
3436
3437 unsigned NDigits = buffer.size();
3438
John McCall6a09aff2009-12-24 23:18:09 +00003439 // Check whether we should use scientific notation.
John McCall00e65de2009-12-24 08:56:26 +00003440 bool FormatScientific;
3441 if (!FormatMaxPadding)
3442 FormatScientific = true;
3443 else {
John McCall00e65de2009-12-24 08:56:26 +00003444 if (exp >= 0) {
John McCall6a09aff2009-12-24 23:18:09 +00003445 // 765e3 --> 765000
3446 // ^^^
3447 // But we shouldn't make the number look more precise than it is.
3448 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3449 NDigits + (unsigned) exp > FormatPrecision);
John McCall00e65de2009-12-24 08:56:26 +00003450 } else {
John McCall6a09aff2009-12-24 23:18:09 +00003451 // Power of the most significant digit.
3452 int MSD = exp + (int) (NDigits - 1);
3453 if (MSD >= 0) {
John McCall00e65de2009-12-24 08:56:26 +00003454 // 765e-2 == 7.65
John McCall6a09aff2009-12-24 23:18:09 +00003455 FormatScientific = false;
John McCall00e65de2009-12-24 08:56:26 +00003456 } else {
3457 // 765e-5 == 0.00765
3458 // ^ ^^
John McCall6a09aff2009-12-24 23:18:09 +00003459 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall00e65de2009-12-24 08:56:26 +00003460 }
3461 }
John McCall00e65de2009-12-24 08:56:26 +00003462 }
3463
3464 // Scientific formatting is pretty straightforward.
3465 if (FormatScientific) {
3466 exp += (NDigits - 1);
3467
3468 Str.push_back(buffer[NDigits-1]);
3469 Str.push_back('.');
3470 if (NDigits == 1)
3471 Str.push_back('0');
3472 else
3473 for (unsigned I = 1; I != NDigits; ++I)
3474 Str.push_back(buffer[NDigits-1-I]);
3475 Str.push_back('E');
3476
3477 Str.push_back(exp >= 0 ? '+' : '-');
3478 if (exp < 0) exp = -exp;
3479 SmallVector<char, 6> expbuf;
3480 do {
3481 expbuf.push_back((char) ('0' + (exp % 10)));
3482 exp /= 10;
3483 } while (exp);
3484 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3485 Str.push_back(expbuf[E-1-I]);
3486 return;
3487 }
3488
3489 // Non-scientific, positive exponents.
3490 if (exp >= 0) {
3491 for (unsigned I = 0; I != NDigits; ++I)
3492 Str.push_back(buffer[NDigits-1-I]);
3493 for (unsigned I = 0; I != (unsigned) exp; ++I)
3494 Str.push_back('0');
3495 return;
3496 }
3497
3498 // Non-scientific, negative exponents.
3499
3500 // The number of digits to the left of the decimal point.
3501 int NWholeDigits = exp + (int) NDigits;
3502
3503 unsigned I = 0;
3504 if (NWholeDigits > 0) {
3505 for (; I != (unsigned) NWholeDigits; ++I)
3506 Str.push_back(buffer[NDigits-I-1]);
3507 Str.push_back('.');
3508 } else {
3509 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3510
3511 Str.push_back('0');
3512 Str.push_back('.');
3513 for (unsigned Z = 1; Z != NZeros; ++Z)
3514 Str.push_back('0');
3515 }
3516
3517 for (; I != NDigits; ++I)
3518 Str.push_back(buffer[NDigits-I-1]);
3519}