blob: 57e60dac45cae6f984a1eb2fa05e86dacfd3e5d3 [file] [log] [blame]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision floating
11// point values and provide a variety of arithmetic operations on them.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnere5256752007-12-08 19:00:03 +000015#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +000016#include "llvm/ADT/APSInt.h"
Ted Kremenek6f30a072008-02-11 17:24:50 +000017#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000018#include "llvm/ADT/Hashing.h"
Jordan Rosee1f76582013-01-18 21:45:30 +000019#include "llvm/ADT/StringExtras.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000020#include "llvm/ADT/StringRef.h"
Torok Edwin56d06592009-07-11 20:10:48 +000021#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000022#include "llvm/Support/MathExtras.h"
Chris Lattner17f71652008-08-17 07:19:36 +000023#include <cstring>
Chandler Carruthed0881b2012-12-03 16:50:05 +000024#include <limits.h>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000025
26using namespace llvm;
27
28#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
29
Neil Booth8f1946f2007-10-03 22:26:02 +000030/* Assumed in hexadecimal significand parsing, and conversion to
31 hexadecimal strings. */
Chris Lattner8fcea672008-08-17 04:58:58 +000032#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000033COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
34
35namespace llvm {
36
37 /* Represents floating point arithmetic semantics. */
38 struct fltSemantics {
39 /* The largest E such that 2^E is representable; this matches the
40 definition of IEEE 754. */
41 exponent_t maxExponent;
42
43 /* The smallest E such that 2^E is a normalized number; this
44 matches the definition of IEEE 754. */
45 exponent_t minExponent;
46
47 /* Number of bits in the significand. This includes the integer
48 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000049 unsigned int precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000050 };
51
Ulrich Weigand908c9362012-10-29 18:18:44 +000052 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11 };
53 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24 };
54 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53 };
55 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113 };
56 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64 };
57 const fltSemantics APFloat::Bogus = { 0, 0, 0 };
Dale Johannesen007aa372007-10-11 18:07:22 +000058
Ulrich Weigandd9f7e252012-10-29 18:09:01 +000059 /* The PowerPC format consists of two doubles. It does not map cleanly
60 onto the usual format above. It is approximated using twice the
61 mantissa bits. Note that for exponents near the double minimum,
62 we no longer can represent the full 106 mantissa bits, so those
63 will be treated as denormal numbers.
64
65 FIXME: While this approximation is equivalent to what GCC uses for
66 compile-time arithmetic on PPC double-double numbers, it is not able
67 to represent all possible values held by a PPC double-double number,
68 for example: (long double) 1.0 + (long double) 0x1p-106
69 Should this be replaced by a full emulation of PPC double-double? */
Ulrich Weigand908c9362012-10-29 18:18:44 +000070 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022 + 53, 53 + 53 };
Neil Boothb93d90e2007-10-12 16:02:31 +000071
72 /* A tight upper bound on number of parts required to hold the value
73 pow(5, power) is
74
Neil Booth91305512007-10-15 15:00:55 +000075 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +000076
Neil Boothb93d90e2007-10-12 16:02:31 +000077 However, whilst the result may require only this many parts,
78 because we are multiplying two values to get it, the
79 multiplication may require an extra part with the excess part
80 being zero (consider the trivial case of 1 * 1, tcFullMultiply
81 requires two parts to hold the single-part result). So we add an
82 extra one to guarantee enough space whilst multiplying. */
83 const unsigned int maxExponent = 16383;
84 const unsigned int maxPrecision = 113;
85 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth91305512007-10-15 15:00:55 +000086 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
87 / (351 * integerPartWidth));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000088}
89
Chris Lattner91702092009-03-12 23:59:55 +000090/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000091
Chris Lattner91702092009-03-12 23:59:55 +000092static inline unsigned int
93partCountForBits(unsigned int bits)
94{
95 return ((bits) + integerPartWidth - 1) / integerPartWidth;
96}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000097
Chris Lattner91702092009-03-12 23:59:55 +000098/* Returns 0U-9U. Return values >= 10U are not digits. */
99static inline unsigned int
100decDigitValue(unsigned int c)
101{
102 return c - '0';
103}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000104
Chris Lattner91702092009-03-12 23:59:55 +0000105/* Return the value of a decimal exponent of the form
106 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000107
Chris Lattner91702092009-03-12 23:59:55 +0000108 If the exponent overflows, returns a large exponent with the
109 appropriate sign. */
110static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000111readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000112{
113 bool isNegative;
114 unsigned int absExponent;
115 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000116 StringRef::iterator p = begin;
117
118 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000119
Chris Lattner91702092009-03-12 23:59:55 +0000120 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000121 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000122 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000123 assert(p != end && "Exponent has no digits");
124 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000125
Chris Lattner91702092009-03-12 23:59:55 +0000126 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000127 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000128
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000129 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000130 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000131
Chris Lattner91702092009-03-12 23:59:55 +0000132 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000133 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000134
Chris Lattner91702092009-03-12 23:59:55 +0000135 value += absExponent * 10;
136 if (absExponent >= overlargeExponent) {
137 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000138 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000139 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000140 }
Chris Lattner91702092009-03-12 23:59:55 +0000141 absExponent = value;
142 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000143
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000144 assert(p == end && "Invalid exponent in exponent");
145
Chris Lattner91702092009-03-12 23:59:55 +0000146 if (isNegative)
147 return -(int) absExponent;
148 else
149 return (int) absExponent;
150}
151
152/* This is ugly and needs cleaning up, but I don't immediately see
153 how whilst remaining safe. */
154static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000155totalExponent(StringRef::iterator p, StringRef::iterator end,
156 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000157{
158 int unsignedExponent;
159 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000160 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000161
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000162 assert(p != end && "Exponent has no digits");
163
Chris Lattner91702092009-03-12 23:59:55 +0000164 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000165 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000166 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000167 assert(p != end && "Exponent has no digits");
168 }
Chris Lattner91702092009-03-12 23:59:55 +0000169
170 unsignedExponent = 0;
171 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000172 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000173 unsigned int value;
174
175 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000176 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000177
Chris Lattner91702092009-03-12 23:59:55 +0000178 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000179 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000180 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000181 break;
182 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000183 }
184
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000185 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000186 overflow = true;
187
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000188 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000189 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000190 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000191 exponent = -exponent;
192 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000193 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000194 overflow = true;
195 }
196
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000197 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000198 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000199
200 return exponent;
201}
202
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000203static StringRef::iterator
204skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
205 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000206{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000207 StringRef::iterator p = begin;
208 *dot = end;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000209 while (*p == '0' && p != end)
Chris Lattner91702092009-03-12 23:59:55 +0000210 p++;
211
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000212 if (*p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000213 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000214
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000215 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000216
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000217 while (*p == '0' && p != end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000218 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000219 }
220
Chris Lattner91702092009-03-12 23:59:55 +0000221 return p;
222}
Neil Booth4ed401b2007-10-14 10:16:12 +0000223
Chris Lattner91702092009-03-12 23:59:55 +0000224/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000225
Chris Lattner91702092009-03-12 23:59:55 +0000226 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000227
Chris Lattner91702092009-03-12 23:59:55 +0000228 where the decimal point and exponent are optional, fill out the
229 structure D. Exponent is appropriate if the significand is
230 treated as an integer, and normalizedExponent if the significand
231 is taken to have the decimal point after a single leading
232 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000233
Chris Lattner91702092009-03-12 23:59:55 +0000234 If the value is zero, V->firstSigDigit points to a non-digit, and
235 the return exponent is zero.
236*/
237struct decimalInfo {
238 const char *firstSigDigit;
239 const char *lastSigDigit;
240 int exponent;
241 int normalizedExponent;
242};
Neil Booth4ed401b2007-10-14 10:16:12 +0000243
Chris Lattner91702092009-03-12 23:59:55 +0000244static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000245interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
246 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000247{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000248 StringRef::iterator dot = end;
249 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000250
Chris Lattner91702092009-03-12 23:59:55 +0000251 D->firstSigDigit = p;
252 D->exponent = 0;
253 D->normalizedExponent = 0;
254
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000255 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000256 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000257 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000258 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000259 if (p == end)
260 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000261 }
Chris Lattner91702092009-03-12 23:59:55 +0000262 if (decDigitValue(*p) >= 10U)
263 break;
Chris Lattner91702092009-03-12 23:59:55 +0000264 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000265
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000266 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000267 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
268 assert(p != begin && "Significand has no digits");
269 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000270
271 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000272 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000273
Chris Lattner91702092009-03-12 23:59:55 +0000274 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000275 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000276 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000277 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000278
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000279 /* If number is all zeroes accept any exponent. */
280 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000281 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000282 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000283 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000284 do
285 p--;
286 while (p != begin && *p == '0');
287 while (p != begin && *p == '.');
288 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000289
Chris Lattner91702092009-03-12 23:59:55 +0000290 /* Adjust the exponents for any decimal point. */
291 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
292 D->normalizedExponent = (D->exponent +
293 static_cast<exponent_t>((p - D->firstSigDigit)
294 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000295 }
296
Chris Lattner91702092009-03-12 23:59:55 +0000297 D->lastSigDigit = p;
298}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000299
Chris Lattner91702092009-03-12 23:59:55 +0000300/* Return the trailing fraction of a hexadecimal number.
301 DIGITVALUE is the first hex digit of the fraction, P points to
302 the next digit. */
303static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000304trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
305 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000306{
307 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000308
Chris Lattner91702092009-03-12 23:59:55 +0000309 /* If the first trailing digit isn't 0 or 8 we can work out the
310 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000311 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000312 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000313 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000314 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000315
316 /* Otherwise we need to find the first non-zero digit. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000317 while (*p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000318 p++;
319
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000320 assert(p != end && "Invalid trailing hexadecimal fraction!");
321
Chris Lattner91702092009-03-12 23:59:55 +0000322 hexDigit = hexDigitValue(*p);
323
324 /* If we ran off the end it is exactly zero or one-half, otherwise
325 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000326 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000327 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
328 else
329 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
330}
331
332/* Return the fraction lost were a bignum truncated losing the least
333 significant BITS bits. */
334static lostFraction
335lostFractionThroughTruncation(const integerPart *parts,
336 unsigned int partCount,
337 unsigned int bits)
338{
339 unsigned int lsb;
340
341 lsb = APInt::tcLSB(parts, partCount);
342
343 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000344 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000345 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000346 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000347 return lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000348 if (bits <= partCount * integerPartWidth &&
349 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000350 return lfMoreThanHalf;
351
352 return lfLessThanHalf;
353}
354
355/* Shift DST right BITS bits noting lost fraction. */
356static lostFraction
357shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
358{
359 lostFraction lost_fraction;
360
361 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
362
363 APInt::tcShiftRight(dst, parts, bits);
364
365 return lost_fraction;
366}
367
368/* Combine the effect of two lost fractions. */
369static lostFraction
370combineLostFractions(lostFraction moreSignificant,
371 lostFraction lessSignificant)
372{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000373 if (lessSignificant != lfExactlyZero) {
374 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000375 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000376 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000377 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000378 }
379
Chris Lattner91702092009-03-12 23:59:55 +0000380 return moreSignificant;
381}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000382
Chris Lattner91702092009-03-12 23:59:55 +0000383/* The error from the true value, in half-ulps, on multiplying two
384 floating point numbers, which differ from the value they
385 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
386 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000387
Chris Lattner91702092009-03-12 23:59:55 +0000388 See "How to Read Floating Point Numbers Accurately" by William D
389 Clinger. */
390static unsigned int
391HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
392{
393 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000394
Chris Lattner91702092009-03-12 23:59:55 +0000395 if (HUerr1 + HUerr2 == 0)
396 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
397 else
398 return inexactMultiply + 2 * (HUerr1 + HUerr2);
399}
Neil Booth8f1946f2007-10-03 22:26:02 +0000400
Chris Lattner91702092009-03-12 23:59:55 +0000401/* The number of ulps from the boundary (zero, or half if ISNEAREST)
402 when the least significant BITS are truncated. BITS cannot be
403 zero. */
404static integerPart
405ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
406{
407 unsigned int count, partBits;
408 integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000409
Evan Cheng67c90212009-10-27 21:35:42 +0000410 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000411
Chris Lattner91702092009-03-12 23:59:55 +0000412 bits--;
413 count = bits / integerPartWidth;
414 partBits = bits % integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000415
Chris Lattner91702092009-03-12 23:59:55 +0000416 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000417
Chris Lattner91702092009-03-12 23:59:55 +0000418 if (isNearest)
419 boundary = (integerPart) 1 << (partBits - 1);
420 else
421 boundary = 0;
422
423 if (count == 0) {
424 if (part - boundary <= boundary - part)
425 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000426 else
Chris Lattner91702092009-03-12 23:59:55 +0000427 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000428 }
429
Chris Lattner91702092009-03-12 23:59:55 +0000430 if (part == boundary) {
431 while (--count)
432 if (parts[count])
433 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000434
Chris Lattner91702092009-03-12 23:59:55 +0000435 return parts[0];
436 } else if (part == boundary - 1) {
437 while (--count)
438 if (~parts[count])
439 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000440
Chris Lattner91702092009-03-12 23:59:55 +0000441 return -parts[0];
442 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000443
Chris Lattner91702092009-03-12 23:59:55 +0000444 return ~(integerPart) 0; /* A lot. */
445}
Neil Boothb93d90e2007-10-12 16:02:31 +0000446
Chris Lattner91702092009-03-12 23:59:55 +0000447/* Place pow(5, power) in DST, and return the number of parts used.
448 DST must be at least one part larger than size of the answer. */
449static unsigned int
450powerOf5(integerPart *dst, unsigned int power)
451{
452 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
453 15625, 78125 };
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000454 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
455 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000456
Chris Lattner0bf18692009-03-13 00:03:51 +0000457 unsigned int partsCount[16] = { 1 };
Chris Lattner91702092009-03-12 23:59:55 +0000458 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
459 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000460 assert(power <= maxExponent);
461
462 p1 = dst;
463 p2 = scratch;
464
465 *p1 = firstEightPowers[power & 7];
466 power >>= 3;
467
468 result = 1;
469 pow5 = pow5s;
470
471 for (unsigned int n = 0; power; power >>= 1, n++) {
472 unsigned int pc;
473
474 pc = partsCount[n];
475
476 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
477 if (pc == 0) {
478 pc = partsCount[n - 1];
479 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
480 pc *= 2;
481 if (pow5[pc - 1] == 0)
482 pc--;
483 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000484 }
485
Chris Lattner91702092009-03-12 23:59:55 +0000486 if (power & 1) {
487 integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000488
Chris Lattner91702092009-03-12 23:59:55 +0000489 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
490 result += pc;
491 if (p2[result - 1] == 0)
492 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000493
Chris Lattner91702092009-03-12 23:59:55 +0000494 /* Now result is in p1 with partsCount parts and p2 is scratch
495 space. */
496 tmp = p1, p1 = p2, p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000497 }
498
Chris Lattner91702092009-03-12 23:59:55 +0000499 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000500 }
501
Chris Lattner91702092009-03-12 23:59:55 +0000502 if (p1 != dst)
503 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000504
Chris Lattner91702092009-03-12 23:59:55 +0000505 return result;
506}
Neil Boothb93d90e2007-10-12 16:02:31 +0000507
Chris Lattner91702092009-03-12 23:59:55 +0000508/* Zero at the end to avoid modular arithmetic when adding one; used
509 when rounding up during hexadecimal output. */
510static const char hexDigitsLower[] = "0123456789abcdef0";
511static const char hexDigitsUpper[] = "0123456789ABCDEF0";
512static const char infinityL[] = "infinity";
513static const char infinityU[] = "INFINITY";
514static const char NaNL[] = "nan";
515static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000516
Chris Lattner91702092009-03-12 23:59:55 +0000517/* Write out an integerPart in hexadecimal, starting with the most
518 significant nibble. Write out exactly COUNT hexdigits, return
519 COUNT. */
520static unsigned int
521partAsHex (char *dst, integerPart part, unsigned int count,
522 const char *hexDigitChars)
523{
524 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000525
Evan Cheng67c90212009-10-27 21:35:42 +0000526 assert(count != 0 && count <= integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000527
Chris Lattner91702092009-03-12 23:59:55 +0000528 part >>= (integerPartWidth - 4 * count);
529 while (count--) {
530 dst[count] = hexDigitChars[part & 0xf];
531 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000532 }
533
Chris Lattner91702092009-03-12 23:59:55 +0000534 return result;
535}
Neil Booth8f1946f2007-10-03 22:26:02 +0000536
Chris Lattner91702092009-03-12 23:59:55 +0000537/* Write out an unsigned decimal integer. */
538static char *
539writeUnsignedDecimal (char *dst, unsigned int n)
540{
541 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000542
Chris Lattner91702092009-03-12 23:59:55 +0000543 p = buff;
544 do
545 *p++ = '0' + n % 10;
546 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000547
Chris Lattner91702092009-03-12 23:59:55 +0000548 do
549 *dst++ = *--p;
550 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000551
Chris Lattner91702092009-03-12 23:59:55 +0000552 return dst;
553}
Neil Booth8f1946f2007-10-03 22:26:02 +0000554
Chris Lattner91702092009-03-12 23:59:55 +0000555/* Write out a signed decimal integer. */
556static char *
557writeSignedDecimal (char *dst, int value)
558{
559 if (value < 0) {
560 *dst++ = '-';
561 dst = writeUnsignedDecimal(dst, -(unsigned) value);
562 } else
563 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000564
Chris Lattner91702092009-03-12 23:59:55 +0000565 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000566}
567
568/* Constructors. */
569void
570APFloat::initialize(const fltSemantics *ourSemantics)
571{
572 unsigned int count;
573
574 semantics = ourSemantics;
575 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000576 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000577 significand.parts = new integerPart[count];
578}
579
580void
581APFloat::freeSignificand()
582{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000583 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000584 delete [] significand.parts;
585}
586
587void
588APFloat::assign(const APFloat &rhs)
589{
590 assert(semantics == rhs.semantics);
591
592 sign = rhs.sign;
593 category = rhs.category;
594 exponent = rhs.exponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000595 if (category == fcNormal || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000596 copySignificand(rhs);
597}
598
599void
600APFloat::copySignificand(const APFloat &rhs)
601{
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000602 assert(category == fcNormal || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000603 assert(rhs.partCount() >= partCount());
604
605 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000606 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000607}
608
Neil Booth5fe658b2007-10-14 10:39:51 +0000609/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000610 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000611 which may not be ideal. If float, this is QNaN(0). */
John McCalldcb9a7a2010-02-28 02:51:25 +0000612void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Booth5fe658b2007-10-14 10:39:51 +0000613{
614 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000615 sign = Negative;
616
John McCallc12b1332010-02-28 12:49:50 +0000617 integerPart *significand = significandParts();
618 unsigned numParts = partCount();
619
John McCalldcb9a7a2010-02-28 02:51:25 +0000620 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000621 if (!fill || fill->getNumWords() < numParts)
622 APInt::tcSet(significand, 0, numParts);
623 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000624 APInt::tcAssign(significand, fill->getRawData(),
625 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000626
627 // Zero out the excess bits of the significand.
628 unsigned bitsToPreserve = semantics->precision - 1;
629 unsigned part = bitsToPreserve / 64;
630 bitsToPreserve %= 64;
631 significand[part] &= ((1ULL << bitsToPreserve) - 1);
632 for (part++; part != numParts; ++part)
633 significand[part] = 0;
634 }
635
636 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000637
638 if (SNaN) {
639 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000640 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000641
642 // If there are no bits set in the payload, we have to set
643 // *something* to make it a NaN instead of an infinity;
644 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000645 if (APInt::tcIsZero(significand, numParts))
646 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000647 } else {
648 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000649 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000650 }
John McCallc12b1332010-02-28 12:49:50 +0000651
652 // For x87 extended precision, we want to make a NaN, not a
653 // pseudo-NaN. Maybe we should expose the ability to make
654 // pseudo-NaNs?
655 if (semantics == &APFloat::x87DoubleExtended)
656 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000657}
658
659APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
660 const APInt *fill) {
661 APFloat value(Sem, uninitialized);
662 value.makeNaN(SNaN, Negative, fill);
663 return value;
Neil Booth5fe658b2007-10-14 10:39:51 +0000664}
665
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000666APFloat &
667APFloat::operator=(const APFloat &rhs)
668{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000669 if (this != &rhs) {
670 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000671 freeSignificand();
672 initialize(rhs.semantics);
673 }
674 assign(rhs);
675 }
676
677 return *this;
678}
679
Dale Johannesena719a602007-08-24 00:56:33 +0000680bool
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000681APFloat::isDenormal() const {
682 return isNormal() && (exponent == semantics->minExponent) &&
683 (APInt::tcExtractBit(significandParts(),
684 semantics->precision - 1) == 0);
685}
686
687bool
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000688APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000689 if (this == &rhs)
690 return true;
691 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000692 category != rhs.category ||
693 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000694 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000695 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000696 return true;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000697 else if (category==fcNormal && exponent!=rhs.exponent)
698 return false;
Dale Johannesena719a602007-08-24 00:56:33 +0000699 else {
Dale Johannesena719a602007-08-24 00:56:33 +0000700 int i= partCount();
701 const integerPart* p=significandParts();
702 const integerPart* q=rhs.significandParts();
703 for (; i>0; i--, p++, q++) {
704 if (*p != *q)
705 return false;
706 }
707 return true;
708 }
709}
710
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000711APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000712 initialize(&ourSemantics);
713 sign = 0;
714 zeroSignificand();
715 exponent = ourSemantics.precision - 1;
716 significandParts()[0] = value;
717 normalize(rmNearestTiesToEven, lfExactlyZero);
718}
719
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000720APFloat::APFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000721 initialize(&ourSemantics);
722 category = fcZero;
723 sign = false;
724}
725
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000726APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
John McCalldcb9a7a2010-02-28 02:51:25 +0000727 // Allocates storage if necessary but does not initialize it.
728 initialize(&ourSemantics);
729}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000730
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000731APFloat::APFloat(const fltSemantics &ourSemantics,
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000732 fltCategory ourCategory, bool negative) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000733 initialize(&ourSemantics);
734 category = ourCategory;
735 sign = negative;
Mike Stump799bf582009-05-30 03:49:43 +0000736 if (category == fcNormal)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000737 category = fcZero;
Neil Booth5fe658b2007-10-14 10:39:51 +0000738 else if (ourCategory == fcNaN)
John McCalldcb9a7a2010-02-28 02:51:25 +0000739 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000740}
741
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000742APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000743 initialize(&ourSemantics);
744 convertFromString(text, rmNearestTiesToEven);
745}
746
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000747APFloat::APFloat(const APFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000748 initialize(rhs.semantics);
749 assign(rhs);
750}
751
752APFloat::~APFloat()
753{
754 freeSignificand();
755}
756
Ted Kremenek6f30a072008-02-11 17:24:50 +0000757// Profile - This method 'profiles' an APFloat for use with FoldingSet.
758void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen54306fe2008-10-09 18:53:47 +0000759 ID.Add(bitcastToAPInt());
Ted Kremenek6f30a072008-02-11 17:24:50 +0000760}
761
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000762unsigned int
763APFloat::partCount() const
764{
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000765 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000766}
767
768unsigned int
769APFloat::semanticsPrecision(const fltSemantics &semantics)
770{
771 return semantics.precision;
772}
773
774const integerPart *
775APFloat::significandParts() const
776{
777 return const_cast<APFloat *>(this)->significandParts();
778}
779
780integerPart *
781APFloat::significandParts()
782{
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000783 assert(category == fcNormal || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000784
Evan Cheng67c90212009-10-27 21:35:42 +0000785 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000786 return significand.parts;
787 else
788 return &significand.part;
789}
790
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000791void
792APFloat::zeroSignificand()
793{
794 category = fcNormal;
795 APInt::tcSet(significandParts(), 0, partCount());
796}
797
798/* Increment an fcNormal floating point number's significand. */
799void
800APFloat::incrementSignificand()
801{
802 integerPart carry;
803
804 carry = APInt::tcIncrement(significandParts(), partCount());
805
806 /* Our callers should never cause us to overflow. */
807 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000808 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000809}
810
811/* Add the significand of the RHS. Returns the carry flag. */
812integerPart
813APFloat::addSignificand(const APFloat &rhs)
814{
815 integerPart *parts;
816
817 parts = significandParts();
818
819 assert(semantics == rhs.semantics);
820 assert(exponent == rhs.exponent);
821
822 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
823}
824
825/* Subtract the significand of the RHS with a borrow flag. Returns
826 the borrow flag. */
827integerPart
828APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
829{
830 integerPart *parts;
831
832 parts = significandParts();
833
834 assert(semantics == rhs.semantics);
835 assert(exponent == rhs.exponent);
836
837 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000838 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000839}
840
841/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
842 on to the full-precision result of the multiplication. Returns the
843 lost fraction. */
844lostFraction
845APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
846{
Neil Booth9acbf5a2007-09-26 21:33:42 +0000847 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000848 unsigned int partsCount, newPartsCount, precision;
849 integerPart *lhsSignificand;
850 integerPart scratch[4];
851 integerPart *fullSignificand;
852 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000853 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000854
855 assert(semantics == rhs.semantics);
856
857 precision = semantics->precision;
858 newPartsCount = partCountForBits(precision * 2);
859
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000860 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000861 fullSignificand = new integerPart[newPartsCount];
862 else
863 fullSignificand = scratch;
864
865 lhsSignificand = significandParts();
866 partsCount = partCount();
867
868 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000869 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000870
871 lost_fraction = lfExactlyZero;
872 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
873 exponent += rhs.exponent;
874
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000875 // Assume the operands involved in the multiplication are single-precision
876 // FP, and the two multiplicants are:
877 // *this = a23 . a22 ... a0 * 2^e1
878 // rhs = b23 . b22 ... b0 * 2^e2
879 // the result of multiplication is:
880 // *this = c47 c46 . c45 ... c0 * 2^(e1+e2)
881 // Note that there are two significant bits at the left-hand side of the
882 // radix point. Move the radix point toward left by one bit, and adjust
883 // exponent accordingly.
884 exponent += 1;
885
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000886 if (addend) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000887 // The intermediate result of the multiplication has "2 * precision"
888 // signicant bit; adjust the addend to be consistent with mul result.
889 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000890 Significand savedSignificand = significand;
891 const fltSemantics *savedSemantics = semantics;
892 fltSemantics extendedSemantics;
893 opStatus status;
894 unsigned int extendedPrecision;
895
896 /* Normalize our MSB. */
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000897 extendedPrecision = 2 * precision;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000898 if (omsb != extendedPrecision) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000899 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000900 APInt::tcShiftLeft(fullSignificand, newPartsCount,
901 extendedPrecision - omsb);
902 exponent -= extendedPrecision - omsb;
903 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000904
905 /* Create new semantics. */
906 extendedSemantics = *semantics;
907 extendedSemantics.precision = extendedPrecision;
908
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000909 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000910 significand.part = fullSignificand[0];
911 else
912 significand.parts = fullSignificand;
913 semantics = &extendedSemantics;
914
915 APFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000916 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000917 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000918 (void)status;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000919 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
920
921 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000922 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000923 fullSignificand[0] = significand.part;
924 significand = savedSignificand;
925 semantics = savedSemantics;
926
927 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
928 }
929
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000930 // Convert the result having "2 * precision" significant-bits back to the one
931 // having "precision" significant-bits. First, move the radix point from
932 // poision "2*precision - 1" to "precision - 1". The exponent need to be
933 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
934 exponent -= precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000935
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000936 // In case MSB resides at the left-hand side of radix point, shift the
937 // mantissa right by some amount to make sure the MSB reside right before
938 // the radix point (i.e. "MSB . rest-significant-bits").
939 //
940 // Note that the result is not normalized when "omsb < precision". So, the
941 // caller needs to call APFloat::normalize() if normalized value is expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000942 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000943 unsigned int bits, significantParts;
944 lostFraction lf;
945
946 bits = omsb - precision;
947 significantParts = partCountForBits(omsb);
948 lf = shiftRight(fullSignificand, significantParts, bits);
949 lost_fraction = combineLostFractions(lf, lost_fraction);
950 exponent += bits;
951 }
952
953 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
954
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000955 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000956 delete [] fullSignificand;
957
958 return lost_fraction;
959}
960
961/* Multiply the significands of LHS and RHS to DST. */
962lostFraction
963APFloat::divideSignificand(const APFloat &rhs)
964{
965 unsigned int bit, i, partsCount;
966 const integerPart *rhsSignificand;
967 integerPart *lhsSignificand, *dividend, *divisor;
968 integerPart scratch[4];
969 lostFraction lost_fraction;
970
971 assert(semantics == rhs.semantics);
972
973 lhsSignificand = significandParts();
974 rhsSignificand = rhs.significandParts();
975 partsCount = partCount();
976
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000977 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000978 dividend = new integerPart[partsCount * 2];
979 else
980 dividend = scratch;
981
982 divisor = dividend + partsCount;
983
984 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000985 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000986 dividend[i] = lhsSignificand[i];
987 divisor[i] = rhsSignificand[i];
988 lhsSignificand[i] = 0;
989 }
990
991 exponent -= rhs.exponent;
992
993 unsigned int precision = semantics->precision;
994
995 /* Normalize the divisor. */
996 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000997 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000998 exponent += bit;
999 APInt::tcShiftLeft(divisor, partsCount, bit);
1000 }
1001
1002 /* Normalize the dividend. */
1003 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001004 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001005 exponent -= bit;
1006 APInt::tcShiftLeft(dividend, partsCount, bit);
1007 }
1008
Neil Boothb93d90e2007-10-12 16:02:31 +00001009 /* Ensure the dividend >= divisor initially for the loop below.
1010 Incidentally, this means that the division loop below is
1011 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001012 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001013 exponent--;
1014 APInt::tcShiftLeft(dividend, partsCount, 1);
1015 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1016 }
1017
1018 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001019 for (bit = precision; bit; bit -= 1) {
1020 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001021 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1022 APInt::tcSetBit(lhsSignificand, bit - 1);
1023 }
1024
1025 APInt::tcShiftLeft(dividend, partsCount, 1);
1026 }
1027
1028 /* Figure out the lost fraction. */
1029 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1030
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001031 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001032 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001033 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001034 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001035 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001036 lost_fraction = lfExactlyZero;
1037 else
1038 lost_fraction = lfLessThanHalf;
1039
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001040 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001041 delete [] dividend;
1042
1043 return lost_fraction;
1044}
1045
1046unsigned int
1047APFloat::significandMSB() const
1048{
1049 return APInt::tcMSB(significandParts(), partCount());
1050}
1051
1052unsigned int
1053APFloat::significandLSB() const
1054{
1055 return APInt::tcLSB(significandParts(), partCount());
1056}
1057
1058/* Note that a zero result is NOT normalized to fcZero. */
1059lostFraction
1060APFloat::shiftSignificandRight(unsigned int bits)
1061{
1062 /* Our exponent should not overflow. */
1063 assert((exponent_t) (exponent + bits) >= exponent);
1064
1065 exponent += bits;
1066
1067 return shiftRight(significandParts(), partCount(), bits);
1068}
1069
1070/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1071void
1072APFloat::shiftSignificandLeft(unsigned int bits)
1073{
1074 assert(bits < semantics->precision);
1075
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001076 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001077 unsigned int partsCount = partCount();
1078
1079 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1080 exponent -= bits;
1081
1082 assert(!APInt::tcIsZero(significandParts(), partsCount));
1083 }
1084}
1085
1086APFloat::cmpResult
1087APFloat::compareAbsoluteValue(const APFloat &rhs) const
1088{
1089 int compare;
1090
1091 assert(semantics == rhs.semantics);
1092 assert(category == fcNormal);
1093 assert(rhs.category == fcNormal);
1094
1095 compare = exponent - rhs.exponent;
1096
1097 /* If exponents are equal, do an unsigned bignum comparison of the
1098 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001099 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001100 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001101 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001102
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001103 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001104 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001105 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001106 return cmpLessThan;
1107 else
1108 return cmpEqual;
1109}
1110
1111/* Handle overflow. Sign is preserved. We either become infinity or
1112 the largest finite number. */
1113APFloat::opStatus
1114APFloat::handleOverflow(roundingMode rounding_mode)
1115{
1116 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001117 if (rounding_mode == rmNearestTiesToEven ||
1118 rounding_mode == rmNearestTiesToAway ||
1119 (rounding_mode == rmTowardPositive && !sign) ||
1120 (rounding_mode == rmTowardNegative && sign)) {
1121 category = fcInfinity;
1122 return (opStatus) (opOverflow | opInexact);
1123 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001124
1125 /* Otherwise we become the largest finite number. */
1126 category = fcNormal;
1127 exponent = semantics->maxExponent;
1128 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001129 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001130
1131 return opInexact;
1132}
1133
Neil Booth1ca1f802007-10-03 15:16:41 +00001134/* Returns TRUE if, when truncating the current number, with BIT the
1135 new LSB, with the given lost fraction and rounding mode, the result
1136 would need to be rounded away from zero (i.e., by increasing the
1137 signficand). This routine must work for fcZero of both signs, and
1138 fcNormal numbers. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001139bool
1140APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Booth1ca1f802007-10-03 15:16:41 +00001141 lostFraction lost_fraction,
1142 unsigned int bit) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001143{
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001144 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001145 assert(category == fcNormal || category == fcZero);
1146
Neil Booth1ca1f802007-10-03 15:16:41 +00001147 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001148 assert(lost_fraction != lfExactlyZero);
1149
Mike Stump889285d2009-05-13 23:23:20 +00001150 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001151 case rmNearestTiesToAway:
1152 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1153
1154 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001155 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001156 return true;
1157
1158 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001159 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001160 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001161
1162 return false;
1163
1164 case rmTowardZero:
1165 return false;
1166
1167 case rmTowardPositive:
1168 return sign == false;
1169
1170 case rmTowardNegative:
1171 return sign == true;
1172 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001173 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001174}
1175
1176APFloat::opStatus
1177APFloat::normalize(roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001178 lostFraction lost_fraction)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001179{
Neil Booth9acbf5a2007-09-26 21:33:42 +00001180 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001181 int exponentChange;
1182
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001183 if (category != fcNormal)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001184 return opOK;
1185
1186 /* Before rounding normalize the exponent of fcNormal numbers. */
1187 omsb = significandMSB() + 1;
1188
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001189 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001190 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001191 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001192 the exponent. */
1193 exponentChange = omsb - semantics->precision;
1194
1195 /* If the resulting exponent is too high, overflow according to
1196 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001197 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001198 return handleOverflow(rounding_mode);
1199
1200 /* Subnormal numbers have exponent minExponent, and their MSB
1201 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001202 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001203 exponentChange = semantics->minExponent - exponent;
1204
1205 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001206 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001207 assert(lost_fraction == lfExactlyZero);
1208
1209 shiftSignificandLeft(-exponentChange);
1210
1211 return opOK;
1212 }
1213
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001214 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001215 lostFraction lf;
1216
1217 /* Shift right and capture any new lost fraction. */
1218 lf = shiftSignificandRight(exponentChange);
1219
1220 lost_fraction = combineLostFractions(lf, lost_fraction);
1221
1222 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001223 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001224 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001225 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001226 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001227 }
1228 }
1229
1230 /* Now round the number according to rounding_mode given the lost
1231 fraction. */
1232
1233 /* As specified in IEEE 754, since we do not trap we do not report
1234 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001235 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001236 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001237 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001238 category = fcZero;
1239
1240 return opOK;
1241 }
1242
1243 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001244 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1245 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001246 exponent = semantics->minExponent;
1247
1248 incrementSignificand();
1249 omsb = significandMSB() + 1;
1250
1251 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001252 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001253 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001254 significand right one. However if we already have the
1255 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001256 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001257 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001258
Neil Booth9acbf5a2007-09-26 21:33:42 +00001259 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001260 }
1261
1262 shiftSignificandRight(1);
1263
1264 return opInexact;
1265 }
1266 }
1267
1268 /* The normal case - we were and are not denormal, and any
1269 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001270 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001271 return opInexact;
1272
1273 /* We have a non-zero denormal. */
1274 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001275
1276 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001277 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001278 category = fcZero;
1279
1280 /* The fcZero case is a denormal that underflowed to zero. */
1281 return (opStatus) (opUnderflow | opInexact);
1282}
1283
1284APFloat::opStatus
1285APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1286{
Mike Stump889285d2009-05-13 23:23:20 +00001287 switch (convolve(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001288 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001289 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001290
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001291 case convolve(fcNaN, fcZero):
1292 case convolve(fcNaN, fcNormal):
1293 case convolve(fcNaN, fcInfinity):
1294 case convolve(fcNaN, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001295 case convolve(fcNormal, fcZero):
1296 case convolve(fcInfinity, fcNormal):
1297 case convolve(fcInfinity, fcZero):
1298 return opOK;
1299
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001300 case convolve(fcZero, fcNaN):
1301 case convolve(fcNormal, fcNaN):
1302 case convolve(fcInfinity, fcNaN):
1303 category = fcNaN;
1304 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001305 return opOK;
1306
1307 case convolve(fcNormal, fcInfinity):
1308 case convolve(fcZero, fcInfinity):
1309 category = fcInfinity;
1310 sign = rhs.sign ^ subtract;
1311 return opOK;
1312
1313 case convolve(fcZero, fcNormal):
1314 assign(rhs);
1315 sign = rhs.sign ^ subtract;
1316 return opOK;
1317
1318 case convolve(fcZero, fcZero):
1319 /* Sign depends on rounding mode; handled by caller. */
1320 return opOK;
1321
1322 case convolve(fcInfinity, fcInfinity):
1323 /* Differently signed infinities can only be validly
1324 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001325 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001326 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001327 return opInvalidOp;
1328 }
1329
1330 return opOK;
1331
1332 case convolve(fcNormal, fcNormal):
1333 return opDivByZero;
1334 }
1335}
1336
1337/* Add or subtract two normal numbers. */
1338lostFraction
1339APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1340{
1341 integerPart carry;
1342 lostFraction lost_fraction;
1343 int bits;
1344
1345 /* Determine if the operation on the absolute values is effectively
1346 an addition or subtraction. */
Hartmut Kaiserfc69d322007-10-25 23:15:31 +00001347 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001348
1349 /* Are we bigger exponent-wise than the RHS? */
1350 bits = exponent - rhs.exponent;
1351
1352 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001353 if (subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001354 APFloat temp_rhs(rhs);
1355 bool reverse;
1356
Chris Lattner3da18eb2007-08-24 03:02:34 +00001357 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001358 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1359 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001360 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001361 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1362 shiftSignificandLeft(1);
1363 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001364 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001365 lost_fraction = shiftSignificandRight(-bits - 1);
1366 temp_rhs.shiftSignificandLeft(1);
1367 reverse = true;
1368 }
1369
Chris Lattner3da18eb2007-08-24 03:02:34 +00001370 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001371 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001372 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001373 copySignificand(temp_rhs);
1374 sign = !sign;
1375 } else {
1376 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001377 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001378 }
1379
1380 /* Invert the lost fraction - it was on the RHS and
1381 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001382 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001383 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001384 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001385 lost_fraction = lfLessThanHalf;
1386
1387 /* The code above is intended to ensure that no borrow is
1388 necessary. */
1389 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001390 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001391 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001392 if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001393 APFloat temp_rhs(rhs);
1394
1395 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1396 carry = addSignificand(temp_rhs);
1397 } else {
1398 lost_fraction = shiftSignificandRight(-bits);
1399 carry = addSignificand(rhs);
1400 }
1401
1402 /* We have a guard bit; generating a carry cannot happen. */
1403 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001404 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001405 }
1406
1407 return lost_fraction;
1408}
1409
1410APFloat::opStatus
1411APFloat::multiplySpecials(const APFloat &rhs)
1412{
Mike Stump889285d2009-05-13 23:23:20 +00001413 switch (convolve(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001414 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001415 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001416
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001417 case convolve(fcNaN, fcZero):
1418 case convolve(fcNaN, fcNormal):
1419 case convolve(fcNaN, fcInfinity):
1420 case convolve(fcNaN, fcNaN):
1421 return opOK;
1422
1423 case convolve(fcZero, fcNaN):
1424 case convolve(fcNormal, fcNaN):
1425 case convolve(fcInfinity, fcNaN):
1426 category = fcNaN;
1427 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001428 return opOK;
1429
1430 case convolve(fcNormal, fcInfinity):
1431 case convolve(fcInfinity, fcNormal):
1432 case convolve(fcInfinity, fcInfinity):
1433 category = fcInfinity;
1434 return opOK;
1435
1436 case convolve(fcZero, fcNormal):
1437 case convolve(fcNormal, fcZero):
1438 case convolve(fcZero, fcZero):
1439 category = fcZero;
1440 return opOK;
1441
1442 case convolve(fcZero, fcInfinity):
1443 case convolve(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001444 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001445 return opInvalidOp;
1446
1447 case convolve(fcNormal, fcNormal):
1448 return opOK;
1449 }
1450}
1451
1452APFloat::opStatus
1453APFloat::divideSpecials(const APFloat &rhs)
1454{
Mike Stump889285d2009-05-13 23:23:20 +00001455 switch (convolve(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001456 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001457 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001458
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001459 case convolve(fcNaN, fcZero):
1460 case convolve(fcNaN, fcNormal):
1461 case convolve(fcNaN, fcInfinity):
1462 case convolve(fcNaN, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001463 case convolve(fcInfinity, fcZero):
1464 case convolve(fcInfinity, fcNormal):
1465 case convolve(fcZero, fcInfinity):
1466 case convolve(fcZero, fcNormal):
1467 return opOK;
1468
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001469 case convolve(fcZero, fcNaN):
1470 case convolve(fcNormal, fcNaN):
1471 case convolve(fcInfinity, fcNaN):
1472 category = fcNaN;
1473 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001474 return opOK;
1475
1476 case convolve(fcNormal, fcInfinity):
1477 category = fcZero;
1478 return opOK;
1479
1480 case convolve(fcNormal, fcZero):
1481 category = fcInfinity;
1482 return opDivByZero;
1483
1484 case convolve(fcInfinity, fcInfinity):
1485 case convolve(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001486 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001487 return opInvalidOp;
1488
1489 case convolve(fcNormal, fcNormal):
1490 return opOK;
1491 }
1492}
1493
Dale Johannesenb5721632009-01-21 00:35:19 +00001494APFloat::opStatus
1495APFloat::modSpecials(const APFloat &rhs)
1496{
Mike Stump889285d2009-05-13 23:23:20 +00001497 switch (convolve(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001498 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001499 llvm_unreachable(0);
Dale Johannesenb5721632009-01-21 00:35:19 +00001500
1501 case convolve(fcNaN, fcZero):
1502 case convolve(fcNaN, fcNormal):
1503 case convolve(fcNaN, fcInfinity):
1504 case convolve(fcNaN, fcNaN):
1505 case convolve(fcZero, fcInfinity):
1506 case convolve(fcZero, fcNormal):
1507 case convolve(fcNormal, fcInfinity):
1508 return opOK;
1509
1510 case convolve(fcZero, fcNaN):
1511 case convolve(fcNormal, fcNaN):
1512 case convolve(fcInfinity, fcNaN):
1513 category = fcNaN;
1514 copySignificand(rhs);
1515 return opOK;
1516
1517 case convolve(fcNormal, fcZero):
1518 case convolve(fcInfinity, fcZero):
1519 case convolve(fcInfinity, fcNormal):
1520 case convolve(fcInfinity, fcInfinity):
1521 case convolve(fcZero, fcZero):
1522 makeNaN();
1523 return opInvalidOp;
1524
1525 case convolve(fcNormal, fcNormal):
1526 return opOK;
1527 }
1528}
1529
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001530/* Change sign. */
1531void
1532APFloat::changeSign()
1533{
1534 /* Look mummy, this one's easy. */
1535 sign = !sign;
1536}
1537
Dale Johannesen689d17d2007-08-31 23:35:31 +00001538void
1539APFloat::clearSign()
1540{
1541 /* So is this one. */
1542 sign = 0;
1543}
1544
1545void
1546APFloat::copySign(const APFloat &rhs)
1547{
1548 /* And this one. */
1549 sign = rhs.sign;
1550}
1551
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001552/* Normalized addition or subtraction. */
1553APFloat::opStatus
1554APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001555 bool subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001556{
1557 opStatus fs;
1558
1559 fs = addOrSubtractSpecials(rhs, subtract);
1560
1561 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001562 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001563 lostFraction lost_fraction;
1564
1565 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1566 fs = normalize(rounding_mode, lost_fraction);
1567
1568 /* Can only be zero if we lost no fraction. */
1569 assert(category != fcZero || lost_fraction == lfExactlyZero);
1570 }
1571
1572 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1573 positive zero unless rounding to minus infinity, except that
1574 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001575 if (category == fcZero) {
1576 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001577 sign = (rounding_mode == rmTowardNegative);
1578 }
1579
1580 return fs;
1581}
1582
1583/* Normalized addition. */
1584APFloat::opStatus
1585APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1586{
1587 return addOrSubtract(rhs, rounding_mode, false);
1588}
1589
1590/* Normalized subtraction. */
1591APFloat::opStatus
1592APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1593{
1594 return addOrSubtract(rhs, rounding_mode, true);
1595}
1596
1597/* Normalized multiply. */
1598APFloat::opStatus
1599APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1600{
1601 opStatus fs;
1602
1603 sign ^= rhs.sign;
1604 fs = multiplySpecials(rhs);
1605
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001606 if (category == fcNormal) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001607 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1608 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001609 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001610 fs = (opStatus) (fs | opInexact);
1611 }
1612
1613 return fs;
1614}
1615
1616/* Normalized divide. */
1617APFloat::opStatus
1618APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1619{
1620 opStatus fs;
1621
1622 sign ^= rhs.sign;
1623 fs = divideSpecials(rhs);
1624
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001625 if (category == fcNormal) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001626 lostFraction lost_fraction = divideSignificand(rhs);
1627 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001628 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001629 fs = (opStatus) (fs | opInexact);
1630 }
1631
1632 return fs;
1633}
1634
Dale Johannesenfe750172009-01-20 18:35:05 +00001635/* Normalized remainder. This is not currently correct in all cases. */
1636APFloat::opStatus
1637APFloat::remainder(const APFloat &rhs)
1638{
1639 opStatus fs;
1640 APFloat V = *this;
1641 unsigned int origSign = sign;
1642
Dale Johannesenfe750172009-01-20 18:35:05 +00001643 fs = V.divide(rhs, rmNearestTiesToEven);
1644 if (fs == opDivByZero)
1645 return fs;
1646
1647 int parts = partCount();
1648 integerPart *x = new integerPart[parts];
1649 bool ignored;
1650 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1651 rmNearestTiesToEven, &ignored);
1652 if (fs==opInvalidOp)
1653 return fs;
1654
1655 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1656 rmNearestTiesToEven);
1657 assert(fs==opOK); // should always work
1658
1659 fs = V.multiply(rhs, rmNearestTiesToEven);
1660 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1661
1662 fs = subtract(V, rmNearestTiesToEven);
1663 assert(fs==opOK || fs==opInexact); // likewise
1664
1665 if (isZero())
1666 sign = origSign; // IEEE754 requires this
1667 delete[] x;
1668 return fs;
1669}
1670
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001671/* Normalized llvm frem (C fmod).
Dale Johannesenfe750172009-01-20 18:35:05 +00001672 This is not currently correct in all cases. */
Dale Johannesen689d17d2007-08-31 23:35:31 +00001673APFloat::opStatus
1674APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1675{
1676 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001677 fs = modSpecials(rhs);
Dale Johannesen689d17d2007-08-31 23:35:31 +00001678
Dale Johannesenb5721632009-01-21 00:35:19 +00001679 if (category == fcNormal && rhs.category == fcNormal) {
1680 APFloat V = *this;
1681 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001682
Dale Johannesenb5721632009-01-21 00:35:19 +00001683 fs = V.divide(rhs, rmNearestTiesToEven);
1684 if (fs == opDivByZero)
1685 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001686
Dale Johannesenb5721632009-01-21 00:35:19 +00001687 int parts = partCount();
1688 integerPart *x = new integerPart[parts];
1689 bool ignored;
1690 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1691 rmTowardZero, &ignored);
1692 if (fs==opInvalidOp)
1693 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001694
Dale Johannesenb5721632009-01-21 00:35:19 +00001695 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1696 rmNearestTiesToEven);
1697 assert(fs==opOK); // should always work
Dale Johannesen728687c2007-09-05 20:39:49 +00001698
Dale Johannesenb5721632009-01-21 00:35:19 +00001699 fs = V.multiply(rhs, rounding_mode);
1700 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1701
1702 fs = subtract(V, rounding_mode);
1703 assert(fs==opOK || fs==opInexact); // likewise
1704
1705 if (isZero())
1706 sign = origSign; // IEEE754 requires this
1707 delete[] x;
1708 }
Dale Johannesen689d17d2007-08-31 23:35:31 +00001709 return fs;
1710}
1711
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001712/* Normalized fused-multiply-add. */
1713APFloat::opStatus
1714APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001715 const APFloat &addend,
1716 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001717{
1718 opStatus fs;
1719
1720 /* Post-multiplication sign, before addition. */
1721 sign ^= multiplicand.sign;
1722
1723 /* If and only if all arguments are normal do we need to do an
1724 extended-precision calculation. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001725 if (category == fcNormal &&
1726 multiplicand.category == fcNormal &&
1727 addend.category == fcNormal) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001728 lostFraction lost_fraction;
1729
1730 lost_fraction = multiplySignificand(multiplicand, &addend);
1731 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001732 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001733 fs = (opStatus) (fs | opInexact);
1734
1735 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1736 positive zero unless rounding to minus infinity, except that
1737 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001738 if (category == fcZero && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001739 sign = (rounding_mode == rmTowardNegative);
1740 } else {
1741 fs = multiplySpecials(multiplicand);
1742
1743 /* FS can only be opOK or opInvalidOp. There is no more work
1744 to do in the latter case. The IEEE-754R standard says it is
1745 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001746 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001747
1748 If we need to do the addition we can do so with normal
1749 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001750 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001751 fs = addOrSubtract(addend, rounding_mode, false);
1752 }
1753
1754 return fs;
1755}
1756
Owen Andersona40319b2012-08-13 23:32:49 +00001757/* Rounding-mode corrrect round to integral value. */
1758APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
1759 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001760
Owen Anderson352dfff2012-08-15 18:28:45 +00001761 // If the exponent is large enough, we know that this value is already
1762 // integral, and the arithmetic below would potentially cause it to saturate
1763 // to +/-Inf. Bail out early instead.
Benjamin Kramerc38fab22012-09-26 14:06:58 +00001764 if (category == fcNormal && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001765 return opOK;
1766
Owen Andersona40319b2012-08-13 23:32:49 +00001767 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1768 // precision of our format, and then subtract it back off again. The choice
1769 // of rounding modes for the addition/subtraction determines the rounding mode
1770 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001771 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001772 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001773 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1774 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Owen Andersona40319b2012-08-13 23:32:49 +00001775 APFloat MagicConstant(*semantics);
1776 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1777 rmNearestTiesToEven);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001778 MagicConstant.copySign(*this);
1779
Owen Andersona40319b2012-08-13 23:32:49 +00001780 if (fs != opOK)
1781 return fs;
1782
Owen Anderson1ff74b02012-08-15 05:39:46 +00001783 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1784 bool inputSign = isNegative();
1785
Owen Andersona40319b2012-08-13 23:32:49 +00001786 fs = add(MagicConstant, rounding_mode);
1787 if (fs != opOK && fs != opInexact)
1788 return fs;
1789
1790 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001791
1792 // Restore the input sign.
1793 if (inputSign != isNegative())
1794 changeSign();
1795
Owen Andersona40319b2012-08-13 23:32:49 +00001796 return fs;
1797}
1798
1799
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001800/* Comparison requires normalized numbers. */
1801APFloat::cmpResult
1802APFloat::compare(const APFloat &rhs) const
1803{
1804 cmpResult result;
1805
1806 assert(semantics == rhs.semantics);
1807
Mike Stump889285d2009-05-13 23:23:20 +00001808 switch (convolve(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001809 default:
Torok Edwinfbcc6632009-07-14 16:55:14 +00001810 llvm_unreachable(0);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001811
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001812 case convolve(fcNaN, fcZero):
1813 case convolve(fcNaN, fcNormal):
1814 case convolve(fcNaN, fcInfinity):
1815 case convolve(fcNaN, fcNaN):
1816 case convolve(fcZero, fcNaN):
1817 case convolve(fcNormal, fcNaN):
1818 case convolve(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001819 return cmpUnordered;
1820
1821 case convolve(fcInfinity, fcNormal):
1822 case convolve(fcInfinity, fcZero):
1823 case convolve(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001824 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001825 return cmpLessThan;
1826 else
1827 return cmpGreaterThan;
1828
1829 case convolve(fcNormal, fcInfinity):
1830 case convolve(fcZero, fcInfinity):
1831 case convolve(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001832 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001833 return cmpGreaterThan;
1834 else
1835 return cmpLessThan;
1836
1837 case convolve(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001838 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001839 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001840 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001841 return cmpLessThan;
1842 else
1843 return cmpGreaterThan;
1844
1845 case convolve(fcZero, fcZero):
1846 return cmpEqual;
1847
1848 case convolve(fcNormal, fcNormal):
1849 break;
1850 }
1851
1852 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001853 if (sign != rhs.sign) {
1854 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001855 result = cmpLessThan;
1856 else
1857 result = cmpGreaterThan;
1858 } else {
1859 /* Compare absolute values; invert result if negative. */
1860 result = compareAbsoluteValue(rhs);
1861
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001862 if (sign) {
1863 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001864 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001865 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001866 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001867 }
1868 }
1869
1870 return result;
1871}
1872
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001873/// APFloat::convert - convert a value of one floating point type to another.
1874/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1875/// records whether the transformation lost information, i.e. whether
1876/// converting the result back to the original type will produce the
1877/// original value (this is almost the same as return value==fsOK, but there
1878/// are edge cases where this is not so).
1879
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001880APFloat::opStatus
1881APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001882 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001883{
Neil Bootha8d72692007-09-22 02:56:19 +00001884 lostFraction lostFraction;
1885 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001886 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001887 int shift;
1888 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001889
Neil Bootha8d72692007-09-22 02:56:19 +00001890 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001891 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001892 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001893 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001894
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001895 bool X86SpecialNan = false;
1896 if (&fromSemantics == &APFloat::x87DoubleExtended &&
1897 &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
1898 (!(*significandParts() & 0x8000000000000000ULL) ||
1899 !(*significandParts() & 0x4000000000000000ULL))) {
1900 // x86 has some unusual NaNs which cannot be represented in any other
1901 // format; note them here.
1902 X86SpecialNan = true;
1903 }
1904
1905 // If this is a truncation, perform the shift before we narrow the storage.
1906 if (shift < 0 && (category==fcNormal || category==fcNaN))
1907 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1908
1909 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00001910 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001911 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001912 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001913 newParts = new integerPart[newPartCount];
1914 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001915 if (category==fcNormal || category==fcNaN)
1916 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001917 freeSignificand();
1918 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001919 } else if (newPartCount == 1 && oldPartCount != 1) {
1920 // Switch to built-in storage for a single part.
1921 integerPart newPart = 0;
1922 if (category==fcNormal || category==fcNaN)
1923 newPart = significandParts()[0];
1924 freeSignificand();
1925 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001926 }
1927
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001928 // Now that we have the right storage, switch the semantics.
1929 semantics = &toSemantics;
1930
1931 // If this is an extension, perform the shift now that the storage is
1932 // available.
1933 if (shift > 0 && (category==fcNormal || category==fcNaN))
1934 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1935
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001936 if (category == fcNormal) {
Neil Bootha8d72692007-09-22 02:56:19 +00001937 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001938 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001939 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001940 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00001941
1942 // For x87 extended precision, we want to make a NaN, not a special NaN if
1943 // the input wasn't special either.
1944 if (!X86SpecialNan && semantics == &APFloat::x87DoubleExtended)
1945 APInt::tcSetBit(significandParts(), semantics->precision - 1);
1946
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001947 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1948 // does not give you back the same bits. This is dubious, and we
1949 // don't currently do it. You're really supposed to get
1950 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001951 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001952 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001953 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00001954 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001955 }
1956
1957 return fs;
1958}
1959
1960/* Convert a floating point number to an integer according to the
1961 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00001962 returns an invalid operation exception and the contents of the
1963 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001964 range but the floating point number is not the exact integer, the C
1965 standard doesn't require an inexact exception to be raised. IEEE
1966 854 does require it so we do that.
1967
1968 Note that for conversions to integer type the C standard requires
1969 round-to-zero to always be used. */
1970APFloat::opStatus
Neil Booth618d0fc2007-11-01 22:43:37 +00001971APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1972 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001973 roundingMode rounding_mode,
1974 bool *isExact) const
Neil Booth618d0fc2007-11-01 22:43:37 +00001975{
1976 lostFraction lost_fraction;
1977 const integerPart *src;
1978 unsigned int dstPartsCount, truncatedBits;
1979
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001980 *isExact = false;
1981
Neil Booth618d0fc2007-11-01 22:43:37 +00001982 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001983 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00001984 return opInvalidOp;
1985
1986 dstPartsCount = partCountForBits(width);
1987
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001988 if (category == fcZero) {
Neil Booth618d0fc2007-11-01 22:43:37 +00001989 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00001990 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001991 *isExact = !sign;
1992 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00001993 }
1994
1995 src = significandParts();
1996
1997 /* Step 1: place our absolute value, with any fraction truncated, in
1998 the destination. */
1999 if (exponent < 0) {
2000 /* Our absolute value is less than one; truncate everything. */
2001 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002002 /* For exponent -1 the integer bit represents .5, look at that.
2003 For smaller exponents leftmost truncated bit is 0. */
2004 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002005 } else {
2006 /* We want the most significant (exponent + 1) bits; the rest are
2007 truncated. */
2008 unsigned int bits = exponent + 1U;
2009
2010 /* Hopelessly large in magnitude? */
2011 if (bits > width)
2012 return opInvalidOp;
2013
2014 if (bits < semantics->precision) {
2015 /* We truncate (semantics->precision - bits) bits. */
2016 truncatedBits = semantics->precision - bits;
2017 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2018 } else {
2019 /* We want at least as many bits as are available. */
2020 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2021 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2022 truncatedBits = 0;
2023 }
2024 }
2025
2026 /* Step 2: work out any lost fraction, and increment the absolute
2027 value if we would round away from zero. */
2028 if (truncatedBits) {
2029 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2030 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002031 if (lost_fraction != lfExactlyZero &&
2032 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002033 if (APInt::tcIncrement(parts, dstPartsCount))
2034 return opInvalidOp; /* Overflow. */
2035 }
2036 } else {
2037 lost_fraction = lfExactlyZero;
2038 }
2039
2040 /* Step 3: check if we fit in the destination. */
2041 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2042
2043 if (sign) {
2044 if (!isSigned) {
2045 /* Negative numbers cannot be represented as unsigned. */
2046 if (omsb != 0)
2047 return opInvalidOp;
2048 } else {
2049 /* It takes omsb bits to represent the unsigned integer value.
2050 We lose a bit for the sign, but care is needed as the
2051 maximally negative integer is a special case. */
2052 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2053 return opInvalidOp;
2054
2055 /* This case can happen because of rounding. */
2056 if (omsb > width)
2057 return opInvalidOp;
2058 }
2059
2060 APInt::tcNegate (parts, dstPartsCount);
2061 } else {
2062 if (omsb >= width + !isSigned)
2063 return opInvalidOp;
2064 }
2065
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002066 if (lost_fraction == lfExactlyZero) {
2067 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002068 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002069 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002070 return opInexact;
2071}
2072
2073/* Same as convertToSignExtendedInteger, except we provide
2074 deterministic values in case of an invalid operation exception,
2075 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002076 for underflow or overflow.
2077 The *isExact output tells whether the result is exact, in the sense
2078 that converting it back to the original floating point type produces
2079 the original value. This is almost equivalent to result==opOK,
2080 except for negative zeroes.
2081*/
Neil Booth618d0fc2007-11-01 22:43:37 +00002082APFloat::opStatus
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002083APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth9acbf5a2007-09-26 21:33:42 +00002084 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002085 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002086{
Neil Booth618d0fc2007-11-01 22:43:37 +00002087 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002088
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002089 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002090 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002091
Neil Booth618d0fc2007-11-01 22:43:37 +00002092 if (fs == opInvalidOp) {
2093 unsigned int bits, dstPartsCount;
2094
2095 dstPartsCount = partCountForBits(width);
2096
2097 if (category == fcNaN)
2098 bits = 0;
2099 else if (sign)
2100 bits = isSigned;
2101 else
2102 bits = width - isSigned;
2103
2104 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2105 if (sign && isSigned)
2106 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002107 }
2108
Neil Booth618d0fc2007-11-01 22:43:37 +00002109 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002110}
2111
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002112/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2113 an APSInt, whose initial bit-width and signed-ness are used to determine the
2114 precision of the conversion.
2115 */
2116APFloat::opStatus
2117APFloat::convertToInteger(APSInt &result,
2118 roundingMode rounding_mode, bool *isExact) const
2119{
2120 unsigned bitWidth = result.getBitWidth();
2121 SmallVector<uint64_t, 4> parts(result.getNumWords());
2122 opStatus status = convertToInteger(
2123 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2124 // Keeps the original signed-ness.
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002125 result = APInt(bitWidth, parts);
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002126 return status;
2127}
2128
Neil Booth6c1c8582007-10-07 12:07:53 +00002129/* Convert an unsigned integer SRC to a floating point number,
2130 rounding according to ROUNDING_MODE. The sign of the floating
2131 point number is not modified. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002132APFloat::opStatus
Neil Booth6c1c8582007-10-07 12:07:53 +00002133APFloat::convertFromUnsignedParts(const integerPart *src,
2134 unsigned int srcCount,
2135 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002136{
Neil Booth49c6aab2007-10-08 14:39:42 +00002137 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002138 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002139 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002140
2141 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002142 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002143 dst = significandParts();
2144 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002145 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002146
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002147 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002148 be that many; extract what we can. */
2149 if (precision <= omsb) {
2150 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002151 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002152 omsb - precision);
2153 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2154 } else {
2155 exponent = precision - 1;
2156 lost_fraction = lfExactlyZero;
2157 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002158 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002159
2160 return normalize(rounding_mode, lost_fraction);
2161}
2162
Dan Gohman35723eb2008-02-29 01:26:11 +00002163APFloat::opStatus
2164APFloat::convertFromAPInt(const APInt &Val,
2165 bool isSigned,
2166 roundingMode rounding_mode)
2167{
2168 unsigned int partCount = Val.getNumWords();
2169 APInt api = Val;
2170
2171 sign = false;
2172 if (isSigned && api.isNegative()) {
2173 sign = true;
2174 api = -api;
2175 }
2176
2177 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2178}
2179
Neil Booth03f58ab2007-10-07 12:15:41 +00002180/* Convert a two's complement integer SRC to a floating point number,
2181 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2182 integer is signed, in which case it must be sign-extended. */
2183APFloat::opStatus
2184APFloat::convertFromSignExtendedInteger(const integerPart *src,
2185 unsigned int srcCount,
2186 bool isSigned,
2187 roundingMode rounding_mode)
2188{
2189 opStatus status;
2190
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002191 if (isSigned &&
2192 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002193 integerPart *copy;
2194
2195 /* If we're signed and negative negate a copy. */
2196 sign = true;
2197 copy = new integerPart[srcCount];
2198 APInt::tcAssign(copy, src, srcCount);
2199 APInt::tcNegate(copy, srcCount);
2200 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2201 delete [] copy;
2202 } else {
2203 sign = false;
2204 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2205 }
2206
2207 return status;
2208}
2209
Neil Booth5f009732007-10-07 11:45:55 +00002210/* FIXME: should this just take a const APInt reference? */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002211APFloat::opStatus
Neil Booth5f009732007-10-07 11:45:55 +00002212APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2213 unsigned int width, bool isSigned,
2214 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002215{
Dale Johannesen42305122007-09-21 22:09:37 +00002216 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002217 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002218
2219 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002220 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002221 sign = true;
2222 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002223 }
2224
Neil Boothba205222007-10-07 12:10:57 +00002225 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002226}
2227
2228APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002229APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002230{
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002231 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002232 integerPart *significand;
2233 unsigned int bitPos, partsCount;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002234 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002235
2236 zeroSignificand();
2237 exponent = 0;
2238 category = fcNormal;
2239
2240 significand = significandParts();
2241 partsCount = partCount();
2242 bitPos = partsCount * integerPartWidth;
2243
Neil Boothd3985922007-10-07 08:51:21 +00002244 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002245 StringRef::iterator begin = s.begin();
2246 StringRef::iterator end = s.end();
2247 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002248 firstSignificantDigit = p;
2249
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002250 for (; p != end;) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002251 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002252
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002253 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002254 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002255 dot = p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002256 if (p == end) {
2257 break;
2258 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002259 }
2260
2261 hex_value = hexDigitValue(*p);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002262 if (hex_value == -1U) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002263 break;
2264 }
2265
2266 p++;
2267
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002268 if (p == end) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002269 break;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002270 } else {
2271 /* Store the number whilst 4-bit nibbles remain. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002272 if (bitPos) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002273 bitPos -= 4;
2274 hex_value <<= bitPos % integerPartWidth;
2275 significand[bitPos / integerPartWidth] |= hex_value;
2276 } else {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002277 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002278 while (p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002279 p++;
2280 break;
2281 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002282 }
2283 }
2284
2285 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002286 assert(p != end && "Hex strings require an exponent");
2287 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2288 assert(p != begin && "Significand has no digits");
2289 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002290
2291 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002292 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002293 int expAdjustment;
2294
2295 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002296 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002297 dot = p;
2298
2299 /* Calculate the exponent adjustment implicit in the number of
2300 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002301 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002302 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002303 expAdjustment++;
2304 expAdjustment = expAdjustment * 4 - 1;
2305
2306 /* Adjust for writing the significand starting at the most
2307 significant nibble. */
2308 expAdjustment += semantics->precision;
2309 expAdjustment -= partsCount * integerPartWidth;
2310
2311 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002312 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002313 }
2314
2315 return normalize(rounding_mode, lost_fraction);
2316}
2317
2318APFloat::opStatus
Neil Boothb93d90e2007-10-12 16:02:31 +00002319APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2320 unsigned sigPartCount, int exp,
2321 roundingMode rounding_mode)
2322{
2323 unsigned int parts, pow5PartCount;
Ulrich Weigand908c9362012-10-29 18:18:44 +00002324 fltSemantics calcSemantics = { 32767, -32767, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002325 integerPart pow5Parts[maxPowerOfFiveParts];
2326 bool isNearest;
2327
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002328 isNearest = (rounding_mode == rmNearestTiesToEven ||
2329 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002330
2331 parts = partCountForBits(semantics->precision + 11);
2332
2333 /* Calculate pow(5, abs(exp)). */
2334 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2335
2336 for (;; parts *= 2) {
2337 opStatus sigStatus, powStatus;
2338 unsigned int excessPrecision, truncatedBits;
2339
2340 calcSemantics.precision = parts * integerPartWidth - 1;
2341 excessPrecision = calcSemantics.precision - semantics->precision;
2342 truncatedBits = excessPrecision;
2343
2344 APFloat decSig(calcSemantics, fcZero, sign);
2345 APFloat pow5(calcSemantics, fcZero, false);
2346
2347 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2348 rmNearestTiesToEven);
2349 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2350 rmNearestTiesToEven);
2351 /* Add exp, as 10^n = 5^n * 2^n. */
2352 decSig.exponent += exp;
2353
2354 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002355 integerPart HUerr, HUdistance;
2356 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002357
2358 if (exp >= 0) {
2359 /* multiplySignificand leaves the precision-th bit set to 1. */
2360 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2361 powHUerr = powStatus != opOK;
2362 } else {
2363 calcLostFraction = decSig.divideSignificand(pow5);
2364 /* Denormal numbers have less precision. */
2365 if (decSig.exponent < semantics->minExponent) {
2366 excessPrecision += (semantics->minExponent - decSig.exponent);
2367 truncatedBits = excessPrecision;
2368 if (excessPrecision > calcSemantics.precision)
2369 excessPrecision = calcSemantics.precision;
2370 }
2371 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002372 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002373 }
2374
2375 /* Both multiplySignificand and divideSignificand return the
2376 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002377 assert(APInt::tcExtractBit
2378 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002379
2380 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2381 powHUerr);
2382 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2383 excessPrecision, isNearest);
2384
2385 /* Are we guaranteed to round correctly if we truncate? */
2386 if (HUdistance >= HUerr) {
2387 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2388 calcSemantics.precision - excessPrecision,
2389 excessPrecision);
2390 /* Take the exponent of decSig. If we tcExtract-ed less bits
2391 above we must adjust our exponent to compensate for the
2392 implicit right shift. */
2393 exponent = (decSig.exponent + semantics->precision
2394 - (calcSemantics.precision - excessPrecision));
2395 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2396 decSig.partCount(),
2397 truncatedBits);
2398 return normalize(rounding_mode, calcLostFraction);
2399 }
2400 }
2401}
2402
2403APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002404APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Boothb93d90e2007-10-12 16:02:31 +00002405{
Neil Booth4ed401b2007-10-14 10:16:12 +00002406 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002407 opStatus fs;
2408
Neil Booth4ed401b2007-10-14 10:16:12 +00002409 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002410 StringRef::iterator p = str.begin();
2411 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002412
Neil Booth91305512007-10-15 15:00:55 +00002413 /* Handle the quick cases. First the case of no significant digits,
2414 i.e. zero, and then exponents that are obviously too large or too
2415 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2416 definitely overflows if
2417
2418 (exp - 1) * L >= maxExponent
2419
2420 and definitely underflows to zero where
2421
2422 (exp + 1) * L <= minExponent - precision
2423
2424 With integer arithmetic the tightest bounds for L are
2425
2426 93/28 < L < 196/59 [ numerator <= 256 ]
2427 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2428 */
2429
Neil Booth06f20ea2007-12-05 13:06:04 +00002430 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002431 category = fcZero;
2432 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002433
2434 /* Check whether the normalized exponent is high enough to overflow
2435 max during the log-rebasing in the max-exponent check below. */
2436 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2437 fs = handleOverflow(rounding_mode);
2438
2439 /* If it wasn't, then it also wasn't high enough to overflow max
2440 during the log-rebasing in the min-exponent check. Check that it
2441 won't overflow min in either check, then perform the min-exponent
2442 check. */
2443 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2444 (D.normalizedExponent + 1) * 28738 <=
2445 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002446 /* Underflow to zero and round. */
2447 zeroSignificand();
2448 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002449
2450 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002451 } else if ((D.normalizedExponent - 1) * 42039
2452 >= 12655 * semantics->maxExponent) {
2453 /* Overflow and round. */
2454 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002455 } else {
Neil Booth4ed401b2007-10-14 10:16:12 +00002456 integerPart *decSignificand;
2457 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002458
Neil Booth4ed401b2007-10-14 10:16:12 +00002459 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002460 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002461 to hold the full significand, and an extra part required by
2462 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002463 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002464 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth4ed401b2007-10-14 10:16:12 +00002465 decSignificand = new integerPart[partCount + 1];
2466 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002467
Neil Booth4ed401b2007-10-14 10:16:12 +00002468 /* Convert to binary efficiently - we do almost all multiplication
2469 in an integerPart. When this would overflow do we do a single
2470 bignum multiplication, and then revert again to multiplication
2471 in an integerPart. */
2472 do {
2473 integerPart decValue, val, multiplier;
2474
2475 val = 0;
2476 multiplier = 1;
2477
2478 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002479 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002480 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002481 if (p == str.end()) {
2482 break;
2483 }
2484 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002485 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002486 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002487 multiplier *= 10;
2488 val = val * 10 + decValue;
2489 /* The maximum number that can be multiplied by ten with any
2490 digit added without overflowing an integerPart. */
2491 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2492
2493 /* Multiply out the current part. */
2494 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2495 partCount, partCount + 1, false);
2496
2497 /* If we used another part (likely but not guaranteed), increase
2498 the count. */
2499 if (decSignificand[partCount])
2500 partCount++;
2501 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002502
Neil Boothae077d22007-11-01 22:51:07 +00002503 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002504 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002505 D.exponent, rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002506
Neil Booth4ed401b2007-10-14 10:16:12 +00002507 delete [] decSignificand;
2508 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002509
2510 return fs;
2511}
2512
2513APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002514APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth9acbf5a2007-09-26 21:33:42 +00002515{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002516 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002517
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002518 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002519 StringRef::iterator p = str.begin();
2520 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002521 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002522 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002523 p++;
2524 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002525 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002526 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002527
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002528 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002529 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002530 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002531 rounding_mode);
2532 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002533
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002534 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002535}
Dale Johannesena719a602007-08-24 00:56:33 +00002536
Neil Booth8f1946f2007-10-03 22:26:02 +00002537/* Write out a hexadecimal representation of the floating point value
2538 to DST, which must be of sufficient size, in the C99 form
2539 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2540 excluding the terminating NUL.
2541
2542 If UPPERCASE, the output is in upper case, otherwise in lower case.
2543
2544 HEXDIGITS digits appear altogether, rounding the value if
2545 necessary. If HEXDIGITS is 0, the minimal precision to display the
2546 number precisely is used instead. If nothing would appear after
2547 the decimal point it is suppressed.
2548
2549 The decimal exponent is always printed and has at least one digit.
2550 Zero values display an exponent of zero. Infinities and NaNs
2551 appear as "infinity" or "nan" respectively.
2552
2553 The above rules are as specified by C99. There is ambiguity about
2554 what the leading hexadecimal digit should be. This implementation
2555 uses whatever is necessary so that the exponent is displayed as
2556 stored. This implies the exponent will fall within the IEEE format
2557 range, and the leading hexadecimal digit will be 0 (for denormals),
2558 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2559 any other digits zero).
2560*/
2561unsigned int
2562APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2563 bool upperCase, roundingMode rounding_mode) const
2564{
2565 char *p;
2566
2567 p = dst;
2568 if (sign)
2569 *dst++ = '-';
2570
2571 switch (category) {
2572 case fcInfinity:
2573 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2574 dst += sizeof infinityL - 1;
2575 break;
2576
2577 case fcNaN:
2578 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2579 dst += sizeof NaNU - 1;
2580 break;
2581
2582 case fcZero:
2583 *dst++ = '0';
2584 *dst++ = upperCase ? 'X': 'x';
2585 *dst++ = '0';
2586 if (hexDigits > 1) {
2587 *dst++ = '.';
2588 memset (dst, '0', hexDigits - 1);
2589 dst += hexDigits - 1;
2590 }
2591 *dst++ = upperCase ? 'P': 'p';
2592 *dst++ = '0';
2593 break;
2594
2595 case fcNormal:
2596 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2597 break;
2598 }
2599
2600 *dst = 0;
2601
Evan Cheng82b9e962008-05-02 21:15:08 +00002602 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002603}
2604
2605/* Does the hard work of outputting the correctly rounded hexadecimal
2606 form of a normal floating point number with the specified number of
2607 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2608 digits necessary to print the value precisely is output. */
2609char *
2610APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2611 bool upperCase,
2612 roundingMode rounding_mode) const
2613{
2614 unsigned int count, valueBits, shift, partsCount, outputDigits;
2615 const char *hexDigitChars;
2616 const integerPart *significand;
2617 char *p;
2618 bool roundUp;
2619
2620 *dst++ = '0';
2621 *dst++ = upperCase ? 'X': 'x';
2622
2623 roundUp = false;
2624 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2625
2626 significand = significandParts();
2627 partsCount = partCount();
2628
2629 /* +3 because the first digit only uses the single integer bit, so
2630 we have 3 virtual zero most-significant-bits. */
2631 valueBits = semantics->precision + 3;
2632 shift = integerPartWidth - valueBits % integerPartWidth;
2633
2634 /* The natural number of digits required ignoring trailing
2635 insignificant zeroes. */
2636 outputDigits = (valueBits - significandLSB () + 3) / 4;
2637
2638 /* hexDigits of zero means use the required number for the
2639 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002640 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002641 if (hexDigits) {
2642 if (hexDigits < outputDigits) {
2643 /* We are dropping non-zero bits, so need to check how to round.
2644 "bits" is the number of dropped bits. */
2645 unsigned int bits;
2646 lostFraction fraction;
2647
2648 bits = valueBits - hexDigits * 4;
2649 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2650 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2651 }
2652 outputDigits = hexDigits;
2653 }
2654
2655 /* Write the digits consecutively, and start writing in the location
2656 of the hexadecimal point. We move the most significant digit
2657 left and add the hexadecimal point later. */
2658 p = ++dst;
2659
2660 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2661
2662 while (outputDigits && count) {
2663 integerPart part;
2664
2665 /* Put the most significant integerPartWidth bits in "part". */
2666 if (--count == partsCount)
2667 part = 0; /* An imaginary higher zero part. */
2668 else
2669 part = significand[count] << shift;
2670
2671 if (count && shift)
2672 part |= significand[count - 1] >> (integerPartWidth - shift);
2673
2674 /* Convert as much of "part" to hexdigits as we can. */
2675 unsigned int curDigits = integerPartWidth / 4;
2676
2677 if (curDigits > outputDigits)
2678 curDigits = outputDigits;
2679 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2680 outputDigits -= curDigits;
2681 }
2682
2683 if (roundUp) {
2684 char *q = dst;
2685
2686 /* Note that hexDigitChars has a trailing '0'. */
2687 do {
2688 q--;
2689 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002690 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002691 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002692 } else {
2693 /* Add trailing zeroes. */
2694 memset (dst, '0', outputDigits);
2695 dst += outputDigits;
2696 }
2697
2698 /* Move the most significant digit to before the point, and if there
2699 is something after the decimal point add it. This must come
2700 after rounding above. */
2701 p[-1] = p[0];
2702 if (dst -1 == p)
2703 dst--;
2704 else
2705 p[0] = '.';
2706
2707 /* Finally output the exponent. */
2708 *dst++ = upperCase ? 'P': 'p';
2709
Neil Booth32897f52007-10-06 07:29:25 +00002710 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002711}
2712
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002713hash_code llvm::hash_value(const APFloat &Arg) {
2714 if (Arg.category != APFloat::fcNormal)
2715 return hash_combine((uint8_t)Arg.category,
2716 // NaN has no sign, fix it at zero.
2717 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2718 Arg.semantics->precision);
2719
2720 // Normal floats need their exponent and significand hashed.
2721 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2722 Arg.semantics->precision, Arg.exponent,
2723 hash_combine_range(
2724 Arg.significandParts(),
2725 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002726}
2727
2728// Conversion from APFloat to/from host float/double. It may eventually be
2729// possible to eliminate these and have everybody deal with APFloats, but that
2730// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002731// Current implementation requires integerPartWidth==64, which is correct at
2732// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002733
Dale Johannesen728687c2007-09-05 20:39:49 +00002734// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002735// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002736
Dale Johannesen245dceb2007-09-11 18:32:33 +00002737APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002738APFloat::convertF80LongDoubleAPFloatToAPInt() const
2739{
Dan Gohmanb456a152008-01-29 12:08:20 +00002740 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002741 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002742
2743 uint64_t myexponent, mysignificand;
2744
2745 if (category==fcNormal) {
2746 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002747 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002748 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2749 myexponent = 0; // denormal
2750 } else if (category==fcZero) {
2751 myexponent = 0;
2752 mysignificand = 0;
2753 } else if (category==fcInfinity) {
2754 myexponent = 0x7fff;
2755 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002756 } else {
2757 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002758 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002759 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002760 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002761
2762 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002763 words[0] = mysignificand;
2764 words[1] = ((uint64_t)(sign & 1) << 15) |
2765 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002766 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002767}
2768
2769APInt
Dale Johannesen007aa372007-10-11 18:07:22 +00002770APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2771{
Dan Gohmanb456a152008-01-29 12:08:20 +00002772 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002773 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002774
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002775 uint64_t words[2];
2776 opStatus fs;
2777 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002778
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002779 // Convert number to double. To avoid spurious underflows, we re-
2780 // normalize against the "double" minExponent first, and only *then*
2781 // truncate the mantissa. The result of that second conversion
2782 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002783 // Declare fltSemantics before APFloat that uses it (and
2784 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002785 fltSemantics extendedSemantics = *semantics;
2786 extendedSemantics.minExponent = IEEEdouble.minExponent;
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002787 APFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002788 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2789 assert(fs == opOK && !losesInfo);
2790 (void)fs;
2791
2792 APFloat u(extended);
2793 fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2794 assert(fs == opOK || fs == opInexact);
2795 (void)fs;
2796 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2797
2798 // If conversion was exact or resulted in a special case, we're done;
2799 // just set the second double to zero. Otherwise, re-convert back to
2800 // the extended format and compute the difference. This now should
2801 // convert exactly to double.
2802 if (u.category == fcNormal && losesInfo) {
2803 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2804 assert(fs == opOK && !losesInfo);
2805 (void)fs;
2806
2807 APFloat v(extended);
2808 v.subtract(u, rmNearestTiesToEven);
2809 fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2810 assert(fs == opOK && !losesInfo);
2811 (void)fs;
2812 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002813 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002814 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002815 }
2816
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002817 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002818}
2819
2820APInt
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002821APFloat::convertQuadrupleAPFloatToAPInt() const
2822{
2823 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002824 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002825
2826 uint64_t myexponent, mysignificand, mysignificand2;
2827
2828 if (category==fcNormal) {
2829 myexponent = exponent+16383; //bias
2830 mysignificand = significandParts()[0];
2831 mysignificand2 = significandParts()[1];
2832 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2833 myexponent = 0; // denormal
2834 } else if (category==fcZero) {
2835 myexponent = 0;
2836 mysignificand = mysignificand2 = 0;
2837 } else if (category==fcInfinity) {
2838 myexponent = 0x7fff;
2839 mysignificand = mysignificand2 = 0;
2840 } else {
2841 assert(category == fcNaN && "Unknown category!");
2842 myexponent = 0x7fff;
2843 mysignificand = significandParts()[0];
2844 mysignificand2 = significandParts()[1];
2845 }
2846
2847 uint64_t words[2];
2848 words[0] = mysignificand;
2849 words[1] = ((uint64_t)(sign & 1) << 63) |
2850 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002851 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002852
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002853 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002854}
2855
2856APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002857APFloat::convertDoubleAPFloatToAPInt() const
2858{
Dan Gohman58c468f2007-09-14 20:08:19 +00002859 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002860 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002861
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002862 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002863
2864 if (category==fcNormal) {
Dale Johannesena719a602007-08-24 00:56:33 +00002865 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002866 mysignificand = *significandParts();
2867 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2868 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002869 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002870 myexponent = 0;
2871 mysignificand = 0;
2872 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002873 myexponent = 0x7ff;
2874 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002875 } else {
2876 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002877 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002878 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002879 }
Dale Johannesena719a602007-08-24 00:56:33 +00002880
Evan Cheng82b9e962008-05-02 21:15:08 +00002881 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002882 ((myexponent & 0x7ff) << 52) |
2883 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002884}
2885
Dale Johannesen245dceb2007-09-11 18:32:33 +00002886APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002887APFloat::convertFloatAPFloatToAPInt() const
2888{
Dan Gohman58c468f2007-09-14 20:08:19 +00002889 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002890 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002891
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002892 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002893
2894 if (category==fcNormal) {
Dale Johannesena719a602007-08-24 00:56:33 +00002895 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00002896 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00002897 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00002898 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002899 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002900 myexponent = 0;
2901 mysignificand = 0;
2902 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002903 myexponent = 0xff;
2904 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002905 } else {
2906 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00002907 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00002908 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002909 }
Dale Johannesena719a602007-08-24 00:56:33 +00002910
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002911 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2912 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00002913}
2914
Chris Lattner4794b2b2009-10-16 02:13:51 +00002915APInt
2916APFloat::convertHalfAPFloatToAPInt() const
2917{
2918 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00002919 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00002920
2921 uint32_t myexponent, mysignificand;
2922
2923 if (category==fcNormal) {
2924 myexponent = exponent+15; //bias
2925 mysignificand = (uint32_t)*significandParts();
2926 if (myexponent == 1 && !(mysignificand & 0x400))
2927 myexponent = 0; // denormal
2928 } else if (category==fcZero) {
2929 myexponent = 0;
2930 mysignificand = 0;
2931 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00002932 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002933 mysignificand = 0;
2934 } else {
2935 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00002936 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002937 mysignificand = (uint32_t)*significandParts();
2938 }
2939
2940 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2941 (mysignificand & 0x3ff)));
2942}
2943
Dale Johannesen007aa372007-10-11 18:07:22 +00002944// This function creates an APInt that is just a bit map of the floating
2945// point constant as it would appear in memory. It is not a conversion,
2946// and treating the result as a normal integer is unlikely to be useful.
2947
Dale Johannesen245dceb2007-09-11 18:32:33 +00002948APInt
Dale Johannesen54306fe2008-10-09 18:53:47 +00002949APFloat::bitcastToAPInt() const
Neil Booth9acbf5a2007-09-26 21:33:42 +00002950{
Chris Lattner4794b2b2009-10-16 02:13:51 +00002951 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2952 return convertHalfAPFloatToAPInt();
2953
Dan Gohmanb456a152008-01-29 12:08:20 +00002954 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00002955 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002956
Dan Gohmanb456a152008-01-29 12:08:20 +00002957 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00002958 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00002959
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002960 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2961 return convertQuadrupleAPFloatToAPInt();
2962
Dan Gohmanb456a152008-01-29 12:08:20 +00002963 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesen007aa372007-10-11 18:07:22 +00002964 return convertPPCDoubleDoubleAPFloatToAPInt();
2965
Dan Gohmanb456a152008-01-29 12:08:20 +00002966 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002967 "unknown format!");
2968 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002969}
2970
Neil Booth9acbf5a2007-09-26 21:33:42 +00002971float
2972APFloat::convertToFloat() const
2973{
Chris Lattner688f9912009-09-24 21:44:20 +00002974 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2975 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00002976 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002977 return api.bitsToFloat();
2978}
2979
Neil Booth9acbf5a2007-09-26 21:33:42 +00002980double
2981APFloat::convertToDouble() const
2982{
Chris Lattner688f9912009-09-24 21:44:20 +00002983 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2984 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00002985 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00002986 return api.bitsToDouble();
2987}
2988
Dale Johannesenfff29952008-10-06 18:22:29 +00002989/// Integer bit is explicit in this format. Intel hardware (387 and later)
2990/// does not support these bit patterns:
2991/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2992/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2993/// exponent = 0, integer bit 1 ("pseudodenormal")
2994/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2995/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen245dceb2007-09-11 18:32:33 +00002996void
Neil Booth9acbf5a2007-09-26 21:33:42 +00002997APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2998{
Dale Johannesen245dceb2007-09-11 18:32:33 +00002999 assert(api.getBitWidth()==80);
3000 uint64_t i1 = api.getRawData()[0];
3001 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003002 uint64_t myexponent = (i2 & 0x7fff);
3003 uint64_t mysignificand = i1;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003004
3005 initialize(&APFloat::x87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003006 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003007
Dale Johannesen93eefa02009-03-23 21:16:53 +00003008 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003009 if (myexponent==0 && mysignificand==0) {
3010 // exponent, significand meaningless
3011 category = fcZero;
3012 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3013 // exponent, significand meaningless
3014 category = fcInfinity;
3015 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3016 // exponent meaningless
3017 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003018 significandParts()[0] = mysignificand;
3019 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003020 } else {
3021 category = fcNormal;
3022 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003023 significandParts()[0] = mysignificand;
3024 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003025 if (myexponent==0) // denormal
3026 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003027 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003028}
3029
3030void
Dale Johannesen007aa372007-10-11 18:07:22 +00003031APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3032{
3033 assert(api.getBitWidth()==128);
3034 uint64_t i1 = api.getRawData()[0];
3035 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003036 opStatus fs;
3037 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003038
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003039 // Get the first double and convert to our format.
3040 initFromDoubleAPInt(APInt(64, i1));
3041 fs = convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3042 assert(fs == opOK && !losesInfo);
3043 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003044
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003045 // Unless we have a special case, add in second double.
3046 if (category == fcNormal) {
Tim Northover29178a32013-01-22 09:46:31 +00003047 APFloat v(IEEEdouble, APInt(64, i2));
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003048 fs = v.convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3049 assert(fs == opOK && !losesInfo);
3050 (void)fs;
3051
3052 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003053 }
3054}
3055
3056void
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003057APFloat::initFromQuadrupleAPInt(const APInt &api)
3058{
3059 assert(api.getBitWidth()==128);
3060 uint64_t i1 = api.getRawData()[0];
3061 uint64_t i2 = api.getRawData()[1];
3062 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3063 uint64_t mysignificand = i1;
3064 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3065
3066 initialize(&APFloat::IEEEquad);
3067 assert(partCount()==2);
3068
3069 sign = static_cast<unsigned int>(i2>>63);
3070 if (myexponent==0 &&
3071 (mysignificand==0 && mysignificand2==0)) {
3072 // exponent, significand meaningless
3073 category = fcZero;
3074 } else if (myexponent==0x7fff &&
3075 (mysignificand==0 && mysignificand2==0)) {
3076 // exponent, significand meaningless
3077 category = fcInfinity;
3078 } else if (myexponent==0x7fff &&
3079 (mysignificand!=0 || mysignificand2 !=0)) {
3080 // exponent meaningless
3081 category = fcNaN;
3082 significandParts()[0] = mysignificand;
3083 significandParts()[1] = mysignificand2;
3084 } else {
3085 category = fcNormal;
3086 exponent = myexponent - 16383;
3087 significandParts()[0] = mysignificand;
3088 significandParts()[1] = mysignificand2;
3089 if (myexponent==0) // denormal
3090 exponent = -16382;
3091 else
3092 significandParts()[1] |= 0x1000000000000LL; // integer bit
3093 }
3094}
3095
3096void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003097APFloat::initFromDoubleAPInt(const APInt &api)
3098{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003099 assert(api.getBitWidth()==64);
3100 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003101 uint64_t myexponent = (i >> 52) & 0x7ff;
3102 uint64_t mysignificand = i & 0xfffffffffffffLL;
3103
Dale Johannesena719a602007-08-24 00:56:33 +00003104 initialize(&APFloat::IEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003105 assert(partCount()==1);
3106
Evan Cheng82b9e962008-05-02 21:15:08 +00003107 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003108 if (myexponent==0 && mysignificand==0) {
3109 // exponent, significand meaningless
3110 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003111 } else if (myexponent==0x7ff && mysignificand==0) {
3112 // exponent, significand meaningless
3113 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003114 } else if (myexponent==0x7ff && mysignificand!=0) {
3115 // exponent meaningless
3116 category = fcNaN;
3117 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003118 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003119 category = fcNormal;
3120 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003121 *significandParts() = mysignificand;
3122 if (myexponent==0) // denormal
3123 exponent = -1022;
3124 else
3125 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003126 }
Dale Johannesena719a602007-08-24 00:56:33 +00003127}
3128
Dale Johannesen245dceb2007-09-11 18:32:33 +00003129void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003130APFloat::initFromFloatAPInt(const APInt & api)
3131{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003132 assert(api.getBitWidth()==32);
3133 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003134 uint32_t myexponent = (i >> 23) & 0xff;
3135 uint32_t mysignificand = i & 0x7fffff;
3136
Dale Johannesena719a602007-08-24 00:56:33 +00003137 initialize(&APFloat::IEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003138 assert(partCount()==1);
3139
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003140 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003141 if (myexponent==0 && mysignificand==0) {
3142 // exponent, significand meaningless
3143 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003144 } else if (myexponent==0xff && mysignificand==0) {
3145 // exponent, significand meaningless
3146 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003147 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003148 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003149 category = fcNaN;
3150 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003151 } else {
3152 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003153 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003154 *significandParts() = mysignificand;
3155 if (myexponent==0) // denormal
3156 exponent = -126;
3157 else
3158 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003159 }
3160}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003161
Chris Lattner4794b2b2009-10-16 02:13:51 +00003162void
3163APFloat::initFromHalfAPInt(const APInt & api)
3164{
3165 assert(api.getBitWidth()==16);
3166 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003167 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003168 uint32_t mysignificand = i & 0x3ff;
3169
3170 initialize(&APFloat::IEEEhalf);
3171 assert(partCount()==1);
3172
3173 sign = i >> 15;
3174 if (myexponent==0 && mysignificand==0) {
3175 // exponent, significand meaningless
3176 category = fcZero;
3177 } else if (myexponent==0x1f && mysignificand==0) {
3178 // exponent, significand meaningless
3179 category = fcInfinity;
3180 } else if (myexponent==0x1f && mysignificand!=0) {
3181 // sign, exponent, significand meaningless
3182 category = fcNaN;
3183 *significandParts() = mysignificand;
3184 } else {
3185 category = fcNormal;
3186 exponent = myexponent - 15; //bias
3187 *significandParts() = mysignificand;
3188 if (myexponent==0) // denormal
3189 exponent = -14;
3190 else
3191 *significandParts() |= 0x400; // integer bit
3192 }
3193}
3194
Dale Johannesen245dceb2007-09-11 18:32:33 +00003195/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003196/// we infer the floating point type from the size of the APInt. The
3197/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3198/// when the size is anything else).
Dale Johannesen245dceb2007-09-11 18:32:33 +00003199void
Tim Northover29178a32013-01-22 09:46:31 +00003200APFloat::initFromAPInt(const fltSemantics* Sem, const APInt& api)
Neil Booth9acbf5a2007-09-26 21:33:42 +00003201{
Tim Northover29178a32013-01-22 09:46:31 +00003202 if (Sem == &IEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003203 return initFromHalfAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003204 if (Sem == &IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003205 return initFromFloatAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003206 if (Sem == &IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003207 return initFromDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003208 if (Sem == &x87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003209 return initFromF80LongDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003210 if (Sem == &IEEEquad)
3211 return initFromQuadrupleAPInt(api);
3212 if (Sem == &PPCDoubleDouble)
3213 return initFromPPCDoubleDoubleAPInt(api);
3214
3215 llvm_unreachable(0);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003216}
3217
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003218APFloat
3219APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3220{
Tim Northover29178a32013-01-22 09:46:31 +00003221 switch (BitWidth) {
3222 case 16:
3223 return APFloat(IEEEhalf, APInt::getAllOnesValue(BitWidth));
3224 case 32:
3225 return APFloat(IEEEsingle, APInt::getAllOnesValue(BitWidth));
3226 case 64:
3227 return APFloat(IEEEdouble, APInt::getAllOnesValue(BitWidth));
3228 case 80:
3229 return APFloat(x87DoubleExtended, APInt::getAllOnesValue(BitWidth));
3230 case 128:
3231 if (isIEEE)
3232 return APFloat(IEEEquad, APInt::getAllOnesValue(BitWidth));
3233 return APFloat(PPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
3234 default:
3235 llvm_unreachable("Unknown floating bit width");
3236 }
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003237}
3238
John McCall29b5c282009-12-24 08:56:26 +00003239APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3240 APFloat Val(Sem, fcNormal, Negative);
3241
3242 // We want (in interchange format):
3243 // sign = {Negative}
3244 // exponent = 1..10
3245 // significand = 1..1
3246
3247 Val.exponent = Sem.maxExponent; // unbiased
3248
3249 // 1-initialize all bits....
3250 Val.zeroSignificand();
3251 integerPart *significand = Val.significandParts();
3252 unsigned N = partCountForBits(Sem.precision);
3253 for (unsigned i = 0; i != N; ++i)
3254 significand[i] = ~((integerPart) 0);
3255
3256 // ...and then clear the top bits for internal consistency.
Eli Friedmanc5322012011-10-12 21:51:36 +00003257 if (Sem.precision % integerPartWidth != 0)
3258 significand[N-1] &=
3259 (((integerPart) 1) << (Sem.precision % integerPartWidth)) - 1;
John McCall29b5c282009-12-24 08:56:26 +00003260
3261 return Val;
3262}
3263
3264APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3265 APFloat Val(Sem, fcNormal, Negative);
3266
3267 // We want (in interchange format):
3268 // sign = {Negative}
3269 // exponent = 0..0
3270 // significand = 0..01
3271
3272 Val.exponent = Sem.minExponent; // unbiased
3273 Val.zeroSignificand();
3274 Val.significandParts()[0] = 1;
3275 return Val;
3276}
3277
3278APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3279 APFloat Val(Sem, fcNormal, Negative);
3280
3281 // We want (in interchange format):
3282 // sign = {Negative}
3283 // exponent = 0..0
3284 // significand = 10..0
3285
3286 Val.exponent = Sem.minExponent;
3287 Val.zeroSignificand();
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003288 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
Eli Friedmand4330422011-10-12 21:56:19 +00003289 (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003290
3291 return Val;
3292}
3293
Tim Northover29178a32013-01-22 09:46:31 +00003294APFloat::APFloat(const fltSemantics &Sem, const APInt &API) {
3295 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003296}
3297
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003298APFloat::APFloat(float f) {
Tim Northover29178a32013-01-22 09:46:31 +00003299 initFromAPInt(&IEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003300}
3301
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003302APFloat::APFloat(double d) {
Tim Northover29178a32013-01-22 09:46:31 +00003303 initFromAPInt(&IEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003304}
John McCall29b5c282009-12-24 08:56:26 +00003305
3306namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003307 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3308 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003309 }
3310
John McCalle6212ace2009-12-24 12:16:56 +00003311 /// Removes data from the given significand until it is no more
3312 /// precise than is required for the desired precision.
3313 void AdjustToPrecision(APInt &significand,
3314 int &exp, unsigned FormatPrecision) {
3315 unsigned bits = significand.getActiveBits();
3316
3317 // 196/59 is a very slight overestimate of lg_2(10).
3318 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3319
3320 if (bits <= bitsRequired) return;
3321
3322 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3323 if (!tensRemovable) return;
3324
3325 exp += tensRemovable;
3326
3327 APInt divisor(significand.getBitWidth(), 1);
3328 APInt powten(significand.getBitWidth(), 10);
3329 while (true) {
3330 if (tensRemovable & 1)
3331 divisor *= powten;
3332 tensRemovable >>= 1;
3333 if (!tensRemovable) break;
3334 powten *= powten;
3335 }
3336
3337 significand = significand.udiv(divisor);
3338
Hao Liube99cc32013-03-20 01:46:36 +00003339 // Truncate the significand down to its active bit count.
3340 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003341 }
3342
3343
John McCall29b5c282009-12-24 08:56:26 +00003344 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3345 int &exp, unsigned FormatPrecision) {
3346 unsigned N = buffer.size();
3347 if (N <= FormatPrecision) return;
3348
3349 // The most significant figures are the last ones in the buffer.
3350 unsigned FirstSignificant = N - FormatPrecision;
3351
3352 // Round.
3353 // FIXME: this probably shouldn't use 'round half up'.
3354
3355 // Rounding down is just a truncation, except we also want to drop
3356 // trailing zeros from the new result.
3357 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003358 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003359 FirstSignificant++;
3360
3361 exp += FirstSignificant;
3362 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3363 return;
3364 }
3365
3366 // Rounding up requires a decimal add-with-carry. If we continue
3367 // the carry, the newly-introduced zeros will just be truncated.
3368 for (unsigned I = FirstSignificant; I != N; ++I) {
3369 if (buffer[I] == '9') {
3370 FirstSignificant++;
3371 } else {
3372 buffer[I]++;
3373 break;
3374 }
3375 }
3376
3377 // If we carried through, we have exactly one digit of precision.
3378 if (FirstSignificant == N) {
3379 exp += FirstSignificant;
3380 buffer.clear();
3381 buffer.push_back('1');
3382 return;
3383 }
3384
3385 exp += FirstSignificant;
3386 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3387 }
3388}
3389
3390void APFloat::toString(SmallVectorImpl<char> &Str,
3391 unsigned FormatPrecision,
Chris Lattner4c1e4db2010-03-06 19:20:13 +00003392 unsigned FormatMaxPadding) const {
John McCall29b5c282009-12-24 08:56:26 +00003393 switch (category) {
3394 case fcInfinity:
3395 if (isNegative())
3396 return append(Str, "-Inf");
3397 else
3398 return append(Str, "+Inf");
3399
3400 case fcNaN: return append(Str, "NaN");
3401
3402 case fcZero:
3403 if (isNegative())
3404 Str.push_back('-');
3405
3406 if (!FormatMaxPadding)
3407 append(Str, "0.0E+0");
3408 else
3409 Str.push_back('0');
3410 return;
3411
3412 case fcNormal:
3413 break;
3414 }
3415
3416 if (isNegative())
3417 Str.push_back('-');
3418
3419 // Decompose the number into an APInt and an exponent.
3420 int exp = exponent - ((int) semantics->precision - 1);
3421 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003422 makeArrayRef(significandParts(),
3423 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003424
John McCalldd5044a2009-12-24 23:18:09 +00003425 // Set FormatPrecision if zero. We want to do this before we
3426 // truncate trailing zeros, as those are part of the precision.
3427 if (!FormatPrecision) {
3428 // It's an interesting question whether to use the nominal
3429 // precision or the active precision here for denormals.
3430
3431 // FormatPrecision = ceil(significandBits / lg_2(10))
3432 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3433 }
3434
John McCall29b5c282009-12-24 08:56:26 +00003435 // Ignore trailing binary zeros.
3436 int trailingZeros = significand.countTrailingZeros();
3437 exp += trailingZeros;
3438 significand = significand.lshr(trailingZeros);
3439
3440 // Change the exponent from 2^e to 10^e.
3441 if (exp == 0) {
3442 // Nothing to do.
3443 } else if (exp > 0) {
3444 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003445 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003446 significand <<= exp;
3447 exp = 0;
3448 } else { /* exp < 0 */
3449 int texp = -exp;
3450
3451 // We transform this using the identity:
3452 // (N)(2^-e) == (N)(5^e)(10^-e)
3453 // This means we have to multiply N (the significand) by 5^e.
3454 // To avoid overflow, we have to operate on numbers large
3455 // enough to store N * 5^e:
3456 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003457 // <= semantics->precision + e * 137 / 59
3458 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003459
Eli Friedman19546412011-10-07 23:40:49 +00003460 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003461
3462 // Multiply significand by 5^e.
3463 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003464 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003465 APInt five_to_the_i(precision, 5);
3466 while (true) {
3467 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003468
John McCall29b5c282009-12-24 08:56:26 +00003469 texp >>= 1;
3470 if (!texp) break;
3471 five_to_the_i *= five_to_the_i;
3472 }
3473 }
3474
John McCalle6212ace2009-12-24 12:16:56 +00003475 AdjustToPrecision(significand, exp, FormatPrecision);
3476
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003477 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003478
3479 // Fill the buffer.
3480 unsigned precision = significand.getBitWidth();
3481 APInt ten(precision, 10);
3482 APInt digit(precision, 0);
3483
3484 bool inTrail = true;
3485 while (significand != 0) {
3486 // digit <- significand % 10
3487 // significand <- significand / 10
3488 APInt::udivrem(significand, ten, significand, digit);
3489
3490 unsigned d = digit.getZExtValue();
3491
3492 // Drop trailing zeros.
3493 if (inTrail && !d) exp++;
3494 else {
3495 buffer.push_back((char) ('0' + d));
3496 inTrail = false;
3497 }
3498 }
3499
3500 assert(!buffer.empty() && "no characters in buffer!");
3501
3502 // Drop down to FormatPrecision.
3503 // TODO: don't do more precise calculations above than are required.
3504 AdjustToPrecision(buffer, exp, FormatPrecision);
3505
3506 unsigned NDigits = buffer.size();
3507
John McCalldd5044a2009-12-24 23:18:09 +00003508 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003509 bool FormatScientific;
3510 if (!FormatMaxPadding)
3511 FormatScientific = true;
3512 else {
John McCall29b5c282009-12-24 08:56:26 +00003513 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003514 // 765e3 --> 765000
3515 // ^^^
3516 // But we shouldn't make the number look more precise than it is.
3517 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3518 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003519 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003520 // Power of the most significant digit.
3521 int MSD = exp + (int) (NDigits - 1);
3522 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003523 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003524 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003525 } else {
3526 // 765e-5 == 0.00765
3527 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003528 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003529 }
3530 }
John McCall29b5c282009-12-24 08:56:26 +00003531 }
3532
3533 // Scientific formatting is pretty straightforward.
3534 if (FormatScientific) {
3535 exp += (NDigits - 1);
3536
3537 Str.push_back(buffer[NDigits-1]);
3538 Str.push_back('.');
3539 if (NDigits == 1)
3540 Str.push_back('0');
3541 else
3542 for (unsigned I = 1; I != NDigits; ++I)
3543 Str.push_back(buffer[NDigits-1-I]);
3544 Str.push_back('E');
3545
3546 Str.push_back(exp >= 0 ? '+' : '-');
3547 if (exp < 0) exp = -exp;
3548 SmallVector<char, 6> expbuf;
3549 do {
3550 expbuf.push_back((char) ('0' + (exp % 10)));
3551 exp /= 10;
3552 } while (exp);
3553 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3554 Str.push_back(expbuf[E-1-I]);
3555 return;
3556 }
3557
3558 // Non-scientific, positive exponents.
3559 if (exp >= 0) {
3560 for (unsigned I = 0; I != NDigits; ++I)
3561 Str.push_back(buffer[NDigits-1-I]);
3562 for (unsigned I = 0; I != (unsigned) exp; ++I)
3563 Str.push_back('0');
3564 return;
3565 }
3566
3567 // Non-scientific, negative exponents.
3568
3569 // The number of digits to the left of the decimal point.
3570 int NWholeDigits = exp + (int) NDigits;
3571
3572 unsigned I = 0;
3573 if (NWholeDigits > 0) {
3574 for (; I != (unsigned) NWholeDigits; ++I)
3575 Str.push_back(buffer[NDigits-I-1]);
3576 Str.push_back('.');
3577 } else {
3578 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3579
3580 Str.push_back('0');
3581 Str.push_back('.');
3582 for (unsigned Z = 1; Z != NZeros; ++Z)
3583 Str.push_back('0');
3584 }
3585
3586 for (; I != NDigits; ++I)
3587 Str.push_back(buffer[NDigits-I-1]);
3588}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003589
3590bool APFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003591 // Special floats and denormals have no exact inverse.
3592 if (category != fcNormal)
3593 return false;
3594
3595 // Check that the number is a power of two by making sure that only the
3596 // integer bit is set in the significand.
3597 if (significandLSB() != semantics->precision - 1)
3598 return false;
3599
3600 // Get the inverse.
3601 APFloat reciprocal(*semantics, 1ULL);
3602 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3603 return false;
3604
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003605 // Avoid multiplication with a denormal, it is not safe on all platforms and
3606 // may be slower than a normal division.
3607 if (reciprocal.significandMSB() + 1 < reciprocal.semantics->precision)
3608 return false;
3609
3610 assert(reciprocal.category == fcNormal &&
3611 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3612
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003613 if (inv)
3614 *inv = reciprocal;
3615
3616 return true;
3617}