blob: 128fee4f01fe8fa2ba3d463684a6e62b15619c26 [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"
Ted Kremenek1f801fa2008-02-11 17:24:50 +000016#include "llvm/ADT/FoldingSet.h"
Dale Johannesend3b51fd2007-08-24 05:08:11 +000017#include "llvm/Support/MathExtras.h"
Chris Lattnerfad86b02008-08-17 07:19:36 +000018#include <cstring>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000019
20using namespace llvm;
21
22#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
23
Neil Bootha30b0ee2007-10-03 22:26:02 +000024/* Assumed in hexadecimal significand parsing, and conversion to
25 hexadecimal strings. */
Chris Lattner9f17eb02008-08-17 04:58:58 +000026#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerb39cdde2007-08-20 22:49:32 +000027COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
28
29namespace llvm {
30
31 /* Represents floating point arithmetic semantics. */
32 struct fltSemantics {
33 /* The largest E such that 2^E is representable; this matches the
34 definition of IEEE 754. */
35 exponent_t maxExponent;
36
37 /* The smallest E such that 2^E is a normalized number; this
38 matches the definition of IEEE 754. */
39 exponent_t minExponent;
40
41 /* Number of bits in the significand. This includes the integer
42 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000043 unsigned int precision;
Neil Boothcaf19d72007-10-14 10:29:28 +000044
45 /* True if arithmetic is supported. */
46 unsigned int arithmeticOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000047 };
48
Neil Boothcaf19d72007-10-14 10:29:28 +000049 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
50 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
51 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
52 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
53 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesena471c2e2007-10-11 18:07:22 +000054
55 // The PowerPC format consists of two doubles. It does not map cleanly
56 // onto the usual format above. For now only storage of constants of
57 // this type is supported, no arithmetic.
Neil Boothcaf19d72007-10-14 10:29:28 +000058 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
Neil Booth96c74712007-10-12 16:02:31 +000059
60 /* A tight upper bound on number of parts required to hold the value
61 pow(5, power) is
62
Neil Booth686700e2007-10-15 15:00:55 +000063 power * 815 / (351 * integerPartWidth) + 1
Neil Booth96c74712007-10-12 16:02:31 +000064
65 However, whilst the result may require only this many parts,
66 because we are multiplying two values to get it, the
67 multiplication may require an extra part with the excess part
68 being zero (consider the trivial case of 1 * 1, tcFullMultiply
69 requires two parts to hold the single-part result). So we add an
70 extra one to guarantee enough space whilst multiplying. */
71 const unsigned int maxExponent = 16383;
72 const unsigned int maxPrecision = 113;
73 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth686700e2007-10-15 15:00:55 +000074 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
75 / (351 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000076}
77
78/* Put a bunch of private, handy routines in an anonymous namespace. */
79namespace {
80
Dan Gohman3bd659b2008-04-10 21:11:47 +000081 static inline unsigned int
Chris Lattnerb39cdde2007-08-20 22:49:32 +000082 partCountForBits(unsigned int bits)
83 {
84 return ((bits) + integerPartWidth - 1) / integerPartWidth;
85 }
86
Neil Booth1870f292007-10-14 10:16:12 +000087 /* Returns 0U-9U. Return values >= 10U are not digits. */
Dan Gohman3bd659b2008-04-10 21:11:47 +000088 static inline unsigned int
Neil Booth1870f292007-10-14 10:16:12 +000089 decDigitValue(unsigned int c)
Chris Lattnerb39cdde2007-08-20 22:49:32 +000090 {
Neil Booth1870f292007-10-14 10:16:12 +000091 return c - '0';
Chris Lattnerb39cdde2007-08-20 22:49:32 +000092 }
93
Dan Gohman3bd659b2008-04-10 21:11:47 +000094 static unsigned int
Neil Booth96c74712007-10-12 16:02:31 +000095 hexDigitValue(unsigned int c)
Chris Lattnerb39cdde2007-08-20 22:49:32 +000096 {
97 unsigned int r;
98
99 r = c - '0';
100 if(r <= 9)
101 return r;
102
103 r = c - 'A';
104 if(r <= 5)
105 return r + 10;
106
107 r = c - 'a';
108 if(r <= 5)
109 return r + 10;
110
111 return -1U;
112 }
113
Dan Gohman3bd659b2008-04-10 21:11:47 +0000114 static inline void
Neil Boothcaf19d72007-10-14 10:29:28 +0000115 assertArithmeticOK(const llvm::fltSemantics &semantics) {
116 assert(semantics.arithmeticOK
117 && "Compile-time arithmetic does not support these semantics");
118 }
119
Evan Cheng88f2d6c2008-11-25 19:00:29 +0000120 static inline bool
121 isArithmeticOk(const llvm::fltSemantics &semantics) {
122 return semantics.arithmeticOK;
123 }
124
Neil Booth1870f292007-10-14 10:16:12 +0000125 /* Return the value of a decimal exponent of the form
126 [+-]ddddddd.
127
128 If the exponent overflows, returns a large exponent with the
129 appropriate sign. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000130 static int
Neil Booth1870f292007-10-14 10:16:12 +0000131 readExponent(const char *p)
132 {
133 bool isNegative;
134 unsigned int absExponent;
135 const unsigned int overlargeExponent = 24000; /* FIXME. */
136
137 isNegative = (*p == '-');
138 if (*p == '-' || *p == '+')
139 p++;
140
141 absExponent = decDigitValue(*p++);
142 assert (absExponent < 10U);
143
144 for (;;) {
145 unsigned int value;
146
147 value = decDigitValue(*p);
148 if (value >= 10U)
149 break;
150
151 p++;
152 value += absExponent * 10;
153 if (absExponent >= overlargeExponent) {
154 absExponent = overlargeExponent;
155 break;
156 }
157 absExponent = value;
158 }
159
160 if (isNegative)
161 return -(int) absExponent;
162 else
163 return (int) absExponent;
164 }
165
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000166 /* This is ugly and needs cleaning up, but I don't immediately see
167 how whilst remaining safe. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000168 static int
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000169 totalExponent(const char *p, int exponentAdjustment)
170 {
Evan Cheng48e8c802008-05-02 21:15:08 +0000171 int unsignedExponent;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000172 bool negative, overflow;
Evan Cheng48e8c802008-05-02 21:15:08 +0000173 int exponent;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000174
175 /* Move past the exponent letter and sign to the digits. */
176 p++;
177 negative = *p == '-';
178 if(*p == '-' || *p == '+')
179 p++;
180
181 unsignedExponent = 0;
182 overflow = false;
183 for(;;) {
184 unsigned int value;
185
Neil Booth1870f292007-10-14 10:16:12 +0000186 value = decDigitValue(*p);
187 if(value >= 10U)
Neil Booth4f881702007-09-26 21:33:42 +0000188 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000189
190 p++;
191 unsignedExponent = unsignedExponent * 10 + value;
192 if(unsignedExponent > 65535)
Neil Booth4f881702007-09-26 21:33:42 +0000193 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000194 }
195
196 if(exponentAdjustment > 65535 || exponentAdjustment < -65536)
197 overflow = true;
198
199 if(!overflow) {
200 exponent = unsignedExponent;
201 if(negative)
Neil Booth4f881702007-09-26 21:33:42 +0000202 exponent = -exponent;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000203 exponent += exponentAdjustment;
204 if(exponent > 65535 || exponent < -65536)
Neil Booth4f881702007-09-26 21:33:42 +0000205 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000206 }
207
208 if(overflow)
209 exponent = negative ? -65536: 65535;
210
211 return exponent;
212 }
213
Dan Gohman3bd659b2008-04-10 21:11:47 +0000214 static const char *
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000215 skipLeadingZeroesAndAnyDot(const char *p, const char **dot)
216 {
217 *dot = 0;
218 while(*p == '0')
219 p++;
220
221 if(*p == '.') {
222 *dot = p++;
223 while(*p == '0')
Neil Booth4f881702007-09-26 21:33:42 +0000224 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000225 }
226
227 return p;
228 }
229
Neil Booth1870f292007-10-14 10:16:12 +0000230 /* Given a normal decimal floating point number of the form
231
232 dddd.dddd[eE][+-]ddd
233
234 where the decimal point and exponent are optional, fill out the
Neil Booth686700e2007-10-15 15:00:55 +0000235 structure D. Exponent is appropriate if the significand is
236 treated as an integer, and normalizedExponent if the significand
237 is taken to have the decimal point after a single leading
238 non-zero digit.
239
Neil Bootha89e45f2007-12-05 13:01:24 +0000240 If the value is zero, V->firstSigDigit points to a non-digit, and
241 the return exponent is zero.
Neil Booth686700e2007-10-15 15:00:55 +0000242 */
Neil Booth1870f292007-10-14 10:16:12 +0000243 struct decimalInfo {
244 const char *firstSigDigit;
245 const char *lastSigDigit;
246 int exponent;
Neil Booth686700e2007-10-15 15:00:55 +0000247 int normalizedExponent;
Neil Booth1870f292007-10-14 10:16:12 +0000248 };
249
Dan Gohman3bd659b2008-04-10 21:11:47 +0000250 static void
Neil Booth1870f292007-10-14 10:16:12 +0000251 interpretDecimal(const char *p, decimalInfo *D)
252 {
253 const char *dot;
254
255 p = skipLeadingZeroesAndAnyDot (p, &dot);
256
257 D->firstSigDigit = p;
258 D->exponent = 0;
Neil Booth686700e2007-10-15 15:00:55 +0000259 D->normalizedExponent = 0;
Neil Booth1870f292007-10-14 10:16:12 +0000260
261 for (;;) {
262 if (*p == '.') {
263 assert(dot == 0);
264 dot = p++;
265 }
266 if (decDigitValue(*p) >= 10U)
267 break;
268 p++;
269 }
270
271 /* If number is all zerooes accept any exponent. */
Neil Boothcc233592007-12-05 13:06:04 +0000272 if (p != D->firstSigDigit) {
Neil Booth1870f292007-10-14 10:16:12 +0000273 if (*p == 'e' || *p == 'E')
274 D->exponent = readExponent(p + 1);
275
276 /* Implied decimal point? */
277 if (!dot)
278 dot = p;
279
280 /* Drop insignificant trailing zeroes. */
281 do
282 do
283 p--;
284 while (*p == '0');
285 while (*p == '.');
286
Neil Booth686700e2007-10-15 15:00:55 +0000287 /* Adjust the exponents for any decimal point. */
Evan Cheng48e8c802008-05-02 21:15:08 +0000288 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
289 D->normalizedExponent = (D->exponent +
290 static_cast<exponent_t>((p - D->firstSigDigit)
291 - (dot > D->firstSigDigit && dot < p)));
Neil Booth1870f292007-10-14 10:16:12 +0000292 }
293
294 D->lastSigDigit = p;
295 }
296
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000297 /* Return the trailing fraction of a hexadecimal number.
298 DIGITVALUE is the first hex digit of the fraction, P points to
299 the next digit. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000300 static lostFraction
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000301 trailingHexadecimalFraction(const char *p, unsigned int digitValue)
302 {
303 unsigned int hexDigit;
304
305 /* If the first trailing digit isn't 0 or 8 we can work out the
306 fraction immediately. */
307 if(digitValue > 8)
308 return lfMoreThanHalf;
309 else if(digitValue < 8 && digitValue > 0)
310 return lfLessThanHalf;
311
312 /* Otherwise we need to find the first non-zero digit. */
313 while(*p == '0')
314 p++;
315
316 hexDigit = hexDigitValue(*p);
317
318 /* If we ran off the end it is exactly zero or one-half, otherwise
319 a little more. */
320 if(hexDigit == -1U)
321 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
322 else
323 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
324 }
325
Neil Boothb7dea4c2007-10-03 15:16:41 +0000326 /* Return the fraction lost were a bignum truncated losing the least
327 significant BITS bits. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000328 static lostFraction
Neil Bootha30b0ee2007-10-03 22:26:02 +0000329 lostFractionThroughTruncation(const integerPart *parts,
Neil Booth4f881702007-09-26 21:33:42 +0000330 unsigned int partCount,
331 unsigned int bits)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000332 {
333 unsigned int lsb;
334
335 lsb = APInt::tcLSB(parts, partCount);
336
337 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
338 if(bits <= lsb)
339 return lfExactlyZero;
340 if(bits == lsb + 1)
341 return lfExactlyHalf;
342 if(bits <= partCount * integerPartWidth
343 && APInt::tcExtractBit(parts, bits - 1))
344 return lfMoreThanHalf;
345
346 return lfLessThanHalf;
347 }
348
349 /* Shift DST right BITS bits noting lost fraction. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000350 static lostFraction
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000351 shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
352 {
353 lostFraction lost_fraction;
354
355 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
356
357 APInt::tcShiftRight(dst, parts, bits);
358
359 return lost_fraction;
360 }
Neil Bootha30b0ee2007-10-03 22:26:02 +0000361
Neil Booth33d4c922007-10-07 08:51:21 +0000362 /* Combine the effect of two lost fractions. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000363 static lostFraction
Neil Booth33d4c922007-10-07 08:51:21 +0000364 combineLostFractions(lostFraction moreSignificant,
365 lostFraction lessSignificant)
366 {
367 if(lessSignificant != lfExactlyZero) {
368 if(moreSignificant == lfExactlyZero)
369 moreSignificant = lfLessThanHalf;
370 else if(moreSignificant == lfExactlyHalf)
371 moreSignificant = lfMoreThanHalf;
372 }
373
374 return moreSignificant;
375 }
Neil Bootha30b0ee2007-10-03 22:26:02 +0000376
Neil Booth96c74712007-10-12 16:02:31 +0000377 /* The error from the true value, in half-ulps, on multiplying two
378 floating point numbers, which differ from the value they
379 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
380 than the returned value.
381
382 See "How to Read Floating Point Numbers Accurately" by William D
383 Clinger. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000384 static unsigned int
Neil Booth96c74712007-10-12 16:02:31 +0000385 HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
386 {
387 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
388
389 if (HUerr1 + HUerr2 == 0)
390 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
391 else
392 return inexactMultiply + 2 * (HUerr1 + HUerr2);
393 }
394
395 /* The number of ulps from the boundary (zero, or half if ISNEAREST)
396 when the least significant BITS are truncated. BITS cannot be
397 zero. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000398 static integerPart
Neil Booth96c74712007-10-12 16:02:31 +0000399 ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
400 {
401 unsigned int count, partBits;
402 integerPart part, boundary;
403
404 assert (bits != 0);
405
406 bits--;
407 count = bits / integerPartWidth;
408 partBits = bits % integerPartWidth + 1;
409
410 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
411
412 if (isNearest)
413 boundary = (integerPart) 1 << (partBits - 1);
414 else
415 boundary = 0;
416
417 if (count == 0) {
418 if (part - boundary <= boundary - part)
419 return part - boundary;
420 else
421 return boundary - part;
422 }
423
424 if (part == boundary) {
425 while (--count)
426 if (parts[count])
427 return ~(integerPart) 0; /* A lot. */
428
429 return parts[0];
430 } else if (part == boundary - 1) {
431 while (--count)
432 if (~parts[count])
433 return ~(integerPart) 0; /* A lot. */
434
435 return -parts[0];
436 }
437
438 return ~(integerPart) 0; /* A lot. */
439 }
440
441 /* Place pow(5, power) in DST, and return the number of parts used.
442 DST must be at least one part larger than size of the answer. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000443 static unsigned int
Neil Booth96c74712007-10-12 16:02:31 +0000444 powerOf5(integerPart *dst, unsigned int power)
445 {
Dan Gohman7c2e4f22008-05-12 16:38:14 +0000446 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
447 15625, 78125 };
Neil Booth96c74712007-10-12 16:02:31 +0000448 static integerPart pow5s[maxPowerOfFiveParts * 2 + 5] = { 78125 * 5 };
449 static unsigned int partsCount[16] = { 1 };
450
451 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
452 unsigned int result;
453
454 assert(power <= maxExponent);
455
456 p1 = dst;
457 p2 = scratch;
458
459 *p1 = firstEightPowers[power & 7];
460 power >>= 3;
461
462 result = 1;
463 pow5 = pow5s;
464
465 for (unsigned int n = 0; power; power >>= 1, n++) {
466 unsigned int pc;
467
468 pc = partsCount[n];
469
470 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
471 if (pc == 0) {
472 pc = partsCount[n - 1];
473 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
474 pc *= 2;
475 if (pow5[pc - 1] == 0)
476 pc--;
477 partsCount[n] = pc;
478 }
479
480 if (power & 1) {
481 integerPart *tmp;
482
483 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
484 result += pc;
485 if (p2[result - 1] == 0)
486 result--;
487
488 /* Now result is in p1 with partsCount parts and p2 is scratch
489 space. */
490 tmp = p1, p1 = p2, p2 = tmp;
491 }
492
493 pow5 += pc;
494 }
495
496 if (p1 != dst)
497 APInt::tcAssign(dst, p1, result);
498
499 return result;
500 }
501
Neil Bootha30b0ee2007-10-03 22:26:02 +0000502 /* Zero at the end to avoid modular arithmetic when adding one; used
503 when rounding up during hexadecimal output. */
504 static const char hexDigitsLower[] = "0123456789abcdef0";
505 static const char hexDigitsUpper[] = "0123456789ABCDEF0";
506 static const char infinityL[] = "infinity";
507 static const char infinityU[] = "INFINITY";
508 static const char NaNL[] = "nan";
509 static const char NaNU[] = "NAN";
510
511 /* Write out an integerPart in hexadecimal, starting with the most
512 significant nibble. Write out exactly COUNT hexdigits, return
513 COUNT. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000514 static unsigned int
Neil Bootha30b0ee2007-10-03 22:26:02 +0000515 partAsHex (char *dst, integerPart part, unsigned int count,
516 const char *hexDigitChars)
517 {
518 unsigned int result = count;
519
520 assert (count != 0 && count <= integerPartWidth / 4);
521
522 part >>= (integerPartWidth - 4 * count);
523 while (count--) {
524 dst[count] = hexDigitChars[part & 0xf];
525 part >>= 4;
526 }
527
528 return result;
529 }
530
Neil Booth92f7e8d2007-10-06 07:29:25 +0000531 /* Write out an unsigned decimal integer. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000532 static char *
Neil Booth92f7e8d2007-10-06 07:29:25 +0000533 writeUnsignedDecimal (char *dst, unsigned int n)
Neil Bootha30b0ee2007-10-03 22:26:02 +0000534 {
Neil Booth92f7e8d2007-10-06 07:29:25 +0000535 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000536
Neil Booth92f7e8d2007-10-06 07:29:25 +0000537 p = buff;
538 do
539 *p++ = '0' + n % 10;
540 while (n /= 10);
541
542 do
543 *dst++ = *--p;
544 while (p != buff);
545
546 return dst;
547 }
548
549 /* Write out a signed decimal integer. */
Dan Gohman3bd659b2008-04-10 21:11:47 +0000550 static char *
Neil Booth92f7e8d2007-10-06 07:29:25 +0000551 writeSignedDecimal (char *dst, int value)
552 {
553 if (value < 0) {
Neil Bootha30b0ee2007-10-03 22:26:02 +0000554 *dst++ = '-';
Neil Booth92f7e8d2007-10-06 07:29:25 +0000555 dst = writeUnsignedDecimal(dst, -(unsigned) value);
556 } else
557 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000558
559 return dst;
560 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000561}
562
563/* Constructors. */
564void
565APFloat::initialize(const fltSemantics *ourSemantics)
566{
567 unsigned int count;
568
569 semantics = ourSemantics;
570 count = partCount();
571 if(count > 1)
572 significand.parts = new integerPart[count];
573}
574
575void
576APFloat::freeSignificand()
577{
578 if(partCount() > 1)
579 delete [] significand.parts;
580}
581
582void
583APFloat::assign(const APFloat &rhs)
584{
585 assert(semantics == rhs.semantics);
586
587 sign = rhs.sign;
588 category = rhs.category;
589 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000590 sign2 = rhs.sign2;
591 exponent2 = rhs.exponent2;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000592 if(category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000593 copySignificand(rhs);
594}
595
596void
597APFloat::copySignificand(const APFloat &rhs)
598{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000599 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000600 assert(rhs.partCount() >= partCount());
601
602 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000603 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000604}
605
Neil Boothe5e01942007-10-14 10:39:51 +0000606/* Make this number a NaN, with an arbitrary but deterministic value
607 for the significand. */
608void
609APFloat::makeNaN(void)
610{
611 category = fcNaN;
612 APInt::tcSet(significandParts(), ~0U, partCount());
613}
614
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000615APFloat &
616APFloat::operator=(const APFloat &rhs)
617{
618 if(this != &rhs) {
619 if(semantics != rhs.semantics) {
620 freeSignificand();
621 initialize(rhs.semantics);
622 }
623 assign(rhs);
624 }
625
626 return *this;
627}
628
Dale Johannesen343e7702007-08-24 00:56:33 +0000629bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000630APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000631 if (this == &rhs)
632 return true;
633 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000634 category != rhs.category ||
635 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000636 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000637 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000638 sign2 != rhs.sign2)
639 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000640 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000641 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000642 else if (category==fcNormal && exponent!=rhs.exponent)
643 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000644 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000645 exponent2!=rhs.exponent2)
646 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000647 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000648 int i= partCount();
649 const integerPart* p=significandParts();
650 const integerPart* q=rhs.significandParts();
651 for (; i>0; i--, p++, q++) {
652 if (*p != *q)
653 return false;
654 }
655 return true;
656 }
657}
658
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000659APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
660{
Neil Boothcaf19d72007-10-14 10:29:28 +0000661 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000662 initialize(&ourSemantics);
663 sign = 0;
664 zeroSignificand();
665 exponent = ourSemantics.precision - 1;
666 significandParts()[0] = value;
667 normalize(rmNearestTiesToEven, lfExactlyZero);
668}
669
670APFloat::APFloat(const fltSemantics &ourSemantics,
Neil Booth4f881702007-09-26 21:33:42 +0000671 fltCategory ourCategory, bool negative)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000672{
Neil Boothcaf19d72007-10-14 10:29:28 +0000673 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000674 initialize(&ourSemantics);
675 category = ourCategory;
676 sign = negative;
677 if(category == fcNormal)
678 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000679 else if (ourCategory == fcNaN)
680 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000681}
682
683APFloat::APFloat(const fltSemantics &ourSemantics, const char *text)
684{
Neil Boothcaf19d72007-10-14 10:29:28 +0000685 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000686 initialize(&ourSemantics);
687 convertFromString(text, rmNearestTiesToEven);
688}
689
690APFloat::APFloat(const APFloat &rhs)
691{
692 initialize(rhs.semantics);
693 assign(rhs);
694}
695
696APFloat::~APFloat()
697{
698 freeSignificand();
699}
700
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000701// Profile - This method 'profiles' an APFloat for use with FoldingSet.
702void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000703 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000704}
705
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000706unsigned int
707APFloat::partCount() const
708{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000709 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000710}
711
712unsigned int
713APFloat::semanticsPrecision(const fltSemantics &semantics)
714{
715 return semantics.precision;
716}
717
718const integerPart *
719APFloat::significandParts() const
720{
721 return const_cast<APFloat *>(this)->significandParts();
722}
723
724integerPart *
725APFloat::significandParts()
726{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000727 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000728
729 if(partCount() > 1)
730 return significand.parts;
731 else
732 return &significand.part;
733}
734
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000735void
736APFloat::zeroSignificand()
737{
738 category = fcNormal;
739 APInt::tcSet(significandParts(), 0, partCount());
740}
741
742/* Increment an fcNormal floating point number's significand. */
743void
744APFloat::incrementSignificand()
745{
746 integerPart carry;
747
748 carry = APInt::tcIncrement(significandParts(), partCount());
749
750 /* Our callers should never cause us to overflow. */
751 assert(carry == 0);
752}
753
754/* Add the significand of the RHS. Returns the carry flag. */
755integerPart
756APFloat::addSignificand(const APFloat &rhs)
757{
758 integerPart *parts;
759
760 parts = significandParts();
761
762 assert(semantics == rhs.semantics);
763 assert(exponent == rhs.exponent);
764
765 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
766}
767
768/* Subtract the significand of the RHS with a borrow flag. Returns
769 the borrow flag. */
770integerPart
771APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
772{
773 integerPart *parts;
774
775 parts = significandParts();
776
777 assert(semantics == rhs.semantics);
778 assert(exponent == rhs.exponent);
779
780 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000781 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000782}
783
784/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
785 on to the full-precision result of the multiplication. Returns the
786 lost fraction. */
787lostFraction
788APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
789{
Neil Booth4f881702007-09-26 21:33:42 +0000790 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000791 unsigned int partsCount, newPartsCount, precision;
792 integerPart *lhsSignificand;
793 integerPart scratch[4];
794 integerPart *fullSignificand;
795 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000796 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000797
798 assert(semantics == rhs.semantics);
799
800 precision = semantics->precision;
801 newPartsCount = partCountForBits(precision * 2);
802
803 if(newPartsCount > 4)
804 fullSignificand = new integerPart[newPartsCount];
805 else
806 fullSignificand = scratch;
807
808 lhsSignificand = significandParts();
809 partsCount = partCount();
810
811 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000812 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000813
814 lost_fraction = lfExactlyZero;
815 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
816 exponent += rhs.exponent;
817
818 if(addend) {
819 Significand savedSignificand = significand;
820 const fltSemantics *savedSemantics = semantics;
821 fltSemantics extendedSemantics;
822 opStatus status;
823 unsigned int extendedPrecision;
824
825 /* Normalize our MSB. */
826 extendedPrecision = precision + precision - 1;
827 if(omsb != extendedPrecision)
828 {
Neil Booth4f881702007-09-26 21:33:42 +0000829 APInt::tcShiftLeft(fullSignificand, newPartsCount,
830 extendedPrecision - omsb);
831 exponent -= extendedPrecision - omsb;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000832 }
833
834 /* Create new semantics. */
835 extendedSemantics = *semantics;
836 extendedSemantics.precision = extendedPrecision;
837
838 if(newPartsCount == 1)
839 significand.part = fullSignificand[0];
840 else
841 significand.parts = fullSignificand;
842 semantics = &extendedSemantics;
843
844 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000845 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000846 assert(status == opOK);
847 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
848
849 /* Restore our state. */
850 if(newPartsCount == 1)
851 fullSignificand[0] = significand.part;
852 significand = savedSignificand;
853 semantics = savedSemantics;
854
855 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
856 }
857
858 exponent -= (precision - 1);
859
860 if(omsb > precision) {
861 unsigned int bits, significantParts;
862 lostFraction lf;
863
864 bits = omsb - precision;
865 significantParts = partCountForBits(omsb);
866 lf = shiftRight(fullSignificand, significantParts, bits);
867 lost_fraction = combineLostFractions(lf, lost_fraction);
868 exponent += bits;
869 }
870
871 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
872
873 if(newPartsCount > 4)
874 delete [] fullSignificand;
875
876 return lost_fraction;
877}
878
879/* Multiply the significands of LHS and RHS to DST. */
880lostFraction
881APFloat::divideSignificand(const APFloat &rhs)
882{
883 unsigned int bit, i, partsCount;
884 const integerPart *rhsSignificand;
885 integerPart *lhsSignificand, *dividend, *divisor;
886 integerPart scratch[4];
887 lostFraction lost_fraction;
888
889 assert(semantics == rhs.semantics);
890
891 lhsSignificand = significandParts();
892 rhsSignificand = rhs.significandParts();
893 partsCount = partCount();
894
895 if(partsCount > 2)
896 dividend = new integerPart[partsCount * 2];
897 else
898 dividend = scratch;
899
900 divisor = dividend + partsCount;
901
902 /* Copy the dividend and divisor as they will be modified in-place. */
903 for(i = 0; i < partsCount; i++) {
904 dividend[i] = lhsSignificand[i];
905 divisor[i] = rhsSignificand[i];
906 lhsSignificand[i] = 0;
907 }
908
909 exponent -= rhs.exponent;
910
911 unsigned int precision = semantics->precision;
912
913 /* Normalize the divisor. */
914 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
915 if(bit) {
916 exponent += bit;
917 APInt::tcShiftLeft(divisor, partsCount, bit);
918 }
919
920 /* Normalize the dividend. */
921 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
922 if(bit) {
923 exponent -= bit;
924 APInt::tcShiftLeft(dividend, partsCount, bit);
925 }
926
Neil Booth96c74712007-10-12 16:02:31 +0000927 /* Ensure the dividend >= divisor initially for the loop below.
928 Incidentally, this means that the division loop below is
929 guaranteed to set the integer bit to one. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000930 if(APInt::tcCompare(dividend, divisor, partsCount) < 0) {
931 exponent--;
932 APInt::tcShiftLeft(dividend, partsCount, 1);
933 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
934 }
935
936 /* Long division. */
937 for(bit = precision; bit; bit -= 1) {
938 if(APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
939 APInt::tcSubtract(dividend, divisor, 0, partsCount);
940 APInt::tcSetBit(lhsSignificand, bit - 1);
941 }
942
943 APInt::tcShiftLeft(dividend, partsCount, 1);
944 }
945
946 /* Figure out the lost fraction. */
947 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
948
949 if(cmp > 0)
950 lost_fraction = lfMoreThanHalf;
951 else if(cmp == 0)
952 lost_fraction = lfExactlyHalf;
953 else if(APInt::tcIsZero(dividend, partsCount))
954 lost_fraction = lfExactlyZero;
955 else
956 lost_fraction = lfLessThanHalf;
957
958 if(partsCount > 2)
959 delete [] dividend;
960
961 return lost_fraction;
962}
963
964unsigned int
965APFloat::significandMSB() const
966{
967 return APInt::tcMSB(significandParts(), partCount());
968}
969
970unsigned int
971APFloat::significandLSB() const
972{
973 return APInt::tcLSB(significandParts(), partCount());
974}
975
976/* Note that a zero result is NOT normalized to fcZero. */
977lostFraction
978APFloat::shiftSignificandRight(unsigned int bits)
979{
980 /* Our exponent should not overflow. */
981 assert((exponent_t) (exponent + bits) >= exponent);
982
983 exponent += bits;
984
985 return shiftRight(significandParts(), partCount(), bits);
986}
987
988/* Shift the significand left BITS bits, subtract BITS from its exponent. */
989void
990APFloat::shiftSignificandLeft(unsigned int bits)
991{
992 assert(bits < semantics->precision);
993
994 if(bits) {
995 unsigned int partsCount = partCount();
996
997 APInt::tcShiftLeft(significandParts(), partsCount, bits);
998 exponent -= bits;
999
1000 assert(!APInt::tcIsZero(significandParts(), partsCount));
1001 }
1002}
1003
1004APFloat::cmpResult
1005APFloat::compareAbsoluteValue(const APFloat &rhs) const
1006{
1007 int compare;
1008
1009 assert(semantics == rhs.semantics);
1010 assert(category == fcNormal);
1011 assert(rhs.category == fcNormal);
1012
1013 compare = exponent - rhs.exponent;
1014
1015 /* If exponents are equal, do an unsigned bignum comparison of the
1016 significands. */
1017 if(compare == 0)
1018 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001019 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001020
1021 if(compare > 0)
1022 return cmpGreaterThan;
1023 else if(compare < 0)
1024 return cmpLessThan;
1025 else
1026 return cmpEqual;
1027}
1028
1029/* Handle overflow. Sign is preserved. We either become infinity or
1030 the largest finite number. */
1031APFloat::opStatus
1032APFloat::handleOverflow(roundingMode rounding_mode)
1033{
1034 /* Infinity? */
1035 if(rounding_mode == rmNearestTiesToEven
1036 || rounding_mode == rmNearestTiesToAway
1037 || (rounding_mode == rmTowardPositive && !sign)
1038 || (rounding_mode == rmTowardNegative && sign))
1039 {
1040 category = fcInfinity;
1041 return (opStatus) (opOverflow | opInexact);
1042 }
1043
1044 /* Otherwise we become the largest finite number. */
1045 category = fcNormal;
1046 exponent = semantics->maxExponent;
1047 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001048 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001049
1050 return opInexact;
1051}
1052
Neil Boothb7dea4c2007-10-03 15:16:41 +00001053/* Returns TRUE if, when truncating the current number, with BIT the
1054 new LSB, with the given lost fraction and rounding mode, the result
1055 would need to be rounded away from zero (i.e., by increasing the
1056 signficand). This routine must work for fcZero of both signs, and
1057 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001058bool
1059APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001060 lostFraction lost_fraction,
1061 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001062{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001063 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001064 assert(category == fcNormal || category == fcZero);
1065
Neil Boothb7dea4c2007-10-03 15:16:41 +00001066 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001067 assert(lost_fraction != lfExactlyZero);
1068
1069 switch(rounding_mode) {
1070 default:
1071 assert(0);
1072
1073 case rmNearestTiesToAway:
1074 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1075
1076 case rmNearestTiesToEven:
1077 if(lost_fraction == lfMoreThanHalf)
1078 return true;
1079
1080 /* Our zeroes don't have a significand to test. */
1081 if(lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001082 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001083
1084 return false;
1085
1086 case rmTowardZero:
1087 return false;
1088
1089 case rmTowardPositive:
1090 return sign == false;
1091
1092 case rmTowardNegative:
1093 return sign == true;
1094 }
1095}
1096
1097APFloat::opStatus
1098APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001099 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001100{
Neil Booth4f881702007-09-26 21:33:42 +00001101 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001102 int exponentChange;
1103
1104 if(category != fcNormal)
1105 return opOK;
1106
1107 /* Before rounding normalize the exponent of fcNormal numbers. */
1108 omsb = significandMSB() + 1;
1109
1110 if(omsb) {
1111 /* OMSB is numbered from 1. We want to place it in the integer
1112 bit numbered PRECISON if possible, with a compensating change in
1113 the exponent. */
1114 exponentChange = omsb - semantics->precision;
1115
1116 /* If the resulting exponent is too high, overflow according to
1117 the rounding mode. */
1118 if(exponent + exponentChange > semantics->maxExponent)
1119 return handleOverflow(rounding_mode);
1120
1121 /* Subnormal numbers have exponent minExponent, and their MSB
1122 is forced based on that. */
1123 if(exponent + exponentChange < semantics->minExponent)
1124 exponentChange = semantics->minExponent - exponent;
1125
1126 /* Shifting left is easy as we don't lose precision. */
1127 if(exponentChange < 0) {
1128 assert(lost_fraction == lfExactlyZero);
1129
1130 shiftSignificandLeft(-exponentChange);
1131
1132 return opOK;
1133 }
1134
1135 if(exponentChange > 0) {
1136 lostFraction lf;
1137
1138 /* Shift right and capture any new lost fraction. */
1139 lf = shiftSignificandRight(exponentChange);
1140
1141 lost_fraction = combineLostFractions(lf, lost_fraction);
1142
1143 /* Keep OMSB up-to-date. */
1144 if(omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001145 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001146 else
Neil Booth4f881702007-09-26 21:33:42 +00001147 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001148 }
1149 }
1150
1151 /* Now round the number according to rounding_mode given the lost
1152 fraction. */
1153
1154 /* As specified in IEEE 754, since we do not trap we do not report
1155 underflow for exact results. */
1156 if(lost_fraction == lfExactlyZero) {
1157 /* Canonicalize zeroes. */
1158 if(omsb == 0)
1159 category = fcZero;
1160
1161 return opOK;
1162 }
1163
1164 /* Increment the significand if we're rounding away from zero. */
Neil Boothb7dea4c2007-10-03 15:16:41 +00001165 if(roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001166 if(omsb == 0)
1167 exponent = semantics->minExponent;
1168
1169 incrementSignificand();
1170 omsb = significandMSB() + 1;
1171
1172 /* Did the significand increment overflow? */
1173 if(omsb == (unsigned) semantics->precision + 1) {
1174 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001175 significand right one. However if we already have the
1176 maximum exponent we overflow to infinity. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001177 if(exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001178 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001179
Neil Booth4f881702007-09-26 21:33:42 +00001180 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001181 }
1182
1183 shiftSignificandRight(1);
1184
1185 return opInexact;
1186 }
1187 }
1188
1189 /* The normal case - we were and are not denormal, and any
1190 significand increment above didn't overflow. */
1191 if(omsb == semantics->precision)
1192 return opInexact;
1193
1194 /* We have a non-zero denormal. */
1195 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001196
1197 /* Canonicalize zeroes. */
1198 if(omsb == 0)
1199 category = fcZero;
1200
1201 /* The fcZero case is a denormal that underflowed to zero. */
1202 return (opStatus) (opUnderflow | opInexact);
1203}
1204
1205APFloat::opStatus
1206APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1207{
1208 switch(convolve(category, rhs.category)) {
1209 default:
1210 assert(0);
1211
Dale Johanneseneaf08942007-08-31 04:03:46 +00001212 case convolve(fcNaN, fcZero):
1213 case convolve(fcNaN, fcNormal):
1214 case convolve(fcNaN, fcInfinity):
1215 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001216 case convolve(fcNormal, fcZero):
1217 case convolve(fcInfinity, fcNormal):
1218 case convolve(fcInfinity, fcZero):
1219 return opOK;
1220
Dale Johanneseneaf08942007-08-31 04:03:46 +00001221 case convolve(fcZero, fcNaN):
1222 case convolve(fcNormal, fcNaN):
1223 case convolve(fcInfinity, fcNaN):
1224 category = fcNaN;
1225 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001226 return opOK;
1227
1228 case convolve(fcNormal, fcInfinity):
1229 case convolve(fcZero, fcInfinity):
1230 category = fcInfinity;
1231 sign = rhs.sign ^ subtract;
1232 return opOK;
1233
1234 case convolve(fcZero, fcNormal):
1235 assign(rhs);
1236 sign = rhs.sign ^ subtract;
1237 return opOK;
1238
1239 case convolve(fcZero, fcZero):
1240 /* Sign depends on rounding mode; handled by caller. */
1241 return opOK;
1242
1243 case convolve(fcInfinity, fcInfinity):
1244 /* Differently signed infinities can only be validly
1245 subtracted. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001246 if((sign ^ rhs.sign) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001247 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001248 return opInvalidOp;
1249 }
1250
1251 return opOK;
1252
1253 case convolve(fcNormal, fcNormal):
1254 return opDivByZero;
1255 }
1256}
1257
1258/* Add or subtract two normal numbers. */
1259lostFraction
1260APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1261{
1262 integerPart carry;
1263 lostFraction lost_fraction;
1264 int bits;
1265
1266 /* Determine if the operation on the absolute values is effectively
1267 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001268 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001269
1270 /* Are we bigger exponent-wise than the RHS? */
1271 bits = exponent - rhs.exponent;
1272
1273 /* Subtraction is more subtle than one might naively expect. */
1274 if(subtract) {
1275 APFloat temp_rhs(rhs);
1276 bool reverse;
1277
Chris Lattnerada530b2007-08-24 03:02:34 +00001278 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001279 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1280 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001281 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001282 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1283 shiftSignificandLeft(1);
1284 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001285 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001286 lost_fraction = shiftSignificandRight(-bits - 1);
1287 temp_rhs.shiftSignificandLeft(1);
1288 reverse = true;
1289 }
1290
Chris Lattnerada530b2007-08-24 03:02:34 +00001291 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001292 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001293 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001294 copySignificand(temp_rhs);
1295 sign = !sign;
1296 } else {
1297 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001298 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001299 }
1300
1301 /* Invert the lost fraction - it was on the RHS and
1302 subtracted. */
1303 if(lost_fraction == lfLessThanHalf)
1304 lost_fraction = lfMoreThanHalf;
1305 else if(lost_fraction == lfMoreThanHalf)
1306 lost_fraction = lfLessThanHalf;
1307
1308 /* The code above is intended to ensure that no borrow is
1309 necessary. */
1310 assert(!carry);
1311 } else {
1312 if(bits > 0) {
1313 APFloat temp_rhs(rhs);
1314
1315 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1316 carry = addSignificand(temp_rhs);
1317 } else {
1318 lost_fraction = shiftSignificandRight(-bits);
1319 carry = addSignificand(rhs);
1320 }
1321
1322 /* We have a guard bit; generating a carry cannot happen. */
1323 assert(!carry);
1324 }
1325
1326 return lost_fraction;
1327}
1328
1329APFloat::opStatus
1330APFloat::multiplySpecials(const APFloat &rhs)
1331{
1332 switch(convolve(category, rhs.category)) {
1333 default:
1334 assert(0);
1335
Dale Johanneseneaf08942007-08-31 04:03:46 +00001336 case convolve(fcNaN, fcZero):
1337 case convolve(fcNaN, fcNormal):
1338 case convolve(fcNaN, fcInfinity):
1339 case convolve(fcNaN, fcNaN):
1340 return opOK;
1341
1342 case convolve(fcZero, fcNaN):
1343 case convolve(fcNormal, fcNaN):
1344 case convolve(fcInfinity, fcNaN):
1345 category = fcNaN;
1346 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001347 return opOK;
1348
1349 case convolve(fcNormal, fcInfinity):
1350 case convolve(fcInfinity, fcNormal):
1351 case convolve(fcInfinity, fcInfinity):
1352 category = fcInfinity;
1353 return opOK;
1354
1355 case convolve(fcZero, fcNormal):
1356 case convolve(fcNormal, fcZero):
1357 case convolve(fcZero, fcZero):
1358 category = fcZero;
1359 return opOK;
1360
1361 case convolve(fcZero, fcInfinity):
1362 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001363 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001364 return opInvalidOp;
1365
1366 case convolve(fcNormal, fcNormal):
1367 return opOK;
1368 }
1369}
1370
1371APFloat::opStatus
1372APFloat::divideSpecials(const APFloat &rhs)
1373{
1374 switch(convolve(category, rhs.category)) {
1375 default:
1376 assert(0);
1377
Dale Johanneseneaf08942007-08-31 04:03:46 +00001378 case convolve(fcNaN, fcZero):
1379 case convolve(fcNaN, fcNormal):
1380 case convolve(fcNaN, fcInfinity):
1381 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001382 case convolve(fcInfinity, fcZero):
1383 case convolve(fcInfinity, fcNormal):
1384 case convolve(fcZero, fcInfinity):
1385 case convolve(fcZero, fcNormal):
1386 return opOK;
1387
Dale Johanneseneaf08942007-08-31 04:03:46 +00001388 case convolve(fcZero, fcNaN):
1389 case convolve(fcNormal, fcNaN):
1390 case convolve(fcInfinity, fcNaN):
1391 category = fcNaN;
1392 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001393 return opOK;
1394
1395 case convolve(fcNormal, fcInfinity):
1396 category = fcZero;
1397 return opOK;
1398
1399 case convolve(fcNormal, fcZero):
1400 category = fcInfinity;
1401 return opDivByZero;
1402
1403 case convolve(fcInfinity, fcInfinity):
1404 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001405 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001406 return opInvalidOp;
1407
1408 case convolve(fcNormal, fcNormal):
1409 return opOK;
1410 }
1411}
1412
1413/* Change sign. */
1414void
1415APFloat::changeSign()
1416{
1417 /* Look mummy, this one's easy. */
1418 sign = !sign;
1419}
1420
Dale Johannesene15c2db2007-08-31 23:35:31 +00001421void
1422APFloat::clearSign()
1423{
1424 /* So is this one. */
1425 sign = 0;
1426}
1427
1428void
1429APFloat::copySign(const APFloat &rhs)
1430{
1431 /* And this one. */
1432 sign = rhs.sign;
1433}
1434
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001435/* Normalized addition or subtraction. */
1436APFloat::opStatus
1437APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001438 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001439{
1440 opStatus fs;
1441
Neil Boothcaf19d72007-10-14 10:29:28 +00001442 assertArithmeticOK(*semantics);
1443
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001444 fs = addOrSubtractSpecials(rhs, subtract);
1445
1446 /* This return code means it was not a simple case. */
1447 if(fs == opDivByZero) {
1448 lostFraction lost_fraction;
1449
1450 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1451 fs = normalize(rounding_mode, lost_fraction);
1452
1453 /* Can only be zero if we lost no fraction. */
1454 assert(category != fcZero || lost_fraction == lfExactlyZero);
1455 }
1456
1457 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1458 positive zero unless rounding to minus infinity, except that
1459 adding two like-signed zeroes gives that zero. */
1460 if(category == fcZero) {
1461 if(rhs.category != fcZero || (sign == rhs.sign) == subtract)
1462 sign = (rounding_mode == rmTowardNegative);
1463 }
1464
1465 return fs;
1466}
1467
1468/* Normalized addition. */
1469APFloat::opStatus
1470APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1471{
1472 return addOrSubtract(rhs, rounding_mode, false);
1473}
1474
1475/* Normalized subtraction. */
1476APFloat::opStatus
1477APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1478{
1479 return addOrSubtract(rhs, rounding_mode, true);
1480}
1481
1482/* Normalized multiply. */
1483APFloat::opStatus
1484APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1485{
1486 opStatus fs;
1487
Neil Boothcaf19d72007-10-14 10:29:28 +00001488 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001489 sign ^= rhs.sign;
1490 fs = multiplySpecials(rhs);
1491
1492 if(category == fcNormal) {
1493 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1494 fs = normalize(rounding_mode, lost_fraction);
1495 if(lost_fraction != lfExactlyZero)
1496 fs = (opStatus) (fs | opInexact);
1497 }
1498
1499 return fs;
1500}
1501
1502/* Normalized divide. */
1503APFloat::opStatus
1504APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1505{
1506 opStatus fs;
1507
Neil Boothcaf19d72007-10-14 10:29:28 +00001508 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001509 sign ^= rhs.sign;
1510 fs = divideSpecials(rhs);
1511
1512 if(category == fcNormal) {
1513 lostFraction lost_fraction = divideSignificand(rhs);
1514 fs = normalize(rounding_mode, lost_fraction);
1515 if(lost_fraction != lfExactlyZero)
1516 fs = (opStatus) (fs | opInexact);
1517 }
1518
1519 return fs;
1520}
1521
Neil Bootha30b0ee2007-10-03 22:26:02 +00001522/* Normalized remainder. This is not currently doing TRT. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001523APFloat::opStatus
1524APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1525{
1526 opStatus fs;
1527 APFloat V = *this;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001528 unsigned int origSign = sign;
Neil Boothcaf19d72007-10-14 10:29:28 +00001529
1530 assertArithmeticOK(*semantics);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001531 fs = V.divide(rhs, rmNearestTiesToEven);
1532 if (fs == opDivByZero)
1533 return fs;
1534
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001535 int parts = partCount();
1536 integerPart *x = new integerPart[parts];
Dale Johannesen23a98552008-10-09 23:00:39 +00001537 bool ignored;
Neil Booth4f881702007-09-26 21:33:42 +00001538 fs = V.convertToInteger(x, parts * integerPartWidth, true,
Dale Johannesen23a98552008-10-09 23:00:39 +00001539 rmNearestTiesToEven, &ignored);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001540 if (fs==opInvalidOp)
1541 return fs;
1542
Neil Boothccf596a2007-10-07 11:45:55 +00001543 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1544 rmNearestTiesToEven);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001545 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001546
Dale Johannesene15c2db2007-08-31 23:35:31 +00001547 fs = V.multiply(rhs, rounding_mode);
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001548 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1549
Dale Johannesene15c2db2007-08-31 23:35:31 +00001550 fs = subtract(V, rounding_mode);
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001551 assert(fs==opOK || fs==opInexact); // likewise
1552
1553 if (isZero())
1554 sign = origSign; // IEEE754 requires this
1555 delete[] x;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001556 return fs;
1557}
1558
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001559/* Normalized fused-multiply-add. */
1560APFloat::opStatus
1561APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001562 const APFloat &addend,
1563 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001564{
1565 opStatus fs;
1566
Neil Boothcaf19d72007-10-14 10:29:28 +00001567 assertArithmeticOK(*semantics);
1568
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001569 /* Post-multiplication sign, before addition. */
1570 sign ^= multiplicand.sign;
1571
1572 /* If and only if all arguments are normal do we need to do an
1573 extended-precision calculation. */
1574 if(category == fcNormal
1575 && multiplicand.category == fcNormal
1576 && addend.category == fcNormal) {
1577 lostFraction lost_fraction;
1578
1579 lost_fraction = multiplySignificand(multiplicand, &addend);
1580 fs = normalize(rounding_mode, lost_fraction);
1581 if(lost_fraction != lfExactlyZero)
1582 fs = (opStatus) (fs | opInexact);
1583
1584 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1585 positive zero unless rounding to minus infinity, except that
1586 adding two like-signed zeroes gives that zero. */
1587 if(category == fcZero && sign != addend.sign)
1588 sign = (rounding_mode == rmTowardNegative);
1589 } else {
1590 fs = multiplySpecials(multiplicand);
1591
1592 /* FS can only be opOK or opInvalidOp. There is no more work
1593 to do in the latter case. The IEEE-754R standard says it is
1594 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001595 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001596
1597 If we need to do the addition we can do so with normal
1598 precision. */
1599 if(fs == opOK)
1600 fs = addOrSubtract(addend, rounding_mode, false);
1601 }
1602
1603 return fs;
1604}
1605
1606/* Comparison requires normalized numbers. */
1607APFloat::cmpResult
1608APFloat::compare(const APFloat &rhs) const
1609{
1610 cmpResult result;
1611
Neil Boothcaf19d72007-10-14 10:29:28 +00001612 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001613 assert(semantics == rhs.semantics);
1614
1615 switch(convolve(category, rhs.category)) {
1616 default:
1617 assert(0);
1618
Dale Johanneseneaf08942007-08-31 04:03:46 +00001619 case convolve(fcNaN, fcZero):
1620 case convolve(fcNaN, fcNormal):
1621 case convolve(fcNaN, fcInfinity):
1622 case convolve(fcNaN, fcNaN):
1623 case convolve(fcZero, fcNaN):
1624 case convolve(fcNormal, fcNaN):
1625 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001626 return cmpUnordered;
1627
1628 case convolve(fcInfinity, fcNormal):
1629 case convolve(fcInfinity, fcZero):
1630 case convolve(fcNormal, fcZero):
1631 if(sign)
1632 return cmpLessThan;
1633 else
1634 return cmpGreaterThan;
1635
1636 case convolve(fcNormal, fcInfinity):
1637 case convolve(fcZero, fcInfinity):
1638 case convolve(fcZero, fcNormal):
1639 if(rhs.sign)
1640 return cmpGreaterThan;
1641 else
1642 return cmpLessThan;
1643
1644 case convolve(fcInfinity, fcInfinity):
1645 if(sign == rhs.sign)
1646 return cmpEqual;
1647 else if(sign)
1648 return cmpLessThan;
1649 else
1650 return cmpGreaterThan;
1651
1652 case convolve(fcZero, fcZero):
1653 return cmpEqual;
1654
1655 case convolve(fcNormal, fcNormal):
1656 break;
1657 }
1658
1659 /* Two normal numbers. Do they have the same sign? */
1660 if(sign != rhs.sign) {
1661 if(sign)
1662 result = cmpLessThan;
1663 else
1664 result = cmpGreaterThan;
1665 } else {
1666 /* Compare absolute values; invert result if negative. */
1667 result = compareAbsoluteValue(rhs);
1668
1669 if(sign) {
1670 if(result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001671 result = cmpGreaterThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001672 else if(result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001673 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001674 }
1675 }
1676
1677 return result;
1678}
1679
Dale Johannesen23a98552008-10-09 23:00:39 +00001680/// APFloat::convert - convert a value of one floating point type to another.
1681/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1682/// records whether the transformation lost information, i.e. whether
1683/// converting the result back to the original type will produce the
1684/// original value (this is almost the same as return value==fsOK, but there
1685/// are edge cases where this is not so).
1686
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001687APFloat::opStatus
1688APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001689 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001690{
Neil Boothc8db43d2007-09-22 02:56:19 +00001691 lostFraction lostFraction;
1692 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001693 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001694
Neil Boothcaf19d72007-10-14 10:29:28 +00001695 assertArithmeticOK(*semantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001696 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001697 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001698 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001699 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001700
Neil Boothc8db43d2007-09-22 02:56:19 +00001701 /* Handle storage complications. If our new form is wider,
1702 re-allocate our bit pattern into wider storage. If it is
1703 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001704 single part we need to free the old storage.
1705 Be careful not to reference significandParts for zeroes
1706 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001707 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001708 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001709 newParts = new integerPart[newPartCount];
1710 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001711 if (category==fcNormal || category==fcNaN)
1712 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001713 freeSignificand();
1714 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001715 } else if (newPartCount < oldPartCount) {
1716 /* Capture any lost fraction through truncation of parts so we get
1717 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001718 if (category==fcNormal)
1719 lostFraction = lostFractionThroughTruncation
1720 (significandParts(), oldPartCount, toSemantics.precision);
1721 if (newPartCount == 1) {
1722 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001723 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001724 newPart = significandParts()[0];
1725 freeSignificand();
1726 significand.part = newPart;
1727 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001728 }
1729
1730 if(category == fcNormal) {
1731 /* Re-interpret our bit-pattern. */
1732 exponent += toSemantics.precision - semantics->precision;
1733 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001734 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001735 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001736 } else if (category == fcNaN) {
1737 int shift = toSemantics.precision - semantics->precision;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001738 // Do this now so significandParts gets the right answer
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001739 const fltSemantics *oldSemantics = semantics;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001740 semantics = &toSemantics;
Dale Johannesen23a98552008-10-09 23:00:39 +00001741 *losesInfo = false;
Dale Johannesen902ff942007-09-25 17:25:00 +00001742 // No normalization here, just truncate
1743 if (shift>0)
1744 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001745 else if (shift < 0) {
1746 unsigned ushift = -shift;
Dale Johannesen23a98552008-10-09 23:00:39 +00001747 // Figure out if we are losing information. This happens
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001748 // if are shifting out something other than 0s, or if the x87 long
1749 // double input did not have its integer bit set (pseudo-NaN), or if the
1750 // x87 long double input did not have its QNan bit set (because the x87
1751 // hardware sets this bit when converting a lower-precision NaN to
1752 // x87 long double).
1753 if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
Dale Johannesen23a98552008-10-09 23:00:39 +00001754 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001755 if (oldSemantics == &APFloat::x87DoubleExtended &&
1756 (!(*significandParts() & 0x8000000000000000ULL) ||
1757 !(*significandParts() & 0x4000000000000000ULL)))
Dale Johannesen23a98552008-10-09 23:00:39 +00001758 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001759 APInt::tcShiftRight(significandParts(), newPartCount, ushift);
1760 }
Dale Johannesen902ff942007-09-25 17:25:00 +00001761 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1762 // does not give you back the same bits. This is dubious, and we
1763 // don't currently do it. You're really supposed to get
1764 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001765 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001766 } else {
1767 semantics = &toSemantics;
1768 fs = opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001769 *losesInfo = false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001770 }
1771
1772 return fs;
1773}
1774
1775/* Convert a floating point number to an integer according to the
1776 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001777 returns an invalid operation exception and the contents of the
1778 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001779 range but the floating point number is not the exact integer, the C
1780 standard doesn't require an inexact exception to be raised. IEEE
1781 854 does require it so we do that.
1782
1783 Note that for conversions to integer type the C standard requires
1784 round-to-zero to always be used. */
1785APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001786APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1787 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001788 roundingMode rounding_mode,
1789 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001790{
1791 lostFraction lost_fraction;
1792 const integerPart *src;
1793 unsigned int dstPartsCount, truncatedBits;
1794
Evan Cheng88f2d6c2008-11-25 19:00:29 +00001795 if (!isArithmeticOk(*semantics))
1796 return opInvalidOp;
Neil Boothe3d936a2007-11-02 15:10:05 +00001797
Dale Johannesen23a98552008-10-09 23:00:39 +00001798 *isExact = false;
1799
Neil Boothee7ae382007-11-01 22:43:37 +00001800 /* Handle the three special cases first. */
1801 if(category == fcInfinity || category == fcNaN)
1802 return opInvalidOp;
1803
1804 dstPartsCount = partCountForBits(width);
1805
1806 if(category == fcZero) {
1807 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00001808 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00001809 *isExact = !sign;
1810 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00001811 }
1812
1813 src = significandParts();
1814
1815 /* Step 1: place our absolute value, with any fraction truncated, in
1816 the destination. */
1817 if (exponent < 0) {
1818 /* Our absolute value is less than one; truncate everything. */
1819 APInt::tcSet(parts, 0, dstPartsCount);
1820 truncatedBits = semantics->precision;
1821 } else {
1822 /* We want the most significant (exponent + 1) bits; the rest are
1823 truncated. */
1824 unsigned int bits = exponent + 1U;
1825
1826 /* Hopelessly large in magnitude? */
1827 if (bits > width)
1828 return opInvalidOp;
1829
1830 if (bits < semantics->precision) {
1831 /* We truncate (semantics->precision - bits) bits. */
1832 truncatedBits = semantics->precision - bits;
1833 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1834 } else {
1835 /* We want at least as many bits as are available. */
1836 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
1837 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
1838 truncatedBits = 0;
1839 }
1840 }
1841
1842 /* Step 2: work out any lost fraction, and increment the absolute
1843 value if we would round away from zero. */
1844 if (truncatedBits) {
1845 lost_fraction = lostFractionThroughTruncation(src, partCount(),
1846 truncatedBits);
1847 if (lost_fraction != lfExactlyZero
1848 && roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
1849 if (APInt::tcIncrement(parts, dstPartsCount))
1850 return opInvalidOp; /* Overflow. */
1851 }
1852 } else {
1853 lost_fraction = lfExactlyZero;
1854 }
1855
1856 /* Step 3: check if we fit in the destination. */
1857 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
1858
1859 if (sign) {
1860 if (!isSigned) {
1861 /* Negative numbers cannot be represented as unsigned. */
1862 if (omsb != 0)
1863 return opInvalidOp;
1864 } else {
1865 /* It takes omsb bits to represent the unsigned integer value.
1866 We lose a bit for the sign, but care is needed as the
1867 maximally negative integer is a special case. */
1868 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
1869 return opInvalidOp;
1870
1871 /* This case can happen because of rounding. */
1872 if (omsb > width)
1873 return opInvalidOp;
1874 }
1875
1876 APInt::tcNegate (parts, dstPartsCount);
1877 } else {
1878 if (omsb >= width + !isSigned)
1879 return opInvalidOp;
1880 }
1881
Dale Johannesen23a98552008-10-09 23:00:39 +00001882 if (lost_fraction == lfExactlyZero) {
1883 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00001884 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001885 } else
Neil Boothee7ae382007-11-01 22:43:37 +00001886 return opInexact;
1887}
1888
1889/* Same as convertToSignExtendedInteger, except we provide
1890 deterministic values in case of an invalid operation exception,
1891 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00001892 for underflow or overflow.
1893 The *isExact output tells whether the result is exact, in the sense
1894 that converting it back to the original floating point type produces
1895 the original value. This is almost equivalent to result==opOK,
1896 except for negative zeroes.
1897*/
Neil Boothee7ae382007-11-01 22:43:37 +00001898APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001899APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00001900 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001901 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001902{
Neil Boothee7ae382007-11-01 22:43:37 +00001903 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001904
Dale Johannesen23a98552008-10-09 23:00:39 +00001905 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
1906 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001907
Neil Boothee7ae382007-11-01 22:43:37 +00001908 if (fs == opInvalidOp) {
1909 unsigned int bits, dstPartsCount;
1910
1911 dstPartsCount = partCountForBits(width);
1912
1913 if (category == fcNaN)
1914 bits = 0;
1915 else if (sign)
1916 bits = isSigned;
1917 else
1918 bits = width - isSigned;
1919
1920 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
1921 if (sign && isSigned)
1922 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001923 }
1924
Neil Boothee7ae382007-11-01 22:43:37 +00001925 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001926}
1927
Neil Booth643ce592007-10-07 12:07:53 +00001928/* Convert an unsigned integer SRC to a floating point number,
1929 rounding according to ROUNDING_MODE. The sign of the floating
1930 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001931APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00001932APFloat::convertFromUnsignedParts(const integerPart *src,
1933 unsigned int srcCount,
1934 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001935{
Neil Booth5477f852007-10-08 14:39:42 +00001936 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00001937 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00001938 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001939
Neil Boothcaf19d72007-10-14 10:29:28 +00001940 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001941 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00001942 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00001943 dst = significandParts();
1944 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00001945 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00001946
Neil Booth5477f852007-10-08 14:39:42 +00001947 /* We want the most significant PRECISON bits of SRC. There may not
1948 be that many; extract what we can. */
1949 if (precision <= omsb) {
1950 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00001951 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00001952 omsb - precision);
1953 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
1954 } else {
1955 exponent = precision - 1;
1956 lost_fraction = lfExactlyZero;
1957 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00001958 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001959
1960 return normalize(rounding_mode, lost_fraction);
1961}
1962
Dan Gohman93c276e2008-02-29 01:26:11 +00001963APFloat::opStatus
1964APFloat::convertFromAPInt(const APInt &Val,
1965 bool isSigned,
1966 roundingMode rounding_mode)
1967{
1968 unsigned int partCount = Val.getNumWords();
1969 APInt api = Val;
1970
1971 sign = false;
1972 if (isSigned && api.isNegative()) {
1973 sign = true;
1974 api = -api;
1975 }
1976
1977 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
1978}
1979
Neil Boothf16c5952007-10-07 12:15:41 +00001980/* Convert a two's complement integer SRC to a floating point number,
1981 rounding according to ROUNDING_MODE. ISSIGNED is true if the
1982 integer is signed, in which case it must be sign-extended. */
1983APFloat::opStatus
1984APFloat::convertFromSignExtendedInteger(const integerPart *src,
1985 unsigned int srcCount,
1986 bool isSigned,
1987 roundingMode rounding_mode)
1988{
1989 opStatus status;
1990
Neil Boothcaf19d72007-10-14 10:29:28 +00001991 assertArithmeticOK(*semantics);
Neil Boothf16c5952007-10-07 12:15:41 +00001992 if (isSigned
1993 && APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
1994 integerPart *copy;
1995
1996 /* If we're signed and negative negate a copy. */
1997 sign = true;
1998 copy = new integerPart[srcCount];
1999 APInt::tcAssign(copy, src, srcCount);
2000 APInt::tcNegate(copy, srcCount);
2001 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2002 delete [] copy;
2003 } else {
2004 sign = false;
2005 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2006 }
2007
2008 return status;
2009}
2010
Neil Boothccf596a2007-10-07 11:45:55 +00002011/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002012APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002013APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2014 unsigned int width, bool isSigned,
2015 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002016{
Dale Johannesen910993e2007-09-21 22:09:37 +00002017 unsigned int partCount = partCountForBits(width);
Dale Johannesen910993e2007-09-21 22:09:37 +00002018 APInt api = APInt(width, partCount, parts);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002019
2020 sign = false;
Dale Johannesencce23a42007-09-30 18:17:01 +00002021 if(isSigned && APInt::tcExtractBit(parts, width - 1)) {
2022 sign = true;
2023 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002024 }
2025
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002026 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002027}
2028
2029APFloat::opStatus
2030APFloat::convertFromHexadecimalString(const char *p,
Neil Booth4f881702007-09-26 21:33:42 +00002031 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002032{
2033 lostFraction lost_fraction;
2034 integerPart *significand;
2035 unsigned int bitPos, partsCount;
2036 const char *dot, *firstSignificantDigit;
2037
2038 zeroSignificand();
2039 exponent = 0;
2040 category = fcNormal;
2041
2042 significand = significandParts();
2043 partsCount = partCount();
2044 bitPos = partsCount * integerPartWidth;
2045
Neil Booth33d4c922007-10-07 08:51:21 +00002046 /* Skip leading zeroes and any (hexa)decimal point. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002047 p = skipLeadingZeroesAndAnyDot(p, &dot);
2048 firstSignificantDigit = p;
2049
2050 for(;;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002051 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002052
2053 if(*p == '.') {
2054 assert(dot == 0);
2055 dot = p++;
2056 }
2057
2058 hex_value = hexDigitValue(*p);
2059 if(hex_value == -1U) {
2060 lost_fraction = lfExactlyZero;
2061 break;
2062 }
2063
2064 p++;
2065
2066 /* Store the number whilst 4-bit nibbles remain. */
2067 if(bitPos) {
2068 bitPos -= 4;
2069 hex_value <<= bitPos % integerPartWidth;
2070 significand[bitPos / integerPartWidth] |= hex_value;
2071 } else {
2072 lost_fraction = trailingHexadecimalFraction(p, hex_value);
2073 while(hexDigitValue(*p) != -1U)
Neil Booth4f881702007-09-26 21:33:42 +00002074 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002075 break;
2076 }
2077 }
2078
2079 /* Hex floats require an exponent but not a hexadecimal point. */
2080 assert(*p == 'p' || *p == 'P');
2081
2082 /* Ignore the exponent if we are zero. */
2083 if(p != firstSignificantDigit) {
2084 int expAdjustment;
2085
2086 /* Implicit hexadecimal point? */
2087 if(!dot)
2088 dot = p;
2089
2090 /* Calculate the exponent adjustment implicit in the number of
2091 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002092 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002093 if(expAdjustment < 0)
2094 expAdjustment++;
2095 expAdjustment = expAdjustment * 4 - 1;
2096
2097 /* Adjust for writing the significand starting at the most
2098 significant nibble. */
2099 expAdjustment += semantics->precision;
2100 expAdjustment -= partsCount * integerPartWidth;
2101
2102 /* Adjust for the given exponent. */
2103 exponent = totalExponent(p, expAdjustment);
2104 }
2105
2106 return normalize(rounding_mode, lost_fraction);
2107}
2108
2109APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002110APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2111 unsigned sigPartCount, int exp,
2112 roundingMode rounding_mode)
2113{
2114 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002115 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002116 integerPart pow5Parts[maxPowerOfFiveParts];
2117 bool isNearest;
2118
2119 isNearest = (rounding_mode == rmNearestTiesToEven
2120 || rounding_mode == rmNearestTiesToAway);
2121
2122 parts = partCountForBits(semantics->precision + 11);
2123
2124 /* Calculate pow(5, abs(exp)). */
2125 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2126
2127 for (;; parts *= 2) {
2128 opStatus sigStatus, powStatus;
2129 unsigned int excessPrecision, truncatedBits;
2130
2131 calcSemantics.precision = parts * integerPartWidth - 1;
2132 excessPrecision = calcSemantics.precision - semantics->precision;
2133 truncatedBits = excessPrecision;
2134
2135 APFloat decSig(calcSemantics, fcZero, sign);
2136 APFloat pow5(calcSemantics, fcZero, false);
2137
2138 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2139 rmNearestTiesToEven);
2140 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2141 rmNearestTiesToEven);
2142 /* Add exp, as 10^n = 5^n * 2^n. */
2143 decSig.exponent += exp;
2144
2145 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002146 integerPart HUerr, HUdistance;
2147 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002148
2149 if (exp >= 0) {
2150 /* multiplySignificand leaves the precision-th bit set to 1. */
2151 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2152 powHUerr = powStatus != opOK;
2153 } else {
2154 calcLostFraction = decSig.divideSignificand(pow5);
2155 /* Denormal numbers have less precision. */
2156 if (decSig.exponent < semantics->minExponent) {
2157 excessPrecision += (semantics->minExponent - decSig.exponent);
2158 truncatedBits = excessPrecision;
2159 if (excessPrecision > calcSemantics.precision)
2160 excessPrecision = calcSemantics.precision;
2161 }
2162 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002163 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002164 }
2165
2166 /* Both multiplySignificand and divideSignificand return the
2167 result with the integer bit set. */
2168 assert (APInt::tcExtractBit
2169 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
2170
2171 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2172 powHUerr);
2173 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2174 excessPrecision, isNearest);
2175
2176 /* Are we guaranteed to round correctly if we truncate? */
2177 if (HUdistance >= HUerr) {
2178 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2179 calcSemantics.precision - excessPrecision,
2180 excessPrecision);
2181 /* Take the exponent of decSig. If we tcExtract-ed less bits
2182 above we must adjust our exponent to compensate for the
2183 implicit right shift. */
2184 exponent = (decSig.exponent + semantics->precision
2185 - (calcSemantics.precision - excessPrecision));
2186 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2187 decSig.partCount(),
2188 truncatedBits);
2189 return normalize(rounding_mode, calcLostFraction);
2190 }
2191 }
2192}
2193
2194APFloat::opStatus
2195APFloat::convertFromDecimalString(const char *p, roundingMode rounding_mode)
2196{
Neil Booth1870f292007-10-14 10:16:12 +00002197 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002198 opStatus fs;
2199
Neil Booth1870f292007-10-14 10:16:12 +00002200 /* Scan the text. */
2201 interpretDecimal(p, &D);
Neil Booth96c74712007-10-12 16:02:31 +00002202
Neil Booth686700e2007-10-15 15:00:55 +00002203 /* Handle the quick cases. First the case of no significant digits,
2204 i.e. zero, and then exponents that are obviously too large or too
2205 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2206 definitely overflows if
2207
2208 (exp - 1) * L >= maxExponent
2209
2210 and definitely underflows to zero where
2211
2212 (exp + 1) * L <= minExponent - precision
2213
2214 With integer arithmetic the tightest bounds for L are
2215
2216 93/28 < L < 196/59 [ numerator <= 256 ]
2217 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2218 */
2219
Neil Boothcc233592007-12-05 13:06:04 +00002220 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002221 category = fcZero;
2222 fs = opOK;
Neil Booth686700e2007-10-15 15:00:55 +00002223 } else if ((D.normalizedExponent + 1) * 28738
2224 <= 8651 * (semantics->minExponent - (int) semantics->precision)) {
2225 /* Underflow to zero and round. */
2226 zeroSignificand();
2227 fs = normalize(rounding_mode, lfLessThanHalf);
2228 } else if ((D.normalizedExponent - 1) * 42039
2229 >= 12655 * semantics->maxExponent) {
2230 /* Overflow and round. */
2231 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002232 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002233 integerPart *decSignificand;
2234 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002235
Neil Booth1870f292007-10-14 10:16:12 +00002236 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002237 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002238 to hold the full significand, and an extra part required by
2239 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002240 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002241 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002242 decSignificand = new integerPart[partCount + 1];
2243 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002244
Neil Booth1870f292007-10-14 10:16:12 +00002245 /* Convert to binary efficiently - we do almost all multiplication
2246 in an integerPart. When this would overflow do we do a single
2247 bignum multiplication, and then revert again to multiplication
2248 in an integerPart. */
2249 do {
2250 integerPart decValue, val, multiplier;
2251
2252 val = 0;
2253 multiplier = 1;
2254
2255 do {
2256 if (*p == '.')
2257 p++;
2258
2259 decValue = decDigitValue(*p++);
2260 multiplier *= 10;
2261 val = val * 10 + decValue;
2262 /* The maximum number that can be multiplied by ten with any
2263 digit added without overflowing an integerPart. */
2264 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2265
2266 /* Multiply out the current part. */
2267 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2268 partCount, partCount + 1, false);
2269
2270 /* If we used another part (likely but not guaranteed), increase
2271 the count. */
2272 if (decSignificand[partCount])
2273 partCount++;
2274 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002275
Neil Booth43a4b282007-11-01 22:51:07 +00002276 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002277 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002278 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002279
Neil Booth1870f292007-10-14 10:16:12 +00002280 delete [] decSignificand;
2281 }
Neil Booth96c74712007-10-12 16:02:31 +00002282
2283 return fs;
2284}
2285
2286APFloat::opStatus
Neil Booth4f881702007-09-26 21:33:42 +00002287APFloat::convertFromString(const char *p, roundingMode rounding_mode)
2288{
Neil Boothcaf19d72007-10-14 10:29:28 +00002289 assertArithmeticOK(*semantics);
2290
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002291 /* Handle a leading minus sign. */
2292 if(*p == '-')
2293 sign = 1, p++;
2294 else
2295 sign = 0;
2296
2297 if(p[0] == '0' && (p[1] == 'x' || p[1] == 'X'))
2298 return convertFromHexadecimalString(p + 2, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002299 else
2300 return convertFromDecimalString(p, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002301}
Dale Johannesen343e7702007-08-24 00:56:33 +00002302
Neil Bootha30b0ee2007-10-03 22:26:02 +00002303/* Write out a hexadecimal representation of the floating point value
2304 to DST, which must be of sufficient size, in the C99 form
2305 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2306 excluding the terminating NUL.
2307
2308 If UPPERCASE, the output is in upper case, otherwise in lower case.
2309
2310 HEXDIGITS digits appear altogether, rounding the value if
2311 necessary. If HEXDIGITS is 0, the minimal precision to display the
2312 number precisely is used instead. If nothing would appear after
2313 the decimal point it is suppressed.
2314
2315 The decimal exponent is always printed and has at least one digit.
2316 Zero values display an exponent of zero. Infinities and NaNs
2317 appear as "infinity" or "nan" respectively.
2318
2319 The above rules are as specified by C99. There is ambiguity about
2320 what the leading hexadecimal digit should be. This implementation
2321 uses whatever is necessary so that the exponent is displayed as
2322 stored. This implies the exponent will fall within the IEEE format
2323 range, and the leading hexadecimal digit will be 0 (for denormals),
2324 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2325 any other digits zero).
2326*/
2327unsigned int
2328APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2329 bool upperCase, roundingMode rounding_mode) const
2330{
2331 char *p;
2332
Neil Boothcaf19d72007-10-14 10:29:28 +00002333 assertArithmeticOK(*semantics);
2334
Neil Bootha30b0ee2007-10-03 22:26:02 +00002335 p = dst;
2336 if (sign)
2337 *dst++ = '-';
2338
2339 switch (category) {
2340 case fcInfinity:
2341 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2342 dst += sizeof infinityL - 1;
2343 break;
2344
2345 case fcNaN:
2346 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2347 dst += sizeof NaNU - 1;
2348 break;
2349
2350 case fcZero:
2351 *dst++ = '0';
2352 *dst++ = upperCase ? 'X': 'x';
2353 *dst++ = '0';
2354 if (hexDigits > 1) {
2355 *dst++ = '.';
2356 memset (dst, '0', hexDigits - 1);
2357 dst += hexDigits - 1;
2358 }
2359 *dst++ = upperCase ? 'P': 'p';
2360 *dst++ = '0';
2361 break;
2362
2363 case fcNormal:
2364 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2365 break;
2366 }
2367
2368 *dst = 0;
2369
Evan Cheng48e8c802008-05-02 21:15:08 +00002370 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002371}
2372
2373/* Does the hard work of outputting the correctly rounded hexadecimal
2374 form of a normal floating point number with the specified number of
2375 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2376 digits necessary to print the value precisely is output. */
2377char *
2378APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2379 bool upperCase,
2380 roundingMode rounding_mode) const
2381{
2382 unsigned int count, valueBits, shift, partsCount, outputDigits;
2383 const char *hexDigitChars;
2384 const integerPart *significand;
2385 char *p;
2386 bool roundUp;
2387
2388 *dst++ = '0';
2389 *dst++ = upperCase ? 'X': 'x';
2390
2391 roundUp = false;
2392 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2393
2394 significand = significandParts();
2395 partsCount = partCount();
2396
2397 /* +3 because the first digit only uses the single integer bit, so
2398 we have 3 virtual zero most-significant-bits. */
2399 valueBits = semantics->precision + 3;
2400 shift = integerPartWidth - valueBits % integerPartWidth;
2401
2402 /* The natural number of digits required ignoring trailing
2403 insignificant zeroes. */
2404 outputDigits = (valueBits - significandLSB () + 3) / 4;
2405
2406 /* hexDigits of zero means use the required number for the
2407 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002408 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002409 if (hexDigits) {
2410 if (hexDigits < outputDigits) {
2411 /* We are dropping non-zero bits, so need to check how to round.
2412 "bits" is the number of dropped bits. */
2413 unsigned int bits;
2414 lostFraction fraction;
2415
2416 bits = valueBits - hexDigits * 4;
2417 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2418 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2419 }
2420 outputDigits = hexDigits;
2421 }
2422
2423 /* Write the digits consecutively, and start writing in the location
2424 of the hexadecimal point. We move the most significant digit
2425 left and add the hexadecimal point later. */
2426 p = ++dst;
2427
2428 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2429
2430 while (outputDigits && count) {
2431 integerPart part;
2432
2433 /* Put the most significant integerPartWidth bits in "part". */
2434 if (--count == partsCount)
2435 part = 0; /* An imaginary higher zero part. */
2436 else
2437 part = significand[count] << shift;
2438
2439 if (count && shift)
2440 part |= significand[count - 1] >> (integerPartWidth - shift);
2441
2442 /* Convert as much of "part" to hexdigits as we can. */
2443 unsigned int curDigits = integerPartWidth / 4;
2444
2445 if (curDigits > outputDigits)
2446 curDigits = outputDigits;
2447 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2448 outputDigits -= curDigits;
2449 }
2450
2451 if (roundUp) {
2452 char *q = dst;
2453
2454 /* Note that hexDigitChars has a trailing '0'. */
2455 do {
2456 q--;
2457 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002458 } while (*q == '0');
2459 assert (q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002460 } else {
2461 /* Add trailing zeroes. */
2462 memset (dst, '0', outputDigits);
2463 dst += outputDigits;
2464 }
2465
2466 /* Move the most significant digit to before the point, and if there
2467 is something after the decimal point add it. This must come
2468 after rounding above. */
2469 p[-1] = p[0];
2470 if (dst -1 == p)
2471 dst--;
2472 else
2473 p[0] = '.';
2474
2475 /* Finally output the exponent. */
2476 *dst++ = upperCase ? 'P': 'p';
2477
Neil Booth92f7e8d2007-10-06 07:29:25 +00002478 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002479}
2480
Dale Johannesen343e7702007-08-24 00:56:33 +00002481// For good performance it is desirable for different APFloats
2482// to produce different integers.
2483uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00002484APFloat::getHashValue() const
2485{
Dale Johannesen343e7702007-08-24 00:56:33 +00002486 if (category==fcZero) return sign<<8 | semantics->precision ;
2487 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002488 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00002489 else {
2490 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2491 const integerPart* p = significandParts();
2492 for (int i=partCount(); i>0; i--, p++)
Evan Cheng48e8c802008-05-02 21:15:08 +00002493 hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
Dale Johannesen343e7702007-08-24 00:56:33 +00002494 return hash;
2495 }
2496}
2497
2498// Conversion from APFloat to/from host float/double. It may eventually be
2499// possible to eliminate these and have everybody deal with APFloats, but that
2500// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002501// Current implementation requires integerPartWidth==64, which is correct at
2502// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002503
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002504// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002505// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002506
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002507APInt
Neil Booth4f881702007-09-26 21:33:42 +00002508APFloat::convertF80LongDoubleAPFloatToAPInt() const
2509{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002510 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002511 assert (partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002512
2513 uint64_t myexponent, mysignificand;
2514
2515 if (category==fcNormal) {
2516 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002517 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002518 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2519 myexponent = 0; // denormal
2520 } else if (category==fcZero) {
2521 myexponent = 0;
2522 mysignificand = 0;
2523 } else if (category==fcInfinity) {
2524 myexponent = 0x7fff;
2525 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002526 } else {
2527 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002528 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002529 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002530 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002531
2532 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002533 words[0] = ((uint64_t)(sign & 1) << 63) |
2534 ((myexponent & 0x7fffLL) << 48) |
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002535 ((mysignificand >>16) & 0xffffffffffffLL);
2536 words[1] = mysignificand & 0xffff;
Chris Lattnera11ef822007-10-06 06:13:42 +00002537 return APInt(80, 2, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002538}
2539
2540APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002541APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2542{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002543 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002544 assert (partCount()==2);
2545
2546 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2547
2548 if (category==fcNormal) {
2549 myexponent = exponent + 1023; //bias
2550 myexponent2 = exponent2 + 1023;
2551 mysignificand = significandParts()[0];
2552 mysignificand2 = significandParts()[1];
2553 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2554 myexponent = 0; // denormal
2555 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2556 myexponent2 = 0; // denormal
2557 } else if (category==fcZero) {
2558 myexponent = 0;
2559 mysignificand = 0;
2560 myexponent2 = 0;
2561 mysignificand2 = 0;
2562 } else if (category==fcInfinity) {
2563 myexponent = 0x7ff;
2564 myexponent2 = 0;
2565 mysignificand = 0;
2566 mysignificand2 = 0;
2567 } else {
2568 assert(category == fcNaN && "Unknown category");
2569 myexponent = 0x7ff;
2570 mysignificand = significandParts()[0];
2571 myexponent2 = exponent2;
2572 mysignificand2 = significandParts()[1];
2573 }
2574
2575 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002576 words[0] = ((uint64_t)(sign & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002577 ((myexponent & 0x7ff) << 52) |
2578 (mysignificand & 0xfffffffffffffLL);
Evan Cheng48e8c802008-05-02 21:15:08 +00002579 words[1] = ((uint64_t)(sign2 & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002580 ((myexponent2 & 0x7ff) << 52) |
2581 (mysignificand2 & 0xfffffffffffffLL);
2582 return APInt(128, 2, words);
2583}
2584
2585APInt
Neil Booth4f881702007-09-26 21:33:42 +00002586APFloat::convertDoubleAPFloatToAPInt() const
2587{
Dan Gohmancb648f92007-09-14 20:08:19 +00002588 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00002589 assert (partCount()==1);
2590
Dale Johanneseneaf08942007-08-31 04:03:46 +00002591 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002592
2593 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002594 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002595 mysignificand = *significandParts();
2596 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2597 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002598 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002599 myexponent = 0;
2600 mysignificand = 0;
2601 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002602 myexponent = 0x7ff;
2603 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002604 } else {
2605 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002606 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002607 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002608 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002609
Evan Cheng48e8c802008-05-02 21:15:08 +00002610 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002611 ((myexponent & 0x7ff) << 52) |
2612 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002613}
2614
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002615APInt
Neil Booth4f881702007-09-26 21:33:42 +00002616APFloat::convertFloatAPFloatToAPInt() const
2617{
Dan Gohmancb648f92007-09-14 20:08:19 +00002618 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00002619 assert (partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002620
Dale Johanneseneaf08942007-08-31 04:03:46 +00002621 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002622
2623 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002624 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002625 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002626 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002627 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002628 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002629 myexponent = 0;
2630 mysignificand = 0;
2631 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002632 myexponent = 0xff;
2633 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002634 } else {
2635 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002636 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002637 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002638 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002639
Chris Lattnera11ef822007-10-06 06:13:42 +00002640 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2641 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002642}
2643
Dale Johannesena471c2e2007-10-11 18:07:22 +00002644// This function creates an APInt that is just a bit map of the floating
2645// point constant as it would appear in memory. It is not a conversion,
2646// and treating the result as a normal integer is unlikely to be useful.
2647
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002648APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002649APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002650{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002651 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002652 return convertFloatAPFloatToAPInt();
Chris Lattnera11ef822007-10-06 06:13:42 +00002653
Dan Gohmanb10abe12008-01-29 12:08:20 +00002654 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002655 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002656
Dan Gohmanb10abe12008-01-29 12:08:20 +00002657 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002658 return convertPPCDoubleDoubleAPFloatToAPInt();
2659
Dan Gohmanb10abe12008-01-29 12:08:20 +00002660 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002661 "unknown format!");
2662 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002663}
2664
Neil Booth4f881702007-09-26 21:33:42 +00002665float
2666APFloat::convertToFloat() const
2667{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002668 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Dale Johannesen7111b022008-10-09 18:53:47 +00002669 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002670 return api.bitsToFloat();
2671}
2672
Neil Booth4f881702007-09-26 21:33:42 +00002673double
2674APFloat::convertToDouble() const
2675{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002676 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Dale Johannesen7111b022008-10-09 18:53:47 +00002677 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002678 return api.bitsToDouble();
2679}
2680
Dale Johannesend3d8ce32008-10-06 18:22:29 +00002681/// Integer bit is explicit in this format. Intel hardware (387 and later)
2682/// does not support these bit patterns:
2683/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2684/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2685/// exponent = 0, integer bit 1 ("pseudodenormal")
2686/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2687/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002688void
Neil Booth4f881702007-09-26 21:33:42 +00002689APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2690{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002691 assert(api.getBitWidth()==80);
2692 uint64_t i1 = api.getRawData()[0];
2693 uint64_t i2 = api.getRawData()[1];
2694 uint64_t myexponent = (i1 >> 48) & 0x7fff;
2695 uint64_t mysignificand = ((i1 << 16) & 0xffffffffffff0000ULL) |
2696 (i2 & 0xffff);
2697
2698 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002699 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002700
Evan Cheng48e8c802008-05-02 21:15:08 +00002701 sign = static_cast<unsigned int>(i1>>63);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002702 if (myexponent==0 && mysignificand==0) {
2703 // exponent, significand meaningless
2704 category = fcZero;
2705 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2706 // exponent, significand meaningless
2707 category = fcInfinity;
2708 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2709 // exponent meaningless
2710 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002711 significandParts()[0] = mysignificand;
2712 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002713 } else {
2714 category = fcNormal;
2715 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002716 significandParts()[0] = mysignificand;
2717 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002718 if (myexponent==0) // denormal
2719 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00002720 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002721}
2722
2723void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002724APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
2725{
2726 assert(api.getBitWidth()==128);
2727 uint64_t i1 = api.getRawData()[0];
2728 uint64_t i2 = api.getRawData()[1];
2729 uint64_t myexponent = (i1 >> 52) & 0x7ff;
2730 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
2731 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
2732 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
2733
2734 initialize(&APFloat::PPCDoubleDouble);
2735 assert(partCount()==2);
2736
Evan Cheng48e8c802008-05-02 21:15:08 +00002737 sign = static_cast<unsigned int>(i1>>63);
2738 sign2 = static_cast<unsigned int>(i2>>63);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002739 if (myexponent==0 && mysignificand==0) {
2740 // exponent, significand meaningless
2741 // exponent2 and significand2 are required to be 0; we don't check
2742 category = fcZero;
2743 } else if (myexponent==0x7ff && mysignificand==0) {
2744 // exponent, significand meaningless
2745 // exponent2 and significand2 are required to be 0; we don't check
2746 category = fcInfinity;
2747 } else if (myexponent==0x7ff && mysignificand!=0) {
2748 // exponent meaningless. So is the whole second word, but keep it
2749 // for determinism.
2750 category = fcNaN;
2751 exponent2 = myexponent2;
2752 significandParts()[0] = mysignificand;
2753 significandParts()[1] = mysignificand2;
2754 } else {
2755 category = fcNormal;
2756 // Note there is no category2; the second word is treated as if it is
2757 // fcNormal, although it might be something else considered by itself.
2758 exponent = myexponent - 1023;
2759 exponent2 = myexponent2 - 1023;
2760 significandParts()[0] = mysignificand;
2761 significandParts()[1] = mysignificand2;
2762 if (myexponent==0) // denormal
2763 exponent = -1022;
2764 else
2765 significandParts()[0] |= 0x10000000000000LL; // integer bit
2766 if (myexponent2==0)
2767 exponent2 = -1022;
2768 else
2769 significandParts()[1] |= 0x10000000000000LL; // integer bit
2770 }
2771}
2772
2773void
Neil Booth4f881702007-09-26 21:33:42 +00002774APFloat::initFromDoubleAPInt(const APInt &api)
2775{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002776 assert(api.getBitWidth()==64);
2777 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00002778 uint64_t myexponent = (i >> 52) & 0x7ff;
2779 uint64_t mysignificand = i & 0xfffffffffffffLL;
2780
Dale Johannesen343e7702007-08-24 00:56:33 +00002781 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00002782 assert(partCount()==1);
2783
Evan Cheng48e8c802008-05-02 21:15:08 +00002784 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00002785 if (myexponent==0 && mysignificand==0) {
2786 // exponent, significand meaningless
2787 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00002788 } else if (myexponent==0x7ff && mysignificand==0) {
2789 // exponent, significand meaningless
2790 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002791 } else if (myexponent==0x7ff && mysignificand!=0) {
2792 // exponent meaningless
2793 category = fcNaN;
2794 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002795 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00002796 category = fcNormal;
2797 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002798 *significandParts() = mysignificand;
2799 if (myexponent==0) // denormal
2800 exponent = -1022;
2801 else
2802 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00002803 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002804}
2805
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002806void
Neil Booth4f881702007-09-26 21:33:42 +00002807APFloat::initFromFloatAPInt(const APInt & api)
2808{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002809 assert(api.getBitWidth()==32);
2810 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00002811 uint32_t myexponent = (i >> 23) & 0xff;
2812 uint32_t mysignificand = i & 0x7fffff;
2813
Dale Johannesen343e7702007-08-24 00:56:33 +00002814 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00002815 assert(partCount()==1);
2816
Dale Johanneseneaf08942007-08-31 04:03:46 +00002817 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00002818 if (myexponent==0 && mysignificand==0) {
2819 // exponent, significand meaningless
2820 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00002821 } else if (myexponent==0xff && mysignificand==0) {
2822 // exponent, significand meaningless
2823 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00002824 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002825 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00002826 category = fcNaN;
2827 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002828 } else {
2829 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00002830 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002831 *significandParts() = mysignificand;
2832 if (myexponent==0) // denormal
2833 exponent = -126;
2834 else
2835 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00002836 }
2837}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002838
2839/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00002840/// we infer the floating point type from the size of the APInt. The
2841/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
2842/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002843void
Dale Johannesena471c2e2007-10-11 18:07:22 +00002844APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00002845{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002846 if (api.getBitWidth() == 32)
2847 return initFromFloatAPInt(api);
2848 else if (api.getBitWidth()==64)
2849 return initFromDoubleAPInt(api);
2850 else if (api.getBitWidth()==80)
2851 return initFromF80LongDoubleAPInt(api);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002852 else if (api.getBitWidth()==128 && !isIEEE)
2853 return initFromPPCDoubleDoubleAPInt(api);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002854 else
2855 assert(0);
2856}
2857
Dale Johannesena471c2e2007-10-11 18:07:22 +00002858APFloat::APFloat(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00002859{
Dale Johannesena471c2e2007-10-11 18:07:22 +00002860 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002861}
2862
Neil Booth4f881702007-09-26 21:33:42 +00002863APFloat::APFloat(float f)
2864{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002865 APInt api = APInt(32, 0);
2866 initFromAPInt(api.floatToBits(f));
2867}
2868
Neil Booth4f881702007-09-26 21:33:42 +00002869APFloat::APFloat(double d)
2870{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002871 APInt api = APInt(64, 0);
2872 initFromAPInt(api.doubleToBits(d));
2873}