blob: 95df8617fb5c4ead5a87c1ad4c73df0c0427c343 [file] [log] [blame]
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision floating
11// point values and provide a variety of arithmetic operations on them.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner36d26c22007-12-08 19:00:03 +000015#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +000016#include "llvm/ADT/APSInt.h"
Erick Tryzelaara15d8902009-08-16 23:36:19 +000017#include "llvm/ADT/StringRef.h"
Ted Kremenek1f801fa2008-02-11 17:24:50 +000018#include "llvm/ADT/FoldingSet.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000019#include "llvm/Support/ErrorHandling.h"
Dale Johannesend3b51fd2007-08-24 05:08:11 +000020#include "llvm/Support/MathExtras.h"
John McCall8b3f3302010-02-26 22:20:41 +000021#include <limits.h>
Chris Lattnerfad86b02008-08-17 07:19:36 +000022#include <cstring>
Chris Lattnerb39cdde2007-08-20 22:49:32 +000023
24using namespace llvm;
25
26#define convolve(lhs, rhs) ((lhs) * 4 + (rhs))
27
Neil Bootha30b0ee2007-10-03 22:26:02 +000028/* Assumed in hexadecimal significand parsing, and conversion to
29 hexadecimal strings. */
Chris Lattner9f17eb02008-08-17 04:58:58 +000030#define COMPILE_TIME_ASSERT(cond) extern int CTAssert[(cond) ? 1 : -1]
Chris Lattnerb39cdde2007-08-20 22:49:32 +000031COMPILE_TIME_ASSERT(integerPartWidth % 4 == 0);
32
33namespace llvm {
34
35 /* Represents floating point arithmetic semantics. */
36 struct fltSemantics {
37 /* The largest E such that 2^E is representable; this matches the
38 definition of IEEE 754. */
39 exponent_t maxExponent;
40
41 /* The smallest E such that 2^E is a normalized number; this
42 matches the definition of IEEE 754. */
43 exponent_t minExponent;
44
45 /* Number of bits in the significand. This includes the integer
46 bit. */
Neil Booth7a951ca2007-10-12 15:33:27 +000047 unsigned int precision;
Neil Boothcaf19d72007-10-14 10:29:28 +000048
49 /* True if arithmetic is supported. */
50 unsigned int arithmeticOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +000051 };
52
Chris Lattnercc4287a2009-10-16 02:13:51 +000053 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11, true };
Neil Boothcaf19d72007-10-14 10:29:28 +000054 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, true };
55 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, true };
56 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, true };
57 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, true };
58 const fltSemantics APFloat::Bogus = { 0, 0, 0, true };
Dale Johannesena471c2e2007-10-11 18:07:22 +000059
60 // The PowerPC format consists of two doubles. It does not map cleanly
61 // onto the usual format above. For now only storage of constants of
62 // this type is supported, no arithmetic.
Neil Boothcaf19d72007-10-14 10:29:28 +000063 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022, 106, false };
Neil Booth96c74712007-10-12 16:02:31 +000064
65 /* A tight upper bound on number of parts required to hold the value
66 pow(5, power) is
67
Neil Booth686700e2007-10-15 15:00:55 +000068 power * 815 / (351 * integerPartWidth) + 1
Dan Gohman16e02092010-03-24 19:38:02 +000069
Neil Booth96c74712007-10-12 16:02:31 +000070 However, whilst the result may require only this many parts,
71 because we are multiplying two values to get it, the
72 multiplication may require an extra part with the excess part
73 being zero (consider the trivial case of 1 * 1, tcFullMultiply
74 requires two parts to hold the single-part result). So we add an
75 extra one to guarantee enough space whilst multiplying. */
76 const unsigned int maxExponent = 16383;
77 const unsigned int maxPrecision = 113;
78 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth686700e2007-10-15 15:00:55 +000079 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
80 / (351 * integerPartWidth));
Chris Lattnerb39cdde2007-08-20 22:49:32 +000081}
82
Chris Lattnere213f3f2009-03-12 23:59:55 +000083/* A bunch of private, handy routines. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +000084
Chris Lattnere213f3f2009-03-12 23:59:55 +000085static inline unsigned int
86partCountForBits(unsigned int bits)
87{
88 return ((bits) + integerPartWidth - 1) / integerPartWidth;
89}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000090
Chris Lattnere213f3f2009-03-12 23:59:55 +000091/* Returns 0U-9U. Return values >= 10U are not digits. */
92static inline unsigned int
93decDigitValue(unsigned int c)
94{
95 return c - '0';
96}
Chris Lattnerb39cdde2007-08-20 22:49:32 +000097
Chris Lattnere213f3f2009-03-12 23:59:55 +000098static unsigned int
99hexDigitValue(unsigned int c)
100{
101 unsigned int r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000102
Chris Lattnere213f3f2009-03-12 23:59:55 +0000103 r = c - '0';
Dan Gohman16e02092010-03-24 19:38:02 +0000104 if (r <= 9)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000105 return r;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000106
Chris Lattnere213f3f2009-03-12 23:59:55 +0000107 r = c - 'A';
Dan Gohman16e02092010-03-24 19:38:02 +0000108 if (r <= 5)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000109 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000110
Chris Lattnere213f3f2009-03-12 23:59:55 +0000111 r = c - 'a';
Dan Gohman16e02092010-03-24 19:38:02 +0000112 if (r <= 5)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000113 return r + 10;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000114
Chris Lattnere213f3f2009-03-12 23:59:55 +0000115 return -1U;
116}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000117
Chris Lattnere213f3f2009-03-12 23:59:55 +0000118static inline void
119assertArithmeticOK(const llvm::fltSemantics &semantics) {
Dan Gohman16e02092010-03-24 19:38:02 +0000120 assert(semantics.arithmeticOK &&
121 "Compile-time arithmetic does not support these semantics");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000122}
Neil Boothcaf19d72007-10-14 10:29:28 +0000123
Chris Lattnere213f3f2009-03-12 23:59:55 +0000124/* Return the value of a decimal exponent of the form
125 [+-]ddddddd.
Neil Booth1870f292007-10-14 10:16:12 +0000126
Chris Lattnere213f3f2009-03-12 23:59:55 +0000127 If the exponent overflows, returns a large exponent with the
128 appropriate sign. */
129static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000130readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000131{
132 bool isNegative;
133 unsigned int absExponent;
134 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000135 StringRef::iterator p = begin;
136
137 assert(p != end && "Exponent has no digits");
Neil Booth1870f292007-10-14 10:16:12 +0000138
Chris Lattnere213f3f2009-03-12 23:59:55 +0000139 isNegative = (*p == '-');
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000140 if (*p == '-' || *p == '+') {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000141 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000142 assert(p != end && "Exponent has no digits");
143 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000144
Chris Lattnere213f3f2009-03-12 23:59:55 +0000145 absExponent = decDigitValue(*p++);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000146 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000147
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000148 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000149 unsigned int value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000150
Chris Lattnere213f3f2009-03-12 23:59:55 +0000151 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000152 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000153
Chris Lattnere213f3f2009-03-12 23:59:55 +0000154 value += absExponent * 10;
155 if (absExponent >= overlargeExponent) {
156 absExponent = overlargeExponent;
Dale Johannesenb1508d12010-08-19 17:58:35 +0000157 p = end; /* outwit assert below */
Chris Lattnere213f3f2009-03-12 23:59:55 +0000158 break;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000159 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000160 absExponent = value;
161 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000162
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000163 assert(p == end && "Invalid exponent in exponent");
164
Chris Lattnere213f3f2009-03-12 23:59:55 +0000165 if (isNegative)
166 return -(int) absExponent;
167 else
168 return (int) absExponent;
169}
170
171/* This is ugly and needs cleaning up, but I don't immediately see
172 how whilst remaining safe. */
173static int
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000174totalExponent(StringRef::iterator p, StringRef::iterator end,
175 int exponentAdjustment)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000176{
177 int unsignedExponent;
178 bool negative, overflow;
Ted Kremenek584520e2011-01-23 17:05:06 +0000179 int exponent = 0;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000180
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000181 assert(p != end && "Exponent has no digits");
182
Chris Lattnere213f3f2009-03-12 23:59:55 +0000183 negative = *p == '-';
Dan Gohman16e02092010-03-24 19:38:02 +0000184 if (*p == '-' || *p == '+') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000185 p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000186 assert(p != end && "Exponent has no digits");
187 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000188
189 unsignedExponent = 0;
190 overflow = false;
Dan Gohman16e02092010-03-24 19:38:02 +0000191 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000192 unsigned int value;
193
194 value = decDigitValue(*p);
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000195 assert(value < 10U && "Invalid character in exponent");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000196
Chris Lattnere213f3f2009-03-12 23:59:55 +0000197 unsignedExponent = unsignedExponent * 10 + value;
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000198 if (unsignedExponent > 32767)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000199 overflow = true;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000200 }
201
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000202 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000203 overflow = true;
204
Dan Gohman16e02092010-03-24 19:38:02 +0000205 if (!overflow) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000206 exponent = unsignedExponent;
Dan Gohman16e02092010-03-24 19:38:02 +0000207 if (negative)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000208 exponent = -exponent;
209 exponent += exponentAdjustment;
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000210 if (exponent > 32767 || exponent < -32768)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000211 overflow = true;
212 }
213
Dan Gohman16e02092010-03-24 19:38:02 +0000214 if (overflow)
Abramo Bagnara4bb46f42011-01-06 16:55:14 +0000215 exponent = negative ? -32768: 32767;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000216
217 return exponent;
218}
219
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000220static StringRef::iterator
221skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
222 StringRef::iterator *dot)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000223{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000224 StringRef::iterator p = begin;
225 *dot = end;
Dan Gohman16e02092010-03-24 19:38:02 +0000226 while (*p == '0' && p != end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000227 p++;
228
Dan Gohman16e02092010-03-24 19:38:02 +0000229 if (*p == '.') {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000230 *dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000231
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000232 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000233
Dan Gohman16e02092010-03-24 19:38:02 +0000234 while (*p == '0' && p != end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000235 p++;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000236 }
237
Chris Lattnere213f3f2009-03-12 23:59:55 +0000238 return p;
239}
Neil Booth1870f292007-10-14 10:16:12 +0000240
Chris Lattnere213f3f2009-03-12 23:59:55 +0000241/* Given a normal decimal floating point number of the form
Neil Booth1870f292007-10-14 10:16:12 +0000242
Chris Lattnere213f3f2009-03-12 23:59:55 +0000243 dddd.dddd[eE][+-]ddd
Neil Booth686700e2007-10-15 15:00:55 +0000244
Chris Lattnere213f3f2009-03-12 23:59:55 +0000245 where the decimal point and exponent are optional, fill out the
246 structure D. Exponent is appropriate if the significand is
247 treated as an integer, and normalizedExponent if the significand
248 is taken to have the decimal point after a single leading
249 non-zero digit.
Neil Booth1870f292007-10-14 10:16:12 +0000250
Chris Lattnere213f3f2009-03-12 23:59:55 +0000251 If the value is zero, V->firstSigDigit points to a non-digit, and
252 the return exponent is zero.
253*/
254struct decimalInfo {
255 const char *firstSigDigit;
256 const char *lastSigDigit;
257 int exponent;
258 int normalizedExponent;
259};
Neil Booth1870f292007-10-14 10:16:12 +0000260
Chris Lattnere213f3f2009-03-12 23:59:55 +0000261static void
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000262interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
263 decimalInfo *D)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000264{
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000265 StringRef::iterator dot = end;
266 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth1870f292007-10-14 10:16:12 +0000267
Chris Lattnere213f3f2009-03-12 23:59:55 +0000268 D->firstSigDigit = p;
269 D->exponent = 0;
270 D->normalizedExponent = 0;
271
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000272 for (; p != end; ++p) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000273 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000274 assert(dot == end && "String contains multiple dots");
Chris Lattnere213f3f2009-03-12 23:59:55 +0000275 dot = p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000276 if (p == end)
277 break;
Neil Booth1870f292007-10-14 10:16:12 +0000278 }
Chris Lattnere213f3f2009-03-12 23:59:55 +0000279 if (decDigitValue(*p) >= 10U)
280 break;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000281 }
Neil Booth1870f292007-10-14 10:16:12 +0000282
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000283 if (p != end) {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000284 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
285 assert(p != begin && "Significand has no digits");
286 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000287
288 /* p points to the first non-digit in the string */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +0000289 D->exponent = readExponent(p + 1, end);
Neil Booth1870f292007-10-14 10:16:12 +0000290
Chris Lattnere213f3f2009-03-12 23:59:55 +0000291 /* Implied decimal point? */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000292 if (dot == end)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000293 dot = p;
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000294 }
Neil Booth1870f292007-10-14 10:16:12 +0000295
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000296 /* If number is all zeroes accept any exponent. */
297 if (p != D->firstSigDigit) {
Chris Lattnere213f3f2009-03-12 23:59:55 +0000298 /* Drop insignificant trailing zeroes. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000299 if (p != begin) {
Neil Booth1870f292007-10-14 10:16:12 +0000300 do
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000301 do
302 p--;
303 while (p != begin && *p == '0');
304 while (p != begin && *p == '.');
305 }
Neil Booth1870f292007-10-14 10:16:12 +0000306
Chris Lattnere213f3f2009-03-12 23:59:55 +0000307 /* Adjust the exponents for any decimal point. */
308 D->exponent += static_cast<exponent_t>((dot - p) - (dot > p));
309 D->normalizedExponent = (D->exponent +
310 static_cast<exponent_t>((p - D->firstSigDigit)
311 - (dot > D->firstSigDigit && dot < p)));
Neil Booth1870f292007-10-14 10:16:12 +0000312 }
313
Chris Lattnere213f3f2009-03-12 23:59:55 +0000314 D->lastSigDigit = p;
315}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000316
Chris Lattnere213f3f2009-03-12 23:59:55 +0000317/* Return the trailing fraction of a hexadecimal number.
318 DIGITVALUE is the first hex digit of the fraction, P points to
319 the next digit. */
320static lostFraction
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000321trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
322 unsigned int digitValue)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000323{
324 unsigned int hexDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000325
Chris Lattnere213f3f2009-03-12 23:59:55 +0000326 /* If the first trailing digit isn't 0 or 8 we can work out the
327 fraction immediately. */
Dan Gohman16e02092010-03-24 19:38:02 +0000328 if (digitValue > 8)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000329 return lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000330 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000331 return lfLessThanHalf;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000332
333 /* Otherwise we need to find the first non-zero digit. */
Dan Gohman16e02092010-03-24 19:38:02 +0000334 while (*p == '0')
Chris Lattnere213f3f2009-03-12 23:59:55 +0000335 p++;
336
Erick Tryzelaara15d8902009-08-16 23:36:19 +0000337 assert(p != end && "Invalid trailing hexadecimal fraction!");
338
Chris Lattnere213f3f2009-03-12 23:59:55 +0000339 hexDigit = hexDigitValue(*p);
340
341 /* If we ran off the end it is exactly zero or one-half, otherwise
342 a little more. */
Dan Gohman16e02092010-03-24 19:38:02 +0000343 if (hexDigit == -1U)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000344 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
345 else
346 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
347}
348
349/* Return the fraction lost were a bignum truncated losing the least
350 significant BITS bits. */
351static lostFraction
352lostFractionThroughTruncation(const integerPart *parts,
353 unsigned int partCount,
354 unsigned int bits)
355{
356 unsigned int lsb;
357
358 lsb = APInt::tcLSB(parts, partCount);
359
360 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohman16e02092010-03-24 19:38:02 +0000361 if (bits <= lsb)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000362 return lfExactlyZero;
Dan Gohman16e02092010-03-24 19:38:02 +0000363 if (bits == lsb + 1)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000364 return lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000365 if (bits <= partCount * integerPartWidth &&
366 APInt::tcExtractBit(parts, bits - 1))
Chris Lattnere213f3f2009-03-12 23:59:55 +0000367 return lfMoreThanHalf;
368
369 return lfLessThanHalf;
370}
371
372/* Shift DST right BITS bits noting lost fraction. */
373static lostFraction
374shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
375{
376 lostFraction lost_fraction;
377
378 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
379
380 APInt::tcShiftRight(dst, parts, bits);
381
382 return lost_fraction;
383}
384
385/* Combine the effect of two lost fractions. */
386static lostFraction
387combineLostFractions(lostFraction moreSignificant,
388 lostFraction lessSignificant)
389{
Dan Gohman16e02092010-03-24 19:38:02 +0000390 if (lessSignificant != lfExactlyZero) {
391 if (moreSignificant == lfExactlyZero)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000392 moreSignificant = lfLessThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +0000393 else if (moreSignificant == lfExactlyHalf)
Chris Lattnere213f3f2009-03-12 23:59:55 +0000394 moreSignificant = lfMoreThanHalf;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000395 }
396
Chris Lattnere213f3f2009-03-12 23:59:55 +0000397 return moreSignificant;
398}
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000399
Chris Lattnere213f3f2009-03-12 23:59:55 +0000400/* The error from the true value, in half-ulps, on multiplying two
401 floating point numbers, which differ from the value they
402 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
403 than the returned value.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000404
Chris Lattnere213f3f2009-03-12 23:59:55 +0000405 See "How to Read Floating Point Numbers Accurately" by William D
406 Clinger. */
407static unsigned int
408HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
409{
410 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000411
Chris Lattnere213f3f2009-03-12 23:59:55 +0000412 if (HUerr1 + HUerr2 == 0)
413 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
414 else
415 return inexactMultiply + 2 * (HUerr1 + HUerr2);
416}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000417
Chris Lattnere213f3f2009-03-12 23:59:55 +0000418/* The number of ulps from the boundary (zero, or half if ISNEAREST)
419 when the least significant BITS are truncated. BITS cannot be
420 zero. */
421static integerPart
422ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
423{
424 unsigned int count, partBits;
425 integerPart part, boundary;
Neil Booth33d4c922007-10-07 08:51:21 +0000426
Evan Cheng99ebfa52009-10-27 21:35:42 +0000427 assert(bits != 0);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000428
Chris Lattnere213f3f2009-03-12 23:59:55 +0000429 bits--;
430 count = bits / integerPartWidth;
431 partBits = bits % integerPartWidth + 1;
Neil Booth96c74712007-10-12 16:02:31 +0000432
Chris Lattnere213f3f2009-03-12 23:59:55 +0000433 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Booth96c74712007-10-12 16:02:31 +0000434
Chris Lattnere213f3f2009-03-12 23:59:55 +0000435 if (isNearest)
436 boundary = (integerPart) 1 << (partBits - 1);
437 else
438 boundary = 0;
439
440 if (count == 0) {
441 if (part - boundary <= boundary - part)
442 return part - boundary;
Neil Booth96c74712007-10-12 16:02:31 +0000443 else
Chris Lattnere213f3f2009-03-12 23:59:55 +0000444 return boundary - part;
Neil Booth96c74712007-10-12 16:02:31 +0000445 }
446
Chris Lattnere213f3f2009-03-12 23:59:55 +0000447 if (part == boundary) {
448 while (--count)
449 if (parts[count])
450 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000451
Chris Lattnere213f3f2009-03-12 23:59:55 +0000452 return parts[0];
453 } else if (part == boundary - 1) {
454 while (--count)
455 if (~parts[count])
456 return ~(integerPart) 0; /* A lot. */
Neil Booth96c74712007-10-12 16:02:31 +0000457
Chris Lattnere213f3f2009-03-12 23:59:55 +0000458 return -parts[0];
459 }
Neil Booth96c74712007-10-12 16:02:31 +0000460
Chris Lattnere213f3f2009-03-12 23:59:55 +0000461 return ~(integerPart) 0; /* A lot. */
462}
Neil Booth96c74712007-10-12 16:02:31 +0000463
Chris Lattnere213f3f2009-03-12 23:59:55 +0000464/* Place pow(5, power) in DST, and return the number of parts used.
465 DST must be at least one part larger than size of the answer. */
466static unsigned int
467powerOf5(integerPart *dst, unsigned int power)
468{
469 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
470 15625, 78125 };
Chris Lattneree167a72009-03-13 00:24:01 +0000471 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
472 pow5s[0] = 78125 * 5;
Dan Gohman16e02092010-03-24 19:38:02 +0000473
Chris Lattner807926a2009-03-13 00:03:51 +0000474 unsigned int partsCount[16] = { 1 };
Chris Lattnere213f3f2009-03-12 23:59:55 +0000475 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
476 unsigned int result;
Chris Lattnere213f3f2009-03-12 23:59:55 +0000477 assert(power <= maxExponent);
478
479 p1 = dst;
480 p2 = scratch;
481
482 *p1 = firstEightPowers[power & 7];
483 power >>= 3;
484
485 result = 1;
486 pow5 = pow5s;
487
488 for (unsigned int n = 0; power; power >>= 1, n++) {
489 unsigned int pc;
490
491 pc = partsCount[n];
492
493 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
494 if (pc == 0) {
495 pc = partsCount[n - 1];
496 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
497 pc *= 2;
498 if (pow5[pc - 1] == 0)
499 pc--;
500 partsCount[n] = pc;
Neil Booth96c74712007-10-12 16:02:31 +0000501 }
502
Chris Lattnere213f3f2009-03-12 23:59:55 +0000503 if (power & 1) {
504 integerPart *tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000505
Chris Lattnere213f3f2009-03-12 23:59:55 +0000506 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
507 result += pc;
508 if (p2[result - 1] == 0)
509 result--;
Neil Booth96c74712007-10-12 16:02:31 +0000510
Chris Lattnere213f3f2009-03-12 23:59:55 +0000511 /* Now result is in p1 with partsCount parts and p2 is scratch
512 space. */
513 tmp = p1, p1 = p2, p2 = tmp;
Neil Booth96c74712007-10-12 16:02:31 +0000514 }
515
Chris Lattnere213f3f2009-03-12 23:59:55 +0000516 pow5 += pc;
Neil Booth96c74712007-10-12 16:02:31 +0000517 }
518
Chris Lattnere213f3f2009-03-12 23:59:55 +0000519 if (p1 != dst)
520 APInt::tcAssign(dst, p1, result);
Neil Booth96c74712007-10-12 16:02:31 +0000521
Chris Lattnere213f3f2009-03-12 23:59:55 +0000522 return result;
523}
Neil Booth96c74712007-10-12 16:02:31 +0000524
Chris Lattnere213f3f2009-03-12 23:59:55 +0000525/* Zero at the end to avoid modular arithmetic when adding one; used
526 when rounding up during hexadecimal output. */
527static const char hexDigitsLower[] = "0123456789abcdef0";
528static const char hexDigitsUpper[] = "0123456789ABCDEF0";
529static const char infinityL[] = "infinity";
530static const char infinityU[] = "INFINITY";
531static const char NaNL[] = "nan";
532static const char NaNU[] = "NAN";
Neil Booth96c74712007-10-12 16:02:31 +0000533
Chris Lattnere213f3f2009-03-12 23:59:55 +0000534/* Write out an integerPart in hexadecimal, starting with the most
535 significant nibble. Write out exactly COUNT hexdigits, return
536 COUNT. */
537static unsigned int
538partAsHex (char *dst, integerPart part, unsigned int count,
539 const char *hexDigitChars)
540{
541 unsigned int result = count;
Neil Booth96c74712007-10-12 16:02:31 +0000542
Evan Cheng99ebfa52009-10-27 21:35:42 +0000543 assert(count != 0 && count <= integerPartWidth / 4);
Neil Booth96c74712007-10-12 16:02:31 +0000544
Chris Lattnere213f3f2009-03-12 23:59:55 +0000545 part >>= (integerPartWidth - 4 * count);
546 while (count--) {
547 dst[count] = hexDigitChars[part & 0xf];
548 part >>= 4;
Neil Booth96c74712007-10-12 16:02:31 +0000549 }
550
Chris Lattnere213f3f2009-03-12 23:59:55 +0000551 return result;
552}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000553
Chris Lattnere213f3f2009-03-12 23:59:55 +0000554/* Write out an unsigned decimal integer. */
555static char *
556writeUnsignedDecimal (char *dst, unsigned int n)
557{
558 char buff[40], *p;
Neil Bootha30b0ee2007-10-03 22:26:02 +0000559
Chris Lattnere213f3f2009-03-12 23:59:55 +0000560 p = buff;
561 do
562 *p++ = '0' + n % 10;
563 while (n /= 10);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000564
Chris Lattnere213f3f2009-03-12 23:59:55 +0000565 do
566 *dst++ = *--p;
567 while (p != buff);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000568
Chris Lattnere213f3f2009-03-12 23:59:55 +0000569 return dst;
570}
Neil Bootha30b0ee2007-10-03 22:26:02 +0000571
Chris Lattnere213f3f2009-03-12 23:59:55 +0000572/* Write out a signed decimal integer. */
573static char *
574writeSignedDecimal (char *dst, int value)
575{
576 if (value < 0) {
577 *dst++ = '-';
578 dst = writeUnsignedDecimal(dst, -(unsigned) value);
579 } else
580 dst = writeUnsignedDecimal(dst, value);
Neil Bootha30b0ee2007-10-03 22:26:02 +0000581
Chris Lattnere213f3f2009-03-12 23:59:55 +0000582 return dst;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000583}
584
585/* Constructors. */
586void
587APFloat::initialize(const fltSemantics *ourSemantics)
588{
589 unsigned int count;
590
591 semantics = ourSemantics;
592 count = partCount();
Dan Gohman16e02092010-03-24 19:38:02 +0000593 if (count > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000594 significand.parts = new integerPart[count];
595}
596
597void
598APFloat::freeSignificand()
599{
Dan Gohman16e02092010-03-24 19:38:02 +0000600 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000601 delete [] significand.parts;
602}
603
604void
605APFloat::assign(const APFloat &rhs)
606{
607 assert(semantics == rhs.semantics);
608
609 sign = rhs.sign;
610 category = rhs.category;
611 exponent = rhs.exponent;
Dale Johannesena471c2e2007-10-11 18:07:22 +0000612 sign2 = rhs.sign2;
613 exponent2 = rhs.exponent2;
Dan Gohman16e02092010-03-24 19:38:02 +0000614 if (category == fcNormal || category == fcNaN)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000615 copySignificand(rhs);
616}
617
618void
619APFloat::copySignificand(const APFloat &rhs)
620{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000621 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000622 assert(rhs.partCount() >= partCount());
623
624 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +0000625 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000626}
627
Neil Boothe5e01942007-10-14 10:39:51 +0000628/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen541ed9f2009-01-21 20:32:55 +0000629 for the significand. If double or longer, this is a signalling NaN,
Mike Stumpc5ca7132009-05-30 03:49:43 +0000630 which may not be ideal. If float, this is QNaN(0). */
John McCalle12b7382010-02-28 02:51:25 +0000631void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Boothe5e01942007-10-14 10:39:51 +0000632{
633 category = fcNaN;
John McCalle12b7382010-02-28 02:51:25 +0000634 sign = Negative;
635
John McCall165e96b2010-02-28 12:49:50 +0000636 integerPart *significand = significandParts();
637 unsigned numParts = partCount();
638
John McCalle12b7382010-02-28 02:51:25 +0000639 // Set the significand bits to the fill.
John McCall165e96b2010-02-28 12:49:50 +0000640 if (!fill || fill->getNumWords() < numParts)
641 APInt::tcSet(significand, 0, numParts);
642 if (fill) {
John McCalld44c6cc2010-03-01 18:38:45 +0000643 APInt::tcAssign(significand, fill->getRawData(),
644 std::min(fill->getNumWords(), numParts));
John McCall165e96b2010-02-28 12:49:50 +0000645
646 // Zero out the excess bits of the significand.
647 unsigned bitsToPreserve = semantics->precision - 1;
648 unsigned part = bitsToPreserve / 64;
649 bitsToPreserve %= 64;
650 significand[part] &= ((1ULL << bitsToPreserve) - 1);
651 for (part++; part != numParts; ++part)
652 significand[part] = 0;
653 }
654
655 unsigned QNaNBit = semantics->precision - 2;
John McCalle12b7382010-02-28 02:51:25 +0000656
657 if (SNaN) {
658 // We always have to clear the QNaN bit to make it an SNaN.
John McCall165e96b2010-02-28 12:49:50 +0000659 APInt::tcClearBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000660
661 // If there are no bits set in the payload, we have to set
662 // *something* to make it a NaN instead of an infinity;
663 // conventionally, this is the next bit down from the QNaN bit.
John McCall165e96b2010-02-28 12:49:50 +0000664 if (APInt::tcIsZero(significand, numParts))
665 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalle12b7382010-02-28 02:51:25 +0000666 } else {
667 // We always have to set the QNaN bit to make it a QNaN.
John McCall165e96b2010-02-28 12:49:50 +0000668 APInt::tcSetBit(significand, QNaNBit);
John McCalle12b7382010-02-28 02:51:25 +0000669 }
John McCall165e96b2010-02-28 12:49:50 +0000670
671 // For x87 extended precision, we want to make a NaN, not a
672 // pseudo-NaN. Maybe we should expose the ability to make
673 // pseudo-NaNs?
674 if (semantics == &APFloat::x87DoubleExtended)
675 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalle12b7382010-02-28 02:51:25 +0000676}
677
678APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
679 const APInt *fill) {
680 APFloat value(Sem, uninitialized);
681 value.makeNaN(SNaN, Negative, fill);
682 return value;
Neil Boothe5e01942007-10-14 10:39:51 +0000683}
684
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000685APFloat &
686APFloat::operator=(const APFloat &rhs)
687{
Dan Gohman16e02092010-03-24 19:38:02 +0000688 if (this != &rhs) {
689 if (semantics != rhs.semantics) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000690 freeSignificand();
691 initialize(rhs.semantics);
692 }
693 assign(rhs);
694 }
695
696 return *this;
697}
698
Dale Johannesen343e7702007-08-24 00:56:33 +0000699bool
Dale Johannesen12595d72007-08-24 22:09:56 +0000700APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesen343e7702007-08-24 00:56:33 +0000701 if (this == &rhs)
702 return true;
703 if (semantics != rhs.semantics ||
Dale Johanneseneaf08942007-08-31 04:03:46 +0000704 category != rhs.category ||
705 sign != rhs.sign)
Dale Johannesen343e7702007-08-24 00:56:33 +0000706 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000707 if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000708 sign2 != rhs.sign2)
709 return false;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000710 if (category==fcZero || category==fcInfinity)
Dale Johannesen343e7702007-08-24 00:56:33 +0000711 return true;
Dale Johanneseneaf08942007-08-31 04:03:46 +0000712 else if (category==fcNormal && exponent!=rhs.exponent)
713 return false;
Dan Gohmanb10abe12008-01-29 12:08:20 +0000714 else if (semantics==(const llvm::fltSemantics*)&PPCDoubleDouble &&
Dale Johannesena471c2e2007-10-11 18:07:22 +0000715 exponent2!=rhs.exponent2)
716 return false;
Dale Johannesen343e7702007-08-24 00:56:33 +0000717 else {
Dale Johannesen343e7702007-08-24 00:56:33 +0000718 int i= partCount();
719 const integerPart* p=significandParts();
720 const integerPart* q=rhs.significandParts();
721 for (; i>0; i--, p++, q++) {
722 if (*p != *q)
723 return false;
724 }
725 return true;
726 }
727}
728
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000729APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value)
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000730 : exponent2(0), sign2(0) {
Neil Boothcaf19d72007-10-14 10:29:28 +0000731 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000732 initialize(&ourSemantics);
733 sign = 0;
734 zeroSignificand();
735 exponent = ourSemantics.precision - 1;
736 significandParts()[0] = value;
737 normalize(rmNearestTiesToEven, lfExactlyZero);
738}
739
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000740APFloat::APFloat(const fltSemantics &ourSemantics) : exponent2(0), sign2(0) {
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000741 assertArithmeticOK(ourSemantics);
742 initialize(&ourSemantics);
743 category = fcZero;
744 sign = false;
745}
746
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000747APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
748 : exponent2(0), sign2(0) {
John McCalle12b7382010-02-28 02:51:25 +0000749 assertArithmeticOK(ourSemantics);
750 // Allocates storage if necessary but does not initialize it.
751 initialize(&ourSemantics);
752}
Chris Lattnerd7bd78e2009-09-17 01:08:43 +0000753
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000754APFloat::APFloat(const fltSemantics &ourSemantics,
John McCalle12b7382010-02-28 02:51:25 +0000755 fltCategory ourCategory, bool negative)
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000756 : exponent2(0), sign2(0) {
Neil Boothcaf19d72007-10-14 10:29:28 +0000757 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000758 initialize(&ourSemantics);
759 category = ourCategory;
760 sign = negative;
Mike Stumpc5ca7132009-05-30 03:49:43 +0000761 if (category == fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000762 category = fcZero;
Neil Boothe5e01942007-10-14 10:39:51 +0000763 else if (ourCategory == fcNaN)
John McCalle12b7382010-02-28 02:51:25 +0000764 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000765}
766
Benjamin Kramer38e59892010-07-14 22:38:02 +0000767APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text)
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000768 : exponent2(0), sign2(0) {
Neil Boothcaf19d72007-10-14 10:29:28 +0000769 assertArithmeticOK(ourSemantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000770 initialize(&ourSemantics);
771 convertFromString(text, rmNearestTiesToEven);
772}
773
Bill Wendlingf09a8b52011-03-18 09:09:44 +0000774APFloat::APFloat(const APFloat &rhs) : exponent2(0), sign2(0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000775 initialize(rhs.semantics);
776 assign(rhs);
777}
778
779APFloat::~APFloat()
780{
781 freeSignificand();
782}
783
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000784// Profile - This method 'profiles' an APFloat for use with FoldingSet.
785void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen7111b022008-10-09 18:53:47 +0000786 ID.Add(bitcastToAPInt());
Ted Kremenek1f801fa2008-02-11 17:24:50 +0000787}
788
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000789unsigned int
790APFloat::partCount() const
791{
Dale Johannesena72a5a02007-09-20 23:47:58 +0000792 return partCountForBits(semantics->precision + 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000793}
794
795unsigned int
796APFloat::semanticsPrecision(const fltSemantics &semantics)
797{
798 return semantics.precision;
799}
800
801const integerPart *
802APFloat::significandParts() const
803{
804 return const_cast<APFloat *>(this)->significandParts();
805}
806
807integerPart *
808APFloat::significandParts()
809{
Dale Johanneseneaf08942007-08-31 04:03:46 +0000810 assert(category == fcNormal || category == fcNaN);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000811
Evan Cheng99ebfa52009-10-27 21:35:42 +0000812 if (partCount() > 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000813 return significand.parts;
814 else
815 return &significand.part;
816}
817
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000818void
819APFloat::zeroSignificand()
820{
821 category = fcNormal;
822 APInt::tcSet(significandParts(), 0, partCount());
823}
824
825/* Increment an fcNormal floating point number's significand. */
826void
827APFloat::incrementSignificand()
828{
829 integerPart carry;
830
831 carry = APInt::tcIncrement(significandParts(), partCount());
832
833 /* Our callers should never cause us to overflow. */
834 assert(carry == 0);
Duncan Sands1f6a3292011-08-12 14:54:45 +0000835 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000836}
837
838/* Add the significand of the RHS. Returns the carry flag. */
839integerPart
840APFloat::addSignificand(const APFloat &rhs)
841{
842 integerPart *parts;
843
844 parts = significandParts();
845
846 assert(semantics == rhs.semantics);
847 assert(exponent == rhs.exponent);
848
849 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
850}
851
852/* Subtract the significand of the RHS with a borrow flag. Returns
853 the borrow flag. */
854integerPart
855APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
856{
857 integerPart *parts;
858
859 parts = significandParts();
860
861 assert(semantics == rhs.semantics);
862 assert(exponent == rhs.exponent);
863
864 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth4f881702007-09-26 21:33:42 +0000865 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000866}
867
868/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
869 on to the full-precision result of the multiplication. Returns the
870 lost fraction. */
871lostFraction
872APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
873{
Neil Booth4f881702007-09-26 21:33:42 +0000874 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000875 unsigned int partsCount, newPartsCount, precision;
876 integerPart *lhsSignificand;
877 integerPart scratch[4];
878 integerPart *fullSignificand;
879 lostFraction lost_fraction;
Dale Johannesen23a98552008-10-09 23:00:39 +0000880 bool ignored;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000881
882 assert(semantics == rhs.semantics);
883
884 precision = semantics->precision;
885 newPartsCount = partCountForBits(precision * 2);
886
Dan Gohman16e02092010-03-24 19:38:02 +0000887 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000888 fullSignificand = new integerPart[newPartsCount];
889 else
890 fullSignificand = scratch;
891
892 lhsSignificand = significandParts();
893 partsCount = partCount();
894
895 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth978661d2007-10-06 00:24:48 +0000896 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000897
898 lost_fraction = lfExactlyZero;
899 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
900 exponent += rhs.exponent;
901
Dan Gohman16e02092010-03-24 19:38:02 +0000902 if (addend) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000903 Significand savedSignificand = significand;
904 const fltSemantics *savedSemantics = semantics;
905 fltSemantics extendedSemantics;
906 opStatus status;
907 unsigned int extendedPrecision;
908
909 /* Normalize our MSB. */
910 extendedPrecision = precision + precision - 1;
Dan Gohman16e02092010-03-24 19:38:02 +0000911 if (omsb != extendedPrecision) {
912 APInt::tcShiftLeft(fullSignificand, newPartsCount,
913 extendedPrecision - omsb);
914 exponent -= extendedPrecision - omsb;
915 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000916
917 /* Create new semantics. */
918 extendedSemantics = *semantics;
919 extendedSemantics.precision = extendedPrecision;
920
Dan Gohman16e02092010-03-24 19:38:02 +0000921 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000922 significand.part = fullSignificand[0];
923 else
924 significand.parts = fullSignificand;
925 semantics = &extendedSemantics;
926
927 APFloat extendedAddend(*addend);
Dale Johannesen23a98552008-10-09 23:00:39 +0000928 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000929 assert(status == opOK);
Duncan Sands1f6a3292011-08-12 14:54:45 +0000930 (void)status;
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000931 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
932
933 /* Restore our state. */
Dan Gohman16e02092010-03-24 19:38:02 +0000934 if (newPartsCount == 1)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000935 fullSignificand[0] = significand.part;
936 significand = savedSignificand;
937 semantics = savedSemantics;
938
939 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
940 }
941
942 exponent -= (precision - 1);
943
Dan Gohman16e02092010-03-24 19:38:02 +0000944 if (omsb > precision) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000945 unsigned int bits, significantParts;
946 lostFraction lf;
947
948 bits = omsb - precision;
949 significantParts = partCountForBits(omsb);
950 lf = shiftRight(fullSignificand, significantParts, bits);
951 lost_fraction = combineLostFractions(lf, lost_fraction);
952 exponent += bits;
953 }
954
955 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
956
Dan Gohman16e02092010-03-24 19:38:02 +0000957 if (newPartsCount > 4)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000958 delete [] fullSignificand;
959
960 return lost_fraction;
961}
962
963/* Multiply the significands of LHS and RHS to DST. */
964lostFraction
965APFloat::divideSignificand(const APFloat &rhs)
966{
967 unsigned int bit, i, partsCount;
968 const integerPart *rhsSignificand;
969 integerPart *lhsSignificand, *dividend, *divisor;
970 integerPart scratch[4];
971 lostFraction lost_fraction;
972
973 assert(semantics == rhs.semantics);
974
975 lhsSignificand = significandParts();
976 rhsSignificand = rhs.significandParts();
977 partsCount = partCount();
978
Dan Gohman16e02092010-03-24 19:38:02 +0000979 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000980 dividend = new integerPart[partsCount * 2];
981 else
982 dividend = scratch;
983
984 divisor = dividend + partsCount;
985
986 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohman16e02092010-03-24 19:38:02 +0000987 for (i = 0; i < partsCount; i++) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +0000988 dividend[i] = lhsSignificand[i];
989 divisor[i] = rhsSignificand[i];
990 lhsSignificand[i] = 0;
991 }
992
993 exponent -= rhs.exponent;
994
995 unsigned int precision = semantics->precision;
996
997 /* Normalize the divisor. */
998 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohman16e02092010-03-24 19:38:02 +0000999 if (bit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001000 exponent += bit;
1001 APInt::tcShiftLeft(divisor, partsCount, bit);
1002 }
1003
1004 /* Normalize the dividend. */
1005 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohman16e02092010-03-24 19:38:02 +00001006 if (bit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001007 exponent -= bit;
1008 APInt::tcShiftLeft(dividend, partsCount, bit);
1009 }
1010
Neil Booth96c74712007-10-12 16:02:31 +00001011 /* Ensure the dividend >= divisor initially for the loop below.
1012 Incidentally, this means that the division loop below is
1013 guaranteed to set the integer bit to one. */
Dan Gohman16e02092010-03-24 19:38:02 +00001014 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001015 exponent--;
1016 APInt::tcShiftLeft(dividend, partsCount, 1);
1017 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1018 }
1019
1020 /* Long division. */
Dan Gohman16e02092010-03-24 19:38:02 +00001021 for (bit = precision; bit; bit -= 1) {
1022 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001023 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1024 APInt::tcSetBit(lhsSignificand, bit - 1);
1025 }
1026
1027 APInt::tcShiftLeft(dividend, partsCount, 1);
1028 }
1029
1030 /* Figure out the lost fraction. */
1031 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1032
Dan Gohman16e02092010-03-24 19:38:02 +00001033 if (cmp > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001034 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001035 else if (cmp == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001036 lost_fraction = lfExactlyHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001037 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001038 lost_fraction = lfExactlyZero;
1039 else
1040 lost_fraction = lfLessThanHalf;
1041
Dan Gohman16e02092010-03-24 19:38:02 +00001042 if (partsCount > 2)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001043 delete [] dividend;
1044
1045 return lost_fraction;
1046}
1047
1048unsigned int
1049APFloat::significandMSB() const
1050{
1051 return APInt::tcMSB(significandParts(), partCount());
1052}
1053
1054unsigned int
1055APFloat::significandLSB() const
1056{
1057 return APInt::tcLSB(significandParts(), partCount());
1058}
1059
1060/* Note that a zero result is NOT normalized to fcZero. */
1061lostFraction
1062APFloat::shiftSignificandRight(unsigned int bits)
1063{
1064 /* Our exponent should not overflow. */
1065 assert((exponent_t) (exponent + bits) >= exponent);
1066
1067 exponent += bits;
1068
1069 return shiftRight(significandParts(), partCount(), bits);
1070}
1071
1072/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1073void
1074APFloat::shiftSignificandLeft(unsigned int bits)
1075{
1076 assert(bits < semantics->precision);
1077
Dan Gohman16e02092010-03-24 19:38:02 +00001078 if (bits) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001079 unsigned int partsCount = partCount();
1080
1081 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1082 exponent -= bits;
1083
1084 assert(!APInt::tcIsZero(significandParts(), partsCount));
1085 }
1086}
1087
1088APFloat::cmpResult
1089APFloat::compareAbsoluteValue(const APFloat &rhs) const
1090{
1091 int compare;
1092
1093 assert(semantics == rhs.semantics);
1094 assert(category == fcNormal);
1095 assert(rhs.category == fcNormal);
1096
1097 compare = exponent - rhs.exponent;
1098
1099 /* If exponents are equal, do an unsigned bignum comparison of the
1100 significands. */
Dan Gohman16e02092010-03-24 19:38:02 +00001101 if (compare == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001102 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth4f881702007-09-26 21:33:42 +00001103 partCount());
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001104
Dan Gohman16e02092010-03-24 19:38:02 +00001105 if (compare > 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001106 return cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001107 else if (compare < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001108 return cmpLessThan;
1109 else
1110 return cmpEqual;
1111}
1112
1113/* Handle overflow. Sign is preserved. We either become infinity or
1114 the largest finite number. */
1115APFloat::opStatus
1116APFloat::handleOverflow(roundingMode rounding_mode)
1117{
1118 /* Infinity? */
Dan Gohman16e02092010-03-24 19:38:02 +00001119 if (rounding_mode == rmNearestTiesToEven ||
1120 rounding_mode == rmNearestTiesToAway ||
1121 (rounding_mode == rmTowardPositive && !sign) ||
1122 (rounding_mode == rmTowardNegative && sign)) {
1123 category = fcInfinity;
1124 return (opStatus) (opOverflow | opInexact);
1125 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001126
1127 /* Otherwise we become the largest finite number. */
1128 category = fcNormal;
1129 exponent = semantics->maxExponent;
1130 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth4f881702007-09-26 21:33:42 +00001131 semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001132
1133 return opInexact;
1134}
1135
Neil Boothb7dea4c2007-10-03 15:16:41 +00001136/* Returns TRUE if, when truncating the current number, with BIT the
1137 new LSB, with the given lost fraction and rounding mode, the result
1138 would need to be rounded away from zero (i.e., by increasing the
1139 signficand). This routine must work for fcZero of both signs, and
1140 fcNormal numbers. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001141bool
1142APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Boothb7dea4c2007-10-03 15:16:41 +00001143 lostFraction lost_fraction,
1144 unsigned int bit) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001145{
Dale Johanneseneaf08942007-08-31 04:03:46 +00001146 /* NaNs and infinities should not have lost fractions. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001147 assert(category == fcNormal || category == fcZero);
1148
Neil Boothb7dea4c2007-10-03 15:16:41 +00001149 /* Current callers never pass this so we don't handle it. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001150 assert(lost_fraction != lfExactlyZero);
1151
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001152 switch (rounding_mode) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001153 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001154 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001155
1156 case rmNearestTiesToAway:
1157 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1158
1159 case rmNearestTiesToEven:
Dan Gohman16e02092010-03-24 19:38:02 +00001160 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001161 return true;
1162
1163 /* Our zeroes don't have a significand to test. */
Dan Gohman16e02092010-03-24 19:38:02 +00001164 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Boothb7dea4c2007-10-03 15:16:41 +00001165 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001166
1167 return false;
1168
1169 case rmTowardZero:
1170 return false;
1171
1172 case rmTowardPositive:
1173 return sign == false;
1174
1175 case rmTowardNegative:
1176 return sign == true;
1177 }
1178}
1179
1180APFloat::opStatus
1181APFloat::normalize(roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001182 lostFraction lost_fraction)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001183{
Neil Booth4f881702007-09-26 21:33:42 +00001184 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001185 int exponentChange;
1186
Dan Gohman16e02092010-03-24 19:38:02 +00001187 if (category != fcNormal)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001188 return opOK;
1189
1190 /* Before rounding normalize the exponent of fcNormal numbers. */
1191 omsb = significandMSB() + 1;
1192
Dan Gohman16e02092010-03-24 19:38:02 +00001193 if (omsb) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001194 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewycky03dd4e82011-10-03 21:30:08 +00001195 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001196 the exponent. */
1197 exponentChange = omsb - semantics->precision;
1198
1199 /* If the resulting exponent is too high, overflow according to
1200 the rounding mode. */
Dan Gohman16e02092010-03-24 19:38:02 +00001201 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001202 return handleOverflow(rounding_mode);
1203
1204 /* Subnormal numbers have exponent minExponent, and their MSB
1205 is forced based on that. */
Dan Gohman16e02092010-03-24 19:38:02 +00001206 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001207 exponentChange = semantics->minExponent - exponent;
1208
1209 /* Shifting left is easy as we don't lose precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001210 if (exponentChange < 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001211 assert(lost_fraction == lfExactlyZero);
1212
1213 shiftSignificandLeft(-exponentChange);
1214
1215 return opOK;
1216 }
1217
Dan Gohman16e02092010-03-24 19:38:02 +00001218 if (exponentChange > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001219 lostFraction lf;
1220
1221 /* Shift right and capture any new lost fraction. */
1222 lf = shiftSignificandRight(exponentChange);
1223
1224 lost_fraction = combineLostFractions(lf, lost_fraction);
1225
1226 /* Keep OMSB up-to-date. */
Dan Gohman16e02092010-03-24 19:38:02 +00001227 if (omsb > (unsigned) exponentChange)
Neil Booth96c74712007-10-12 16:02:31 +00001228 omsb -= exponentChange;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001229 else
Neil Booth4f881702007-09-26 21:33:42 +00001230 omsb = 0;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001231 }
1232 }
1233
1234 /* Now round the number according to rounding_mode given the lost
1235 fraction. */
1236
1237 /* As specified in IEEE 754, since we do not trap we do not report
1238 underflow for exact results. */
Dan Gohman16e02092010-03-24 19:38:02 +00001239 if (lost_fraction == lfExactlyZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001240 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001241 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001242 category = fcZero;
1243
1244 return opOK;
1245 }
1246
1247 /* Increment the significand if we're rounding away from zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001248 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1249 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001250 exponent = semantics->minExponent;
1251
1252 incrementSignificand();
1253 omsb = significandMSB() + 1;
1254
1255 /* Did the significand increment overflow? */
Dan Gohman16e02092010-03-24 19:38:02 +00001256 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001257 /* Renormalize by incrementing the exponent and shifting our
Neil Booth4f881702007-09-26 21:33:42 +00001258 significand right one. However if we already have the
1259 maximum exponent we overflow to infinity. */
Dan Gohman16e02092010-03-24 19:38:02 +00001260 if (exponent == semantics->maxExponent) {
Neil Booth4f881702007-09-26 21:33:42 +00001261 category = fcInfinity;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001262
Neil Booth4f881702007-09-26 21:33:42 +00001263 return (opStatus) (opOverflow | opInexact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001264 }
1265
1266 shiftSignificandRight(1);
1267
1268 return opInexact;
1269 }
1270 }
1271
1272 /* The normal case - we were and are not denormal, and any
1273 significand increment above didn't overflow. */
Dan Gohman16e02092010-03-24 19:38:02 +00001274 if (omsb == semantics->precision)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001275 return opInexact;
1276
1277 /* We have a non-zero denormal. */
1278 assert(omsb < semantics->precision);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001279
1280 /* Canonicalize zeroes. */
Dan Gohman16e02092010-03-24 19:38:02 +00001281 if (omsb == 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001282 category = fcZero;
1283
1284 /* The fcZero case is a denormal that underflowed to zero. */
1285 return (opStatus) (opUnderflow | opInexact);
1286}
1287
1288APFloat::opStatus
1289APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1290{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001291 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001292 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001293 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001294
Dale Johanneseneaf08942007-08-31 04:03:46 +00001295 case convolve(fcNaN, fcZero):
1296 case convolve(fcNaN, fcNormal):
1297 case convolve(fcNaN, fcInfinity):
1298 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001299 case convolve(fcNormal, fcZero):
1300 case convolve(fcInfinity, fcNormal):
1301 case convolve(fcInfinity, fcZero):
1302 return opOK;
1303
Dale Johanneseneaf08942007-08-31 04:03:46 +00001304 case convolve(fcZero, fcNaN):
1305 case convolve(fcNormal, fcNaN):
1306 case convolve(fcInfinity, fcNaN):
1307 category = fcNaN;
1308 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001309 return opOK;
1310
1311 case convolve(fcNormal, fcInfinity):
1312 case convolve(fcZero, fcInfinity):
1313 category = fcInfinity;
1314 sign = rhs.sign ^ subtract;
1315 return opOK;
1316
1317 case convolve(fcZero, fcNormal):
1318 assign(rhs);
1319 sign = rhs.sign ^ subtract;
1320 return opOK;
1321
1322 case convolve(fcZero, fcZero):
1323 /* Sign depends on rounding mode; handled by caller. */
1324 return opOK;
1325
1326 case convolve(fcInfinity, fcInfinity):
1327 /* Differently signed infinities can only be validly
1328 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001329 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Boothe5e01942007-10-14 10:39:51 +00001330 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001331 return opInvalidOp;
1332 }
1333
1334 return opOK;
1335
1336 case convolve(fcNormal, fcNormal):
1337 return opDivByZero;
1338 }
1339}
1340
1341/* Add or subtract two normal numbers. */
1342lostFraction
1343APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1344{
1345 integerPart carry;
1346 lostFraction lost_fraction;
1347 int bits;
1348
1349 /* Determine if the operation on the absolute values is effectively
1350 an addition or subtraction. */
Hartmut Kaiser8df77a92007-10-25 23:15:31 +00001351 subtract ^= (sign ^ rhs.sign) ? true : false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001352
1353 /* Are we bigger exponent-wise than the RHS? */
1354 bits = exponent - rhs.exponent;
1355
1356 /* Subtraction is more subtle than one might naively expect. */
Dan Gohman16e02092010-03-24 19:38:02 +00001357 if (subtract) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001358 APFloat temp_rhs(rhs);
1359 bool reverse;
1360
Chris Lattnerada530b2007-08-24 03:02:34 +00001361 if (bits == 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001362 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1363 lost_fraction = lfExactlyZero;
Chris Lattnerada530b2007-08-24 03:02:34 +00001364 } else if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001365 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1366 shiftSignificandLeft(1);
1367 reverse = false;
Chris Lattnerada530b2007-08-24 03:02:34 +00001368 } else {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001369 lost_fraction = shiftSignificandRight(-bits - 1);
1370 temp_rhs.shiftSignificandLeft(1);
1371 reverse = true;
1372 }
1373
Chris Lattnerada530b2007-08-24 03:02:34 +00001374 if (reverse) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001375 carry = temp_rhs.subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001376 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001377 copySignificand(temp_rhs);
1378 sign = !sign;
1379 } else {
1380 carry = subtractSignificand
Neil Booth4f881702007-09-26 21:33:42 +00001381 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001382 }
1383
1384 /* Invert the lost fraction - it was on the RHS and
1385 subtracted. */
Dan Gohman16e02092010-03-24 19:38:02 +00001386 if (lost_fraction == lfLessThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001387 lost_fraction = lfMoreThanHalf;
Dan Gohman16e02092010-03-24 19:38:02 +00001388 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001389 lost_fraction = lfLessThanHalf;
1390
1391 /* The code above is intended to ensure that no borrow is
1392 necessary. */
1393 assert(!carry);
Duncan Sands1f6a3292011-08-12 14:54:45 +00001394 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001395 } else {
Dan Gohman16e02092010-03-24 19:38:02 +00001396 if (bits > 0) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001397 APFloat temp_rhs(rhs);
1398
1399 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1400 carry = addSignificand(temp_rhs);
1401 } else {
1402 lost_fraction = shiftSignificandRight(-bits);
1403 carry = addSignificand(rhs);
1404 }
1405
1406 /* We have a guard bit; generating a carry cannot happen. */
1407 assert(!carry);
Duncan Sands1f6a3292011-08-12 14:54:45 +00001408 (void)carry;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001409 }
1410
1411 return lost_fraction;
1412}
1413
1414APFloat::opStatus
1415APFloat::multiplySpecials(const APFloat &rhs)
1416{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001417 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001418 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001419 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001420
Dale Johanneseneaf08942007-08-31 04:03:46 +00001421 case convolve(fcNaN, fcZero):
1422 case convolve(fcNaN, fcNormal):
1423 case convolve(fcNaN, fcInfinity):
1424 case convolve(fcNaN, fcNaN):
1425 return opOK;
1426
1427 case convolve(fcZero, fcNaN):
1428 case convolve(fcNormal, fcNaN):
1429 case convolve(fcInfinity, fcNaN):
1430 category = fcNaN;
1431 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001432 return opOK;
1433
1434 case convolve(fcNormal, fcInfinity):
1435 case convolve(fcInfinity, fcNormal):
1436 case convolve(fcInfinity, fcInfinity):
1437 category = fcInfinity;
1438 return opOK;
1439
1440 case convolve(fcZero, fcNormal):
1441 case convolve(fcNormal, fcZero):
1442 case convolve(fcZero, fcZero):
1443 category = fcZero;
1444 return opOK;
1445
1446 case convolve(fcZero, fcInfinity):
1447 case convolve(fcInfinity, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001448 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001449 return opInvalidOp;
1450
1451 case convolve(fcNormal, fcNormal):
1452 return opOK;
1453 }
1454}
1455
1456APFloat::opStatus
1457APFloat::divideSpecials(const APFloat &rhs)
1458{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001459 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001460 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001461 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001462
Dale Johanneseneaf08942007-08-31 04:03:46 +00001463 case convolve(fcNaN, fcZero):
1464 case convolve(fcNaN, fcNormal):
1465 case convolve(fcNaN, fcInfinity):
1466 case convolve(fcNaN, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001467 case convolve(fcInfinity, fcZero):
1468 case convolve(fcInfinity, fcNormal):
1469 case convolve(fcZero, fcInfinity):
1470 case convolve(fcZero, fcNormal):
1471 return opOK;
1472
Dale Johanneseneaf08942007-08-31 04:03:46 +00001473 case convolve(fcZero, fcNaN):
1474 case convolve(fcNormal, fcNaN):
1475 case convolve(fcInfinity, fcNaN):
1476 category = fcNaN;
1477 copySignificand(rhs);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001478 return opOK;
1479
1480 case convolve(fcNormal, fcInfinity):
1481 category = fcZero;
1482 return opOK;
1483
1484 case convolve(fcNormal, fcZero):
1485 category = fcInfinity;
1486 return opDivByZero;
1487
1488 case convolve(fcInfinity, fcInfinity):
1489 case convolve(fcZero, fcZero):
Neil Boothe5e01942007-10-14 10:39:51 +00001490 makeNaN();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001491 return opInvalidOp;
1492
1493 case convolve(fcNormal, fcNormal):
1494 return opOK;
1495 }
1496}
1497
Dale Johannesened6af242009-01-21 00:35:19 +00001498APFloat::opStatus
1499APFloat::modSpecials(const APFloat &rhs)
1500{
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001501 switch (convolve(category, rhs.category)) {
Dale Johannesened6af242009-01-21 00:35:19 +00001502 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001503 llvm_unreachable(0);
Dale Johannesened6af242009-01-21 00:35:19 +00001504
1505 case convolve(fcNaN, fcZero):
1506 case convolve(fcNaN, fcNormal):
1507 case convolve(fcNaN, fcInfinity):
1508 case convolve(fcNaN, fcNaN):
1509 case convolve(fcZero, fcInfinity):
1510 case convolve(fcZero, fcNormal):
1511 case convolve(fcNormal, fcInfinity):
1512 return opOK;
1513
1514 case convolve(fcZero, fcNaN):
1515 case convolve(fcNormal, fcNaN):
1516 case convolve(fcInfinity, fcNaN):
1517 category = fcNaN;
1518 copySignificand(rhs);
1519 return opOK;
1520
1521 case convolve(fcNormal, fcZero):
1522 case convolve(fcInfinity, fcZero):
1523 case convolve(fcInfinity, fcNormal):
1524 case convolve(fcInfinity, fcInfinity):
1525 case convolve(fcZero, fcZero):
1526 makeNaN();
1527 return opInvalidOp;
1528
1529 case convolve(fcNormal, fcNormal):
1530 return opOK;
1531 }
1532}
1533
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001534/* Change sign. */
1535void
1536APFloat::changeSign()
1537{
1538 /* Look mummy, this one's easy. */
1539 sign = !sign;
1540}
1541
Dale Johannesene15c2db2007-08-31 23:35:31 +00001542void
1543APFloat::clearSign()
1544{
1545 /* So is this one. */
1546 sign = 0;
1547}
1548
1549void
1550APFloat::copySign(const APFloat &rhs)
1551{
1552 /* And this one. */
1553 sign = rhs.sign;
1554}
1555
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001556/* Normalized addition or subtraction. */
1557APFloat::opStatus
1558APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth4f881702007-09-26 21:33:42 +00001559 bool subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001560{
1561 opStatus fs;
1562
Neil Boothcaf19d72007-10-14 10:29:28 +00001563 assertArithmeticOK(*semantics);
1564
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001565 fs = addOrSubtractSpecials(rhs, subtract);
1566
1567 /* This return code means it was not a simple case. */
Dan Gohman16e02092010-03-24 19:38:02 +00001568 if (fs == opDivByZero) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001569 lostFraction lost_fraction;
1570
1571 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1572 fs = normalize(rounding_mode, lost_fraction);
1573
1574 /* Can only be zero if we lost no fraction. */
1575 assert(category != fcZero || lost_fraction == lfExactlyZero);
1576 }
1577
1578 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1579 positive zero unless rounding to minus infinity, except that
1580 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001581 if (category == fcZero) {
1582 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001583 sign = (rounding_mode == rmTowardNegative);
1584 }
1585
1586 return fs;
1587}
1588
1589/* Normalized addition. */
1590APFloat::opStatus
1591APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1592{
1593 return addOrSubtract(rhs, rounding_mode, false);
1594}
1595
1596/* Normalized subtraction. */
1597APFloat::opStatus
1598APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1599{
1600 return addOrSubtract(rhs, rounding_mode, true);
1601}
1602
1603/* Normalized multiply. */
1604APFloat::opStatus
1605APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1606{
1607 opStatus fs;
1608
Neil Boothcaf19d72007-10-14 10:29:28 +00001609 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001610 sign ^= rhs.sign;
1611 fs = multiplySpecials(rhs);
1612
Dan Gohman16e02092010-03-24 19:38:02 +00001613 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001614 lostFraction lost_fraction = multiplySignificand(rhs, 0);
1615 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001616 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001617 fs = (opStatus) (fs | opInexact);
1618 }
1619
1620 return fs;
1621}
1622
1623/* Normalized divide. */
1624APFloat::opStatus
1625APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1626{
1627 opStatus fs;
1628
Neil Boothcaf19d72007-10-14 10:29:28 +00001629 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001630 sign ^= rhs.sign;
1631 fs = divideSpecials(rhs);
1632
Dan Gohman16e02092010-03-24 19:38:02 +00001633 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001634 lostFraction lost_fraction = divideSignificand(rhs);
1635 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001636 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001637 fs = (opStatus) (fs | opInexact);
1638 }
1639
1640 return fs;
1641}
1642
Dale Johannesen24b66a82009-01-20 18:35:05 +00001643/* Normalized remainder. This is not currently correct in all cases. */
1644APFloat::opStatus
1645APFloat::remainder(const APFloat &rhs)
1646{
1647 opStatus fs;
1648 APFloat V = *this;
1649 unsigned int origSign = sign;
1650
1651 assertArithmeticOK(*semantics);
1652 fs = V.divide(rhs, rmNearestTiesToEven);
1653 if (fs == opDivByZero)
1654 return fs;
1655
1656 int parts = partCount();
1657 integerPart *x = new integerPart[parts];
1658 bool ignored;
1659 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1660 rmNearestTiesToEven, &ignored);
1661 if (fs==opInvalidOp)
1662 return fs;
1663
1664 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1665 rmNearestTiesToEven);
1666 assert(fs==opOK); // should always work
1667
1668 fs = V.multiply(rhs, rmNearestTiesToEven);
1669 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1670
1671 fs = subtract(V, rmNearestTiesToEven);
1672 assert(fs==opOK || fs==opInexact); // likewise
1673
1674 if (isZero())
1675 sign = origSign; // IEEE754 requires this
1676 delete[] x;
1677 return fs;
1678}
1679
Dan Gohman16e02092010-03-24 19:38:02 +00001680/* Normalized llvm frem (C fmod).
Dale Johannesen24b66a82009-01-20 18:35:05 +00001681 This is not currently correct in all cases. */
Dale Johannesene15c2db2007-08-31 23:35:31 +00001682APFloat::opStatus
1683APFloat::mod(const APFloat &rhs, roundingMode rounding_mode)
1684{
1685 opStatus fs;
Neil Boothcaf19d72007-10-14 10:29:28 +00001686 assertArithmeticOK(*semantics);
Dale Johannesened6af242009-01-21 00:35:19 +00001687 fs = modSpecials(rhs);
Dale Johannesene15c2db2007-08-31 23:35:31 +00001688
Dale Johannesened6af242009-01-21 00:35:19 +00001689 if (category == fcNormal && rhs.category == fcNormal) {
1690 APFloat V = *this;
1691 unsigned int origSign = sign;
Dale Johannesene15c2db2007-08-31 23:35:31 +00001692
Dale Johannesened6af242009-01-21 00:35:19 +00001693 fs = V.divide(rhs, rmNearestTiesToEven);
1694 if (fs == opDivByZero)
1695 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001696
Dale Johannesened6af242009-01-21 00:35:19 +00001697 int parts = partCount();
1698 integerPart *x = new integerPart[parts];
1699 bool ignored;
1700 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1701 rmTowardZero, &ignored);
1702 if (fs==opInvalidOp)
1703 return fs;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001704
Dale Johannesened6af242009-01-21 00:35:19 +00001705 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1706 rmNearestTiesToEven);
1707 assert(fs==opOK); // should always work
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00001708
Dale Johannesened6af242009-01-21 00:35:19 +00001709 fs = V.multiply(rhs, rounding_mode);
1710 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1711
1712 fs = subtract(V, rounding_mode);
1713 assert(fs==opOK || fs==opInexact); // likewise
1714
1715 if (isZero())
1716 sign = origSign; // IEEE754 requires this
1717 delete[] x;
1718 }
Dale Johannesene15c2db2007-08-31 23:35:31 +00001719 return fs;
1720}
1721
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001722/* Normalized fused-multiply-add. */
1723APFloat::opStatus
1724APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth4f881702007-09-26 21:33:42 +00001725 const APFloat &addend,
1726 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001727{
1728 opStatus fs;
1729
Neil Boothcaf19d72007-10-14 10:29:28 +00001730 assertArithmeticOK(*semantics);
1731
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001732 /* Post-multiplication sign, before addition. */
1733 sign ^= multiplicand.sign;
1734
1735 /* If and only if all arguments are normal do we need to do an
1736 extended-precision calculation. */
Dan Gohman16e02092010-03-24 19:38:02 +00001737 if (category == fcNormal &&
1738 multiplicand.category == fcNormal &&
1739 addend.category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001740 lostFraction lost_fraction;
1741
1742 lost_fraction = multiplySignificand(multiplicand, &addend);
1743 fs = normalize(rounding_mode, lost_fraction);
Dan Gohman16e02092010-03-24 19:38:02 +00001744 if (lost_fraction != lfExactlyZero)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001745 fs = (opStatus) (fs | opInexact);
1746
1747 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1748 positive zero unless rounding to minus infinity, except that
1749 adding two like-signed zeroes gives that zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00001750 if (category == fcZero && sign != addend.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001751 sign = (rounding_mode == rmTowardNegative);
1752 } else {
1753 fs = multiplySpecials(multiplicand);
1754
1755 /* FS can only be opOK or opInvalidOp. There is no more work
1756 to do in the latter case. The IEEE-754R standard says it is
1757 implementation-defined in this case whether, if ADDEND is a
Dale Johanneseneaf08942007-08-31 04:03:46 +00001758 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001759
1760 If we need to do the addition we can do so with normal
1761 precision. */
Dan Gohman16e02092010-03-24 19:38:02 +00001762 if (fs == opOK)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001763 fs = addOrSubtract(addend, rounding_mode, false);
1764 }
1765
1766 return fs;
1767}
1768
1769/* Comparison requires normalized numbers. */
1770APFloat::cmpResult
1771APFloat::compare(const APFloat &rhs) const
1772{
1773 cmpResult result;
1774
Neil Boothcaf19d72007-10-14 10:29:28 +00001775 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001776 assert(semantics == rhs.semantics);
1777
Mike Stumpf3dc0c02009-05-13 23:23:20 +00001778 switch (convolve(category, rhs.category)) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001779 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00001780 llvm_unreachable(0);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001781
Dale Johanneseneaf08942007-08-31 04:03:46 +00001782 case convolve(fcNaN, fcZero):
1783 case convolve(fcNaN, fcNormal):
1784 case convolve(fcNaN, fcInfinity):
1785 case convolve(fcNaN, fcNaN):
1786 case convolve(fcZero, fcNaN):
1787 case convolve(fcNormal, fcNaN):
1788 case convolve(fcInfinity, fcNaN):
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001789 return cmpUnordered;
1790
1791 case convolve(fcInfinity, fcNormal):
1792 case convolve(fcInfinity, fcZero):
1793 case convolve(fcNormal, fcZero):
Dan Gohman16e02092010-03-24 19:38:02 +00001794 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001795 return cmpLessThan;
1796 else
1797 return cmpGreaterThan;
1798
1799 case convolve(fcNormal, fcInfinity):
1800 case convolve(fcZero, fcInfinity):
1801 case convolve(fcZero, fcNormal):
Dan Gohman16e02092010-03-24 19:38:02 +00001802 if (rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001803 return cmpGreaterThan;
1804 else
1805 return cmpLessThan;
1806
1807 case convolve(fcInfinity, fcInfinity):
Dan Gohman16e02092010-03-24 19:38:02 +00001808 if (sign == rhs.sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001809 return cmpEqual;
Dan Gohman16e02092010-03-24 19:38:02 +00001810 else if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001811 return cmpLessThan;
1812 else
1813 return cmpGreaterThan;
1814
1815 case convolve(fcZero, fcZero):
1816 return cmpEqual;
1817
1818 case convolve(fcNormal, fcNormal):
1819 break;
1820 }
1821
1822 /* Two normal numbers. Do they have the same sign? */
Dan Gohman16e02092010-03-24 19:38:02 +00001823 if (sign != rhs.sign) {
1824 if (sign)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001825 result = cmpLessThan;
1826 else
1827 result = cmpGreaterThan;
1828 } else {
1829 /* Compare absolute values; invert result if negative. */
1830 result = compareAbsoluteValue(rhs);
1831
Dan Gohman16e02092010-03-24 19:38:02 +00001832 if (sign) {
1833 if (result == cmpLessThan)
Neil Booth4f881702007-09-26 21:33:42 +00001834 result = cmpGreaterThan;
Dan Gohman16e02092010-03-24 19:38:02 +00001835 else if (result == cmpGreaterThan)
Neil Booth4f881702007-09-26 21:33:42 +00001836 result = cmpLessThan;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001837 }
1838 }
1839
1840 return result;
1841}
1842
Dale Johannesen23a98552008-10-09 23:00:39 +00001843/// APFloat::convert - convert a value of one floating point type to another.
1844/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1845/// records whether the transformation lost information, i.e. whether
1846/// converting the result back to the original type will produce the
1847/// original value (this is almost the same as return value==fsOK, but there
1848/// are edge cases where this is not so).
1849
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001850APFloat::opStatus
1851APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen23a98552008-10-09 23:00:39 +00001852 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001853{
Neil Boothc8db43d2007-09-22 02:56:19 +00001854 lostFraction lostFraction;
1855 unsigned int newPartCount, oldPartCount;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001856 opStatus fs;
Neil Booth4f881702007-09-26 21:33:42 +00001857
Neil Boothcaf19d72007-10-14 10:29:28 +00001858 assertArithmeticOK(*semantics);
Dale Johannesen79f82f92008-04-20 01:34:03 +00001859 assertArithmeticOK(toSemantics);
Neil Boothc8db43d2007-09-22 02:56:19 +00001860 lostFraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001861 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Boothc8db43d2007-09-22 02:56:19 +00001862 oldPartCount = partCount();
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001863
Neil Boothc8db43d2007-09-22 02:56:19 +00001864 /* Handle storage complications. If our new form is wider,
1865 re-allocate our bit pattern into wider storage. If it is
1866 narrower, we ignore the excess parts, but if narrowing to a
Dale Johannesen902ff942007-09-25 17:25:00 +00001867 single part we need to free the old storage.
1868 Be careful not to reference significandParts for zeroes
1869 and infinities, since it aborts. */
Neil Boothc8db43d2007-09-22 02:56:19 +00001870 if (newPartCount > oldPartCount) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001871 integerPart *newParts;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001872 newParts = new integerPart[newPartCount];
1873 APInt::tcSet(newParts, 0, newPartCount);
Dale Johannesen902ff942007-09-25 17:25:00 +00001874 if (category==fcNormal || category==fcNaN)
1875 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001876 freeSignificand();
1877 significand.parts = newParts;
Neil Boothc8db43d2007-09-22 02:56:19 +00001878 } else if (newPartCount < oldPartCount) {
1879 /* Capture any lost fraction through truncation of parts so we get
1880 correct rounding whilst normalizing. */
Dale Johannesen902ff942007-09-25 17:25:00 +00001881 if (category==fcNormal)
1882 lostFraction = lostFractionThroughTruncation
1883 (significandParts(), oldPartCount, toSemantics.precision);
1884 if (newPartCount == 1) {
1885 integerPart newPart = 0;
Neil Booth4f881702007-09-26 21:33:42 +00001886 if (category==fcNormal || category==fcNaN)
Dale Johannesen902ff942007-09-25 17:25:00 +00001887 newPart = significandParts()[0];
1888 freeSignificand();
1889 significand.part = newPart;
1890 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001891 }
1892
Dan Gohman16e02092010-03-24 19:38:02 +00001893 if (category == fcNormal) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001894 /* Re-interpret our bit-pattern. */
1895 exponent += toSemantics.precision - semantics->precision;
1896 semantics = &toSemantics;
Neil Boothc8db43d2007-09-22 02:56:19 +00001897 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen23a98552008-10-09 23:00:39 +00001898 *losesInfo = (fs != opOK);
Dale Johannesen902ff942007-09-25 17:25:00 +00001899 } else if (category == fcNaN) {
1900 int shift = toSemantics.precision - semantics->precision;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001901 // Do this now so significandParts gets the right answer
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001902 const fltSemantics *oldSemantics = semantics;
Dale Johannesenb63fa052008-01-31 18:34:01 +00001903 semantics = &toSemantics;
Dale Johannesen23a98552008-10-09 23:00:39 +00001904 *losesInfo = false;
Dale Johannesen902ff942007-09-25 17:25:00 +00001905 // No normalization here, just truncate
1906 if (shift>0)
1907 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001908 else if (shift < 0) {
1909 unsigned ushift = -shift;
Dale Johannesen23a98552008-10-09 23:00:39 +00001910 // Figure out if we are losing information. This happens
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001911 // if are shifting out something other than 0s, or if the x87 long
1912 // double input did not have its integer bit set (pseudo-NaN), or if the
1913 // x87 long double input did not have its QNan bit set (because the x87
1914 // hardware sets this bit when converting a lower-precision NaN to
1915 // x87 long double).
1916 if (APInt::tcLSB(significandParts(), newPartCount) < ushift)
Dale Johannesen23a98552008-10-09 23:00:39 +00001917 *losesInfo = true;
Dan Gohman16e02092010-03-24 19:38:02 +00001918 if (oldSemantics == &APFloat::x87DoubleExtended &&
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001919 (!(*significandParts() & 0x8000000000000000ULL) ||
1920 !(*significandParts() & 0x4000000000000000ULL)))
Dale Johannesen23a98552008-10-09 23:00:39 +00001921 *losesInfo = true;
Dale Johannesen2df5eec2008-10-06 22:59:10 +00001922 APInt::tcShiftRight(significandParts(), newPartCount, ushift);
1923 }
Dale Johannesen902ff942007-09-25 17:25:00 +00001924 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
1925 // does not give you back the same bits. This is dubious, and we
1926 // don't currently do it. You're really supposed to get
1927 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen23a98552008-10-09 23:00:39 +00001928 fs = opOK;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001929 } else {
1930 semantics = &toSemantics;
1931 fs = opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00001932 *losesInfo = false;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001933 }
1934
1935 return fs;
1936}
1937
1938/* Convert a floating point number to an integer according to the
1939 rounding mode. If the rounded integer value is out of range this
Neil Boothee7ae382007-11-01 22:43:37 +00001940 returns an invalid operation exception and the contents of the
1941 destination parts are unspecified. If the rounded value is in
Chris Lattnerb39cdde2007-08-20 22:49:32 +00001942 range but the floating point number is not the exact integer, the C
1943 standard doesn't require an inexact exception to be raised. IEEE
1944 854 does require it so we do that.
1945
1946 Note that for conversions to integer type the C standard requires
1947 round-to-zero to always be used. */
1948APFloat::opStatus
Neil Boothee7ae382007-11-01 22:43:37 +00001949APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
1950 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00001951 roundingMode rounding_mode,
1952 bool *isExact) const
Neil Boothee7ae382007-11-01 22:43:37 +00001953{
1954 lostFraction lost_fraction;
1955 const integerPart *src;
1956 unsigned int dstPartsCount, truncatedBits;
1957
Evan Cheng794a7db2008-11-26 01:11:57 +00001958 assertArithmeticOK(*semantics);
Neil Boothe3d936a2007-11-02 15:10:05 +00001959
Dale Johannesen23a98552008-10-09 23:00:39 +00001960 *isExact = false;
1961
Neil Boothee7ae382007-11-01 22:43:37 +00001962 /* Handle the three special cases first. */
Dan Gohman16e02092010-03-24 19:38:02 +00001963 if (category == fcInfinity || category == fcNaN)
Neil Boothee7ae382007-11-01 22:43:37 +00001964 return opInvalidOp;
1965
1966 dstPartsCount = partCountForBits(width);
1967
Dan Gohman16e02092010-03-24 19:38:02 +00001968 if (category == fcZero) {
Neil Boothee7ae382007-11-01 22:43:37 +00001969 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesene4a42452008-10-07 00:40:01 +00001970 // Negative zero can't be represented as an int.
Dale Johannesen23a98552008-10-09 23:00:39 +00001971 *isExact = !sign;
1972 return opOK;
Neil Boothee7ae382007-11-01 22:43:37 +00001973 }
1974
1975 src = significandParts();
1976
1977 /* Step 1: place our absolute value, with any fraction truncated, in
1978 the destination. */
1979 if (exponent < 0) {
1980 /* Our absolute value is less than one; truncate everything. */
1981 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen1f54f582009-01-19 21:17:05 +00001982 /* For exponent -1 the integer bit represents .5, look at that.
1983 For smaller exponents leftmost truncated bit is 0. */
1984 truncatedBits = semantics->precision -1U - exponent;
Neil Boothee7ae382007-11-01 22:43:37 +00001985 } else {
1986 /* We want the most significant (exponent + 1) bits; the rest are
1987 truncated. */
1988 unsigned int bits = exponent + 1U;
1989
1990 /* Hopelessly large in magnitude? */
1991 if (bits > width)
1992 return opInvalidOp;
1993
1994 if (bits < semantics->precision) {
1995 /* We truncate (semantics->precision - bits) bits. */
1996 truncatedBits = semantics->precision - bits;
1997 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
1998 } else {
1999 /* We want at least as many bits as are available. */
2000 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2001 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2002 truncatedBits = 0;
2003 }
2004 }
2005
2006 /* Step 2: work out any lost fraction, and increment the absolute
2007 value if we would round away from zero. */
2008 if (truncatedBits) {
2009 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2010 truncatedBits);
Dan Gohman16e02092010-03-24 19:38:02 +00002011 if (lost_fraction != lfExactlyZero &&
2012 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Boothee7ae382007-11-01 22:43:37 +00002013 if (APInt::tcIncrement(parts, dstPartsCount))
2014 return opInvalidOp; /* Overflow. */
2015 }
2016 } else {
2017 lost_fraction = lfExactlyZero;
2018 }
2019
2020 /* Step 3: check if we fit in the destination. */
2021 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2022
2023 if (sign) {
2024 if (!isSigned) {
2025 /* Negative numbers cannot be represented as unsigned. */
2026 if (omsb != 0)
2027 return opInvalidOp;
2028 } else {
2029 /* It takes omsb bits to represent the unsigned integer value.
2030 We lose a bit for the sign, but care is needed as the
2031 maximally negative integer is a special case. */
2032 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2033 return opInvalidOp;
2034
2035 /* This case can happen because of rounding. */
2036 if (omsb > width)
2037 return opInvalidOp;
2038 }
2039
2040 APInt::tcNegate (parts, dstPartsCount);
2041 } else {
2042 if (omsb >= width + !isSigned)
2043 return opInvalidOp;
2044 }
2045
Dale Johannesen23a98552008-10-09 23:00:39 +00002046 if (lost_fraction == lfExactlyZero) {
2047 *isExact = true;
Neil Boothee7ae382007-11-01 22:43:37 +00002048 return opOK;
Dale Johannesen23a98552008-10-09 23:00:39 +00002049 } else
Neil Boothee7ae382007-11-01 22:43:37 +00002050 return opInexact;
2051}
2052
2053/* Same as convertToSignExtendedInteger, except we provide
2054 deterministic values in case of an invalid operation exception,
2055 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen23a98552008-10-09 23:00:39 +00002056 for underflow or overflow.
2057 The *isExact output tells whether the result is exact, in the sense
2058 that converting it back to the original floating point type produces
2059 the original value. This is almost equivalent to result==opOK,
2060 except for negative zeroes.
2061*/
Neil Boothee7ae382007-11-01 22:43:37 +00002062APFloat::opStatus
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002063APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth4f881702007-09-26 21:33:42 +00002064 bool isSigned,
Dale Johannesen23a98552008-10-09 23:00:39 +00002065 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002066{
Neil Boothee7ae382007-11-01 22:43:37 +00002067 opStatus fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002068
Dan Gohman16e02092010-03-24 19:38:02 +00002069 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen23a98552008-10-09 23:00:39 +00002070 isExact);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002071
Neil Boothee7ae382007-11-01 22:43:37 +00002072 if (fs == opInvalidOp) {
2073 unsigned int bits, dstPartsCount;
2074
2075 dstPartsCount = partCountForBits(width);
2076
2077 if (category == fcNaN)
2078 bits = 0;
2079 else if (sign)
2080 bits = isSigned;
2081 else
2082 bits = width - isSigned;
2083
2084 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2085 if (sign && isSigned)
2086 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002087 }
2088
Neil Boothee7ae382007-11-01 22:43:37 +00002089 return fs;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002090}
2091
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +00002092/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2093 an APSInt, whose initial bit-width and signed-ness are used to determine the
2094 precision of the conversion.
2095 */
2096APFloat::opStatus
2097APFloat::convertToInteger(APSInt &result,
2098 roundingMode rounding_mode, bool *isExact) const
2099{
2100 unsigned bitWidth = result.getBitWidth();
2101 SmallVector<uint64_t, 4> parts(result.getNumWords());
2102 opStatus status = convertToInteger(
2103 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2104 // Keeps the original signed-ness.
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002105 result = APInt(bitWidth, parts);
Jeffrey Yasskin3d42bfb2011-07-15 07:04:56 +00002106 return status;
2107}
2108
Neil Booth643ce592007-10-07 12:07:53 +00002109/* Convert an unsigned integer SRC to a floating point number,
2110 rounding according to ROUNDING_MODE. The sign of the floating
2111 point number is not modified. */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002112APFloat::opStatus
Neil Booth643ce592007-10-07 12:07:53 +00002113APFloat::convertFromUnsignedParts(const integerPart *src,
2114 unsigned int srcCount,
2115 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002116{
Neil Booth5477f852007-10-08 14:39:42 +00002117 unsigned int omsb, precision, dstCount;
Neil Booth643ce592007-10-07 12:07:53 +00002118 integerPart *dst;
Neil Booth5477f852007-10-08 14:39:42 +00002119 lostFraction lost_fraction;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002120
Neil Boothcaf19d72007-10-14 10:29:28 +00002121 assertArithmeticOK(*semantics);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002122 category = fcNormal;
Neil Booth5477f852007-10-08 14:39:42 +00002123 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth643ce592007-10-07 12:07:53 +00002124 dst = significandParts();
2125 dstCount = partCount();
Neil Booth5477f852007-10-08 14:39:42 +00002126 precision = semantics->precision;
Neil Booth643ce592007-10-07 12:07:53 +00002127
Nick Lewycky03dd4e82011-10-03 21:30:08 +00002128 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth5477f852007-10-08 14:39:42 +00002129 be that many; extract what we can. */
2130 if (precision <= omsb) {
2131 exponent = omsb - 1;
Neil Booth643ce592007-10-07 12:07:53 +00002132 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth5477f852007-10-08 14:39:42 +00002133 omsb - precision);
2134 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2135 } else {
2136 exponent = precision - 1;
2137 lost_fraction = lfExactlyZero;
2138 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth643ce592007-10-07 12:07:53 +00002139 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002140
2141 return normalize(rounding_mode, lost_fraction);
2142}
2143
Dan Gohman93c276e2008-02-29 01:26:11 +00002144APFloat::opStatus
2145APFloat::convertFromAPInt(const APInt &Val,
2146 bool isSigned,
2147 roundingMode rounding_mode)
2148{
2149 unsigned int partCount = Val.getNumWords();
2150 APInt api = Val;
2151
2152 sign = false;
2153 if (isSigned && api.isNegative()) {
2154 sign = true;
2155 api = -api;
2156 }
2157
2158 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2159}
2160
Neil Boothf16c5952007-10-07 12:15:41 +00002161/* Convert a two's complement integer SRC to a floating point number,
2162 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2163 integer is signed, in which case it must be sign-extended. */
2164APFloat::opStatus
2165APFloat::convertFromSignExtendedInteger(const integerPart *src,
2166 unsigned int srcCount,
2167 bool isSigned,
2168 roundingMode rounding_mode)
2169{
2170 opStatus status;
2171
Neil Boothcaf19d72007-10-14 10:29:28 +00002172 assertArithmeticOK(*semantics);
Dan Gohman16e02092010-03-24 19:38:02 +00002173 if (isSigned &&
2174 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Neil Boothf16c5952007-10-07 12:15:41 +00002175 integerPart *copy;
2176
2177 /* If we're signed and negative negate a copy. */
2178 sign = true;
2179 copy = new integerPart[srcCount];
2180 APInt::tcAssign(copy, src, srcCount);
2181 APInt::tcNegate(copy, srcCount);
2182 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
2183 delete [] copy;
2184 } else {
2185 sign = false;
2186 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2187 }
2188
2189 return status;
2190}
2191
Neil Boothccf596a2007-10-07 11:45:55 +00002192/* FIXME: should this just take a const APInt reference? */
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002193APFloat::opStatus
Neil Boothccf596a2007-10-07 11:45:55 +00002194APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2195 unsigned int width, bool isSigned,
2196 roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002197{
Dale Johannesen910993e2007-09-21 22:09:37 +00002198 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002199 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002200
2201 sign = false;
Dan Gohman16e02092010-03-24 19:38:02 +00002202 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesencce23a42007-09-30 18:17:01 +00002203 sign = true;
2204 api = -api;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002205 }
2206
Neil Booth7a7bc0f2007-10-07 12:10:57 +00002207 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002208}
2209
2210APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002211APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002212{
Erick Tryzelaarf8bc8012009-08-18 18:20:37 +00002213 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002214 integerPart *significand;
2215 unsigned int bitPos, partsCount;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002216 StringRef::iterator dot, firstSignificantDigit;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002217
2218 zeroSignificand();
2219 exponent = 0;
2220 category = fcNormal;
2221
2222 significand = significandParts();
2223 partsCount = partCount();
2224 bitPos = partsCount * integerPartWidth;
2225
Neil Booth33d4c922007-10-07 08:51:21 +00002226 /* Skip leading zeroes and any (hexa)decimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002227 StringRef::iterator begin = s.begin();
2228 StringRef::iterator end = s.end();
2229 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002230 firstSignificantDigit = p;
2231
Dan Gohman16e02092010-03-24 19:38:02 +00002232 for (; p != end;) {
Dale Johannesen386f3e92008-05-14 22:53:25 +00002233 integerPart hex_value;
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002234
Dan Gohman16e02092010-03-24 19:38:02 +00002235 if (*p == '.') {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002236 assert(dot == end && "String contains multiple dots");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002237 dot = p++;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002238 if (p == end) {
2239 break;
2240 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002241 }
2242
2243 hex_value = hexDigitValue(*p);
Dan Gohman16e02092010-03-24 19:38:02 +00002244 if (hex_value == -1U) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002245 break;
2246 }
2247
2248 p++;
2249
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002250 if (p == end) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002251 break;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002252 } else {
2253 /* Store the number whilst 4-bit nibbles remain. */
Dan Gohman16e02092010-03-24 19:38:02 +00002254 if (bitPos) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002255 bitPos -= 4;
2256 hex_value <<= bitPos % integerPartWidth;
2257 significand[bitPos / integerPartWidth] |= hex_value;
2258 } else {
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002259 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
Dan Gohman16e02092010-03-24 19:38:02 +00002260 while (p != end && hexDigitValue(*p) != -1U)
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002261 p++;
2262 break;
2263 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002264 }
2265 }
2266
2267 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002268 assert(p != end && "Hex strings require an exponent");
2269 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2270 assert(p != begin && "Significand has no digits");
2271 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002272
2273 /* Ignore the exponent if we are zero. */
Dan Gohman16e02092010-03-24 19:38:02 +00002274 if (p != firstSignificantDigit) {
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002275 int expAdjustment;
2276
2277 /* Implicit hexadecimal point? */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002278 if (dot == end)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002279 dot = p;
2280
2281 /* Calculate the exponent adjustment implicit in the number of
2282 significant digits. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002283 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohman16e02092010-03-24 19:38:02 +00002284 if (expAdjustment < 0)
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002285 expAdjustment++;
2286 expAdjustment = expAdjustment * 4 - 1;
2287
2288 /* Adjust for writing the significand starting at the most
2289 significant nibble. */
2290 expAdjustment += semantics->precision;
2291 expAdjustment -= partsCount * integerPartWidth;
2292
2293 /* Adjust for the given exponent. */
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002294 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002295 }
2296
2297 return normalize(rounding_mode, lost_fraction);
2298}
2299
2300APFloat::opStatus
Neil Booth96c74712007-10-12 16:02:31 +00002301APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2302 unsigned sigPartCount, int exp,
2303 roundingMode rounding_mode)
2304{
2305 unsigned int parts, pow5PartCount;
Neil Boothcaf19d72007-10-14 10:29:28 +00002306 fltSemantics calcSemantics = { 32767, -32767, 0, true };
Neil Booth96c74712007-10-12 16:02:31 +00002307 integerPart pow5Parts[maxPowerOfFiveParts];
2308 bool isNearest;
2309
Dan Gohman16e02092010-03-24 19:38:02 +00002310 isNearest = (rounding_mode == rmNearestTiesToEven ||
2311 rounding_mode == rmNearestTiesToAway);
Neil Booth96c74712007-10-12 16:02:31 +00002312
2313 parts = partCountForBits(semantics->precision + 11);
2314
2315 /* Calculate pow(5, abs(exp)). */
2316 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2317
2318 for (;; parts *= 2) {
2319 opStatus sigStatus, powStatus;
2320 unsigned int excessPrecision, truncatedBits;
2321
2322 calcSemantics.precision = parts * integerPartWidth - 1;
2323 excessPrecision = calcSemantics.precision - semantics->precision;
2324 truncatedBits = excessPrecision;
2325
2326 APFloat decSig(calcSemantics, fcZero, sign);
2327 APFloat pow5(calcSemantics, fcZero, false);
2328
2329 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2330 rmNearestTiesToEven);
2331 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2332 rmNearestTiesToEven);
2333 /* Add exp, as 10^n = 5^n * 2^n. */
2334 decSig.exponent += exp;
2335
2336 lostFraction calcLostFraction;
Evan Cheng48e8c802008-05-02 21:15:08 +00002337 integerPart HUerr, HUdistance;
2338 unsigned int powHUerr;
Neil Booth96c74712007-10-12 16:02:31 +00002339
2340 if (exp >= 0) {
2341 /* multiplySignificand leaves the precision-th bit set to 1. */
2342 calcLostFraction = decSig.multiplySignificand(pow5, NULL);
2343 powHUerr = powStatus != opOK;
2344 } else {
2345 calcLostFraction = decSig.divideSignificand(pow5);
2346 /* Denormal numbers have less precision. */
2347 if (decSig.exponent < semantics->minExponent) {
2348 excessPrecision += (semantics->minExponent - decSig.exponent);
2349 truncatedBits = excessPrecision;
2350 if (excessPrecision > calcSemantics.precision)
2351 excessPrecision = calcSemantics.precision;
2352 }
2353 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002354 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Booth96c74712007-10-12 16:02:31 +00002355 }
2356
2357 /* Both multiplySignificand and divideSignificand return the
2358 result with the integer bit set. */
Evan Cheng99ebfa52009-10-27 21:35:42 +00002359 assert(APInt::tcExtractBit
2360 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Booth96c74712007-10-12 16:02:31 +00002361
2362 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2363 powHUerr);
2364 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2365 excessPrecision, isNearest);
2366
2367 /* Are we guaranteed to round correctly if we truncate? */
2368 if (HUdistance >= HUerr) {
2369 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2370 calcSemantics.precision - excessPrecision,
2371 excessPrecision);
2372 /* Take the exponent of decSig. If we tcExtract-ed less bits
2373 above we must adjust our exponent to compensate for the
2374 implicit right shift. */
2375 exponent = (decSig.exponent + semantics->precision
2376 - (calcSemantics.precision - excessPrecision));
2377 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2378 decSig.partCount(),
2379 truncatedBits);
2380 return normalize(rounding_mode, calcLostFraction);
2381 }
2382 }
2383}
2384
2385APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002386APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Booth96c74712007-10-12 16:02:31 +00002387{
Neil Booth1870f292007-10-14 10:16:12 +00002388 decimalInfo D;
Neil Booth96c74712007-10-12 16:02:31 +00002389 opStatus fs;
2390
Neil Booth1870f292007-10-14 10:16:12 +00002391 /* Scan the text. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002392 StringRef::iterator p = str.begin();
2393 interpretDecimal(p, str.end(), &D);
Neil Booth96c74712007-10-12 16:02:31 +00002394
Neil Booth686700e2007-10-15 15:00:55 +00002395 /* Handle the quick cases. First the case of no significant digits,
2396 i.e. zero, and then exponents that are obviously too large or too
2397 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2398 definitely overflows if
2399
2400 (exp - 1) * L >= maxExponent
2401
2402 and definitely underflows to zero where
2403
2404 (exp + 1) * L <= minExponent - precision
2405
2406 With integer arithmetic the tightest bounds for L are
2407
2408 93/28 < L < 196/59 [ numerator <= 256 ]
2409 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2410 */
2411
Neil Boothcc233592007-12-05 13:06:04 +00002412 if (decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Booth96c74712007-10-12 16:02:31 +00002413 category = fcZero;
2414 fs = opOK;
John McCall8b3f3302010-02-26 22:20:41 +00002415
2416 /* Check whether the normalized exponent is high enough to overflow
2417 max during the log-rebasing in the max-exponent check below. */
2418 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
2419 fs = handleOverflow(rounding_mode);
2420
2421 /* If it wasn't, then it also wasn't high enough to overflow max
2422 during the log-rebasing in the min-exponent check. Check that it
2423 won't overflow min in either check, then perform the min-exponent
2424 check. */
2425 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
2426 (D.normalizedExponent + 1) * 28738 <=
2427 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth686700e2007-10-15 15:00:55 +00002428 /* Underflow to zero and round. */
2429 zeroSignificand();
2430 fs = normalize(rounding_mode, lfLessThanHalf);
John McCall8b3f3302010-02-26 22:20:41 +00002431
2432 /* We can finally safely perform the max-exponent check. */
Neil Booth686700e2007-10-15 15:00:55 +00002433 } else if ((D.normalizedExponent - 1) * 42039
2434 >= 12655 * semantics->maxExponent) {
2435 /* Overflow and round. */
2436 fs = handleOverflow(rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002437 } else {
Neil Booth1870f292007-10-14 10:16:12 +00002438 integerPart *decSignificand;
2439 unsigned int partCount;
Neil Booth96c74712007-10-12 16:02:31 +00002440
Neil Booth1870f292007-10-14 10:16:12 +00002441 /* A tight upper bound on number of bits required to hold an
Neil Booth686700e2007-10-15 15:00:55 +00002442 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth1870f292007-10-14 10:16:12 +00002443 to hold the full significand, and an extra part required by
2444 tcMultiplyPart. */
Evan Cheng48e8c802008-05-02 21:15:08 +00002445 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth686700e2007-10-15 15:00:55 +00002446 partCount = partCountForBits(1 + 196 * partCount / 59);
Neil Booth1870f292007-10-14 10:16:12 +00002447 decSignificand = new integerPart[partCount + 1];
2448 partCount = 0;
Neil Booth96c74712007-10-12 16:02:31 +00002449
Neil Booth1870f292007-10-14 10:16:12 +00002450 /* Convert to binary efficiently - we do almost all multiplication
2451 in an integerPart. When this would overflow do we do a single
2452 bignum multiplication, and then revert again to multiplication
2453 in an integerPart. */
2454 do {
2455 integerPart decValue, val, multiplier;
2456
2457 val = 0;
2458 multiplier = 1;
2459
2460 do {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002461 if (*p == '.') {
Neil Booth1870f292007-10-14 10:16:12 +00002462 p++;
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002463 if (p == str.end()) {
2464 break;
2465 }
2466 }
Neil Booth1870f292007-10-14 10:16:12 +00002467 decValue = decDigitValue(*p++);
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002468 assert(decValue < 10U && "Invalid character in significand");
Neil Booth1870f292007-10-14 10:16:12 +00002469 multiplier *= 10;
2470 val = val * 10 + decValue;
2471 /* The maximum number that can be multiplied by ten with any
2472 digit added without overflowing an integerPart. */
2473 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2474
2475 /* Multiply out the current part. */
2476 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2477 partCount, partCount + 1, false);
2478
2479 /* If we used another part (likely but not guaranteed), increase
2480 the count. */
2481 if (decSignificand[partCount])
2482 partCount++;
2483 } while (p <= D.lastSigDigit);
Neil Booth96c74712007-10-12 16:02:31 +00002484
Neil Booth43a4b282007-11-01 22:51:07 +00002485 category = fcNormal;
Neil Booth96c74712007-10-12 16:02:31 +00002486 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth1870f292007-10-14 10:16:12 +00002487 D.exponent, rounding_mode);
Neil Booth96c74712007-10-12 16:02:31 +00002488
Neil Booth1870f292007-10-14 10:16:12 +00002489 delete [] decSignificand;
2490 }
Neil Booth96c74712007-10-12 16:02:31 +00002491
2492 return fs;
2493}
2494
2495APFloat::opStatus
Benjamin Kramer38e59892010-07-14 22:38:02 +00002496APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth4f881702007-09-26 21:33:42 +00002497{
Neil Boothcaf19d72007-10-14 10:29:28 +00002498 assertArithmeticOK(*semantics);
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002499 assert(!str.empty() && "Invalid string length");
Neil Boothcaf19d72007-10-14 10:29:28 +00002500
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002501 /* Handle a leading minus sign. */
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002502 StringRef::iterator p = str.begin();
2503 size_t slen = str.size();
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002504 sign = *p == '-' ? 1 : 0;
Dan Gohman16e02092010-03-24 19:38:02 +00002505 if (*p == '-' || *p == '+') {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002506 p++;
2507 slen--;
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002508 assert(slen && "String has no digits");
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002509 }
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002510
Dan Gohman16e02092010-03-24 19:38:02 +00002511 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002512 assert(slen - 2 && "Invalid string");
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002513 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaara15d8902009-08-16 23:36:19 +00002514 rounding_mode);
2515 }
Bill Wendlingb7c0d942008-11-27 08:00:12 +00002516
Erick Tryzelaarc78b33b2009-08-20 23:30:43 +00002517 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerb39cdde2007-08-20 22:49:32 +00002518}
Dale Johannesen343e7702007-08-24 00:56:33 +00002519
Neil Bootha30b0ee2007-10-03 22:26:02 +00002520/* Write out a hexadecimal representation of the floating point value
2521 to DST, which must be of sufficient size, in the C99 form
2522 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2523 excluding the terminating NUL.
2524
2525 If UPPERCASE, the output is in upper case, otherwise in lower case.
2526
2527 HEXDIGITS digits appear altogether, rounding the value if
2528 necessary. If HEXDIGITS is 0, the minimal precision to display the
2529 number precisely is used instead. If nothing would appear after
2530 the decimal point it is suppressed.
2531
2532 The decimal exponent is always printed and has at least one digit.
2533 Zero values display an exponent of zero. Infinities and NaNs
2534 appear as "infinity" or "nan" respectively.
2535
2536 The above rules are as specified by C99. There is ambiguity about
2537 what the leading hexadecimal digit should be. This implementation
2538 uses whatever is necessary so that the exponent is displayed as
2539 stored. This implies the exponent will fall within the IEEE format
2540 range, and the leading hexadecimal digit will be 0 (for denormals),
2541 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2542 any other digits zero).
2543*/
2544unsigned int
2545APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2546 bool upperCase, roundingMode rounding_mode) const
2547{
2548 char *p;
2549
Neil Boothcaf19d72007-10-14 10:29:28 +00002550 assertArithmeticOK(*semantics);
2551
Neil Bootha30b0ee2007-10-03 22:26:02 +00002552 p = dst;
2553 if (sign)
2554 *dst++ = '-';
2555
2556 switch (category) {
2557 case fcInfinity:
2558 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2559 dst += sizeof infinityL - 1;
2560 break;
2561
2562 case fcNaN:
2563 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2564 dst += sizeof NaNU - 1;
2565 break;
2566
2567 case fcZero:
2568 *dst++ = '0';
2569 *dst++ = upperCase ? 'X': 'x';
2570 *dst++ = '0';
2571 if (hexDigits > 1) {
2572 *dst++ = '.';
2573 memset (dst, '0', hexDigits - 1);
2574 dst += hexDigits - 1;
2575 }
2576 *dst++ = upperCase ? 'P': 'p';
2577 *dst++ = '0';
2578 break;
2579
2580 case fcNormal:
2581 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2582 break;
2583 }
2584
2585 *dst = 0;
2586
Evan Cheng48e8c802008-05-02 21:15:08 +00002587 return static_cast<unsigned int>(dst - p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002588}
2589
2590/* Does the hard work of outputting the correctly rounded hexadecimal
2591 form of a normal floating point number with the specified number of
2592 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2593 digits necessary to print the value precisely is output. */
2594char *
2595APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2596 bool upperCase,
2597 roundingMode rounding_mode) const
2598{
2599 unsigned int count, valueBits, shift, partsCount, outputDigits;
2600 const char *hexDigitChars;
2601 const integerPart *significand;
2602 char *p;
2603 bool roundUp;
2604
2605 *dst++ = '0';
2606 *dst++ = upperCase ? 'X': 'x';
2607
2608 roundUp = false;
2609 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2610
2611 significand = significandParts();
2612 partsCount = partCount();
2613
2614 /* +3 because the first digit only uses the single integer bit, so
2615 we have 3 virtual zero most-significant-bits. */
2616 valueBits = semantics->precision + 3;
2617 shift = integerPartWidth - valueBits % integerPartWidth;
2618
2619 /* The natural number of digits required ignoring trailing
2620 insignificant zeroes. */
2621 outputDigits = (valueBits - significandLSB () + 3) / 4;
2622
2623 /* hexDigits of zero means use the required number for the
2624 precision. Otherwise, see if we are truncating. If we are,
Neil Booth978661d2007-10-06 00:24:48 +00002625 find out if we need to round away from zero. */
Neil Bootha30b0ee2007-10-03 22:26:02 +00002626 if (hexDigits) {
2627 if (hexDigits < outputDigits) {
2628 /* We are dropping non-zero bits, so need to check how to round.
2629 "bits" is the number of dropped bits. */
2630 unsigned int bits;
2631 lostFraction fraction;
2632
2633 bits = valueBits - hexDigits * 4;
2634 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2635 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2636 }
2637 outputDigits = hexDigits;
2638 }
2639
2640 /* Write the digits consecutively, and start writing in the location
2641 of the hexadecimal point. We move the most significant digit
2642 left and add the hexadecimal point later. */
2643 p = ++dst;
2644
2645 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2646
2647 while (outputDigits && count) {
2648 integerPart part;
2649
2650 /* Put the most significant integerPartWidth bits in "part". */
2651 if (--count == partsCount)
2652 part = 0; /* An imaginary higher zero part. */
2653 else
2654 part = significand[count] << shift;
2655
2656 if (count && shift)
2657 part |= significand[count - 1] >> (integerPartWidth - shift);
2658
2659 /* Convert as much of "part" to hexdigits as we can. */
2660 unsigned int curDigits = integerPartWidth / 4;
2661
2662 if (curDigits > outputDigits)
2663 curDigits = outputDigits;
2664 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2665 outputDigits -= curDigits;
2666 }
2667
2668 if (roundUp) {
2669 char *q = dst;
2670
2671 /* Note that hexDigitChars has a trailing '0'. */
2672 do {
2673 q--;
2674 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth978661d2007-10-06 00:24:48 +00002675 } while (*q == '0');
Evan Cheng99ebfa52009-10-27 21:35:42 +00002676 assert(q >= p);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002677 } else {
2678 /* Add trailing zeroes. */
2679 memset (dst, '0', outputDigits);
2680 dst += outputDigits;
2681 }
2682
2683 /* Move the most significant digit to before the point, and if there
2684 is something after the decimal point add it. This must come
2685 after rounding above. */
2686 p[-1] = p[0];
2687 if (dst -1 == p)
2688 dst--;
2689 else
2690 p[0] = '.';
2691
2692 /* Finally output the exponent. */
2693 *dst++ = upperCase ? 'P': 'p';
2694
Neil Booth92f7e8d2007-10-06 07:29:25 +00002695 return writeSignedDecimal (dst, exponent);
Neil Bootha30b0ee2007-10-03 22:26:02 +00002696}
2697
Dale Johannesen343e7702007-08-24 00:56:33 +00002698// For good performance it is desirable for different APFloats
2699// to produce different integers.
2700uint32_t
Neil Booth4f881702007-09-26 21:33:42 +00002701APFloat::getHashValue() const
2702{
Dale Johannesen343e7702007-08-24 00:56:33 +00002703 if (category==fcZero) return sign<<8 | semantics->precision ;
2704 else if (category==fcInfinity) return sign<<9 | semantics->precision;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002705 else if (category==fcNaN) return 1<<10 | semantics->precision;
Dale Johannesen343e7702007-08-24 00:56:33 +00002706 else {
2707 uint32_t hash = sign<<11 | semantics->precision | exponent<<12;
2708 const integerPart* p = significandParts();
2709 for (int i=partCount(); i>0; i--, p++)
Evan Cheng48e8c802008-05-02 21:15:08 +00002710 hash ^= ((uint32_t)*p) ^ (uint32_t)((*p)>>32);
Dale Johannesen343e7702007-08-24 00:56:33 +00002711 return hash;
2712 }
2713}
2714
2715// Conversion from APFloat to/from host float/double. It may eventually be
2716// possible to eliminate these and have everybody deal with APFloats, but that
2717// will take a while. This approach will not easily extend to long double.
Dale Johannesena72a5a02007-09-20 23:47:58 +00002718// Current implementation requires integerPartWidth==64, which is correct at
2719// the moment but could be made more general.
Dale Johannesen343e7702007-08-24 00:56:33 +00002720
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002721// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesena72a5a02007-09-20 23:47:58 +00002722// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002723
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002724APInt
Neil Booth4f881702007-09-26 21:33:42 +00002725APFloat::convertF80LongDoubleAPFloatToAPInt() const
2726{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002727 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002728 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002729
2730 uint64_t myexponent, mysignificand;
2731
2732 if (category==fcNormal) {
2733 myexponent = exponent+16383; //bias
Dale Johannesena72a5a02007-09-20 23:47:58 +00002734 mysignificand = significandParts()[0];
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002735 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2736 myexponent = 0; // denormal
2737 } else if (category==fcZero) {
2738 myexponent = 0;
2739 mysignificand = 0;
2740 } else if (category==fcInfinity) {
2741 myexponent = 0x7fff;
2742 mysignificand = 0x8000000000000000ULL;
Chris Lattnera11ef822007-10-06 06:13:42 +00002743 } else {
2744 assert(category == fcNaN && "Unknown category");
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002745 myexponent = 0x7fff;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002746 mysignificand = significandParts()[0];
Chris Lattnera11ef822007-10-06 06:13:42 +00002747 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002748
2749 uint64_t words[2];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002750 words[0] = mysignificand;
2751 words[1] = ((uint64_t)(sign & 1) << 15) |
2752 (myexponent & 0x7fffLL);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002753 return APInt(80, words);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002754}
2755
2756APInt
Dale Johannesena471c2e2007-10-11 18:07:22 +00002757APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2758{
Dan Gohmanb10abe12008-01-29 12:08:20 +00002759 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002760 assert(partCount()==2);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002761
2762 uint64_t myexponent, mysignificand, myexponent2, mysignificand2;
2763
2764 if (category==fcNormal) {
2765 myexponent = exponent + 1023; //bias
2766 myexponent2 = exponent2 + 1023;
2767 mysignificand = significandParts()[0];
2768 mysignificand2 = significandParts()[1];
2769 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2770 myexponent = 0; // denormal
2771 if (myexponent2==1 && !(mysignificand2 & 0x10000000000000LL))
2772 myexponent2 = 0; // denormal
2773 } else if (category==fcZero) {
2774 myexponent = 0;
2775 mysignificand = 0;
2776 myexponent2 = 0;
2777 mysignificand2 = 0;
2778 } else if (category==fcInfinity) {
2779 myexponent = 0x7ff;
2780 myexponent2 = 0;
2781 mysignificand = 0;
2782 mysignificand2 = 0;
2783 } else {
2784 assert(category == fcNaN && "Unknown category");
2785 myexponent = 0x7ff;
2786 mysignificand = significandParts()[0];
2787 myexponent2 = exponent2;
2788 mysignificand2 = significandParts()[1];
2789 }
2790
2791 uint64_t words[2];
Evan Cheng48e8c802008-05-02 21:15:08 +00002792 words[0] = ((uint64_t)(sign & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002793 ((myexponent & 0x7ff) << 52) |
2794 (mysignificand & 0xfffffffffffffLL);
Evan Cheng48e8c802008-05-02 21:15:08 +00002795 words[1] = ((uint64_t)(sign2 & 1) << 63) |
Dale Johannesena471c2e2007-10-11 18:07:22 +00002796 ((myexponent2 & 0x7ff) << 52) |
2797 (mysignificand2 & 0xfffffffffffffLL);
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002798 return APInt(128, words);
Dale Johannesena471c2e2007-10-11 18:07:22 +00002799}
2800
2801APInt
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002802APFloat::convertQuadrupleAPFloatToAPInt() const
2803{
2804 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002805 assert(partCount()==2);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002806
2807 uint64_t myexponent, mysignificand, mysignificand2;
2808
2809 if (category==fcNormal) {
2810 myexponent = exponent+16383; //bias
2811 mysignificand = significandParts()[0];
2812 mysignificand2 = significandParts()[1];
2813 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2814 myexponent = 0; // denormal
2815 } else if (category==fcZero) {
2816 myexponent = 0;
2817 mysignificand = mysignificand2 = 0;
2818 } else if (category==fcInfinity) {
2819 myexponent = 0x7fff;
2820 mysignificand = mysignificand2 = 0;
2821 } else {
2822 assert(category == fcNaN && "Unknown category!");
2823 myexponent = 0x7fff;
2824 mysignificand = significandParts()[0];
2825 mysignificand2 = significandParts()[1];
2826 }
2827
2828 uint64_t words[2];
2829 words[0] = mysignificand;
2830 words[1] = ((uint64_t)(sign & 1) << 63) |
2831 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov4755e992009-08-21 23:09:47 +00002832 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002833
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00002834 return APInt(128, words);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002835}
2836
2837APInt
Neil Booth4f881702007-09-26 21:33:42 +00002838APFloat::convertDoubleAPFloatToAPInt() const
2839{
Dan Gohmancb648f92007-09-14 20:08:19 +00002840 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002841 assert(partCount()==1);
Dale Johannesen343e7702007-08-24 00:56:33 +00002842
Dale Johanneseneaf08942007-08-31 04:03:46 +00002843 uint64_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002844
2845 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002846 myexponent = exponent+1023; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002847 mysignificand = *significandParts();
2848 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2849 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002850 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002851 myexponent = 0;
2852 mysignificand = 0;
2853 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002854 myexponent = 0x7ff;
2855 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002856 } else {
2857 assert(category == fcNaN && "Unknown category!");
Dale Johannesen343e7702007-08-24 00:56:33 +00002858 myexponent = 0x7ff;
Dale Johanneseneaf08942007-08-31 04:03:46 +00002859 mysignificand = *significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002860 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002861
Evan Cheng48e8c802008-05-02 21:15:08 +00002862 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattnera11ef822007-10-06 06:13:42 +00002863 ((myexponent & 0x7ff) << 52) |
2864 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesen343e7702007-08-24 00:56:33 +00002865}
2866
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002867APInt
Neil Booth4f881702007-09-26 21:33:42 +00002868APFloat::convertFloatAPFloatToAPInt() const
2869{
Dan Gohmancb648f92007-09-14 20:08:19 +00002870 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002871 assert(partCount()==1);
Neil Booth4f881702007-09-26 21:33:42 +00002872
Dale Johanneseneaf08942007-08-31 04:03:46 +00002873 uint32_t myexponent, mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00002874
2875 if (category==fcNormal) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002876 myexponent = exponent+127; //bias
Evan Cheng48e8c802008-05-02 21:15:08 +00002877 mysignificand = (uint32_t)*significandParts();
Dale Johannesend0763b92007-11-17 01:02:27 +00002878 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002879 myexponent = 0; // denormal
Dale Johannesen343e7702007-08-24 00:56:33 +00002880 } else if (category==fcZero) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002881 myexponent = 0;
2882 mysignificand = 0;
2883 } else if (category==fcInfinity) {
Dale Johannesen343e7702007-08-24 00:56:33 +00002884 myexponent = 0xff;
2885 mysignificand = 0;
Chris Lattnera11ef822007-10-06 06:13:42 +00002886 } else {
2887 assert(category == fcNaN && "Unknown category!");
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00002888 myexponent = 0xff;
Evan Cheng48e8c802008-05-02 21:15:08 +00002889 mysignificand = (uint32_t)*significandParts();
Chris Lattnera11ef822007-10-06 06:13:42 +00002890 }
Dale Johannesen343e7702007-08-24 00:56:33 +00002891
Chris Lattnera11ef822007-10-06 06:13:42 +00002892 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2893 (mysignificand & 0x7fffff)));
Dale Johannesen343e7702007-08-24 00:56:33 +00002894}
2895
Chris Lattnercc4287a2009-10-16 02:13:51 +00002896APInt
2897APFloat::convertHalfAPFloatToAPInt() const
2898{
2899 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng99ebfa52009-10-27 21:35:42 +00002900 assert(partCount()==1);
Chris Lattnercc4287a2009-10-16 02:13:51 +00002901
2902 uint32_t myexponent, mysignificand;
2903
2904 if (category==fcNormal) {
2905 myexponent = exponent+15; //bias
2906 mysignificand = (uint32_t)*significandParts();
2907 if (myexponent == 1 && !(mysignificand & 0x400))
2908 myexponent = 0; // denormal
2909 } else if (category==fcZero) {
2910 myexponent = 0;
2911 mysignificand = 0;
2912 } else if (category==fcInfinity) {
Dale Johannesena223aed2009-10-23 04:02:51 +00002913 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002914 mysignificand = 0;
2915 } else {
2916 assert(category == fcNaN && "Unknown category!");
Dale Johannesena223aed2009-10-23 04:02:51 +00002917 myexponent = 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00002918 mysignificand = (uint32_t)*significandParts();
2919 }
2920
2921 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2922 (mysignificand & 0x3ff)));
2923}
2924
Dale Johannesena471c2e2007-10-11 18:07:22 +00002925// This function creates an APInt that is just a bit map of the floating
2926// point constant as it would appear in memory. It is not a conversion,
2927// and treating the result as a normal integer is unlikely to be useful.
2928
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002929APInt
Dale Johannesen7111b022008-10-09 18:53:47 +00002930APFloat::bitcastToAPInt() const
Neil Booth4f881702007-09-26 21:33:42 +00002931{
Chris Lattnercc4287a2009-10-16 02:13:51 +00002932 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
2933 return convertHalfAPFloatToAPInt();
2934
Dan Gohmanb10abe12008-01-29 12:08:20 +00002935 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002936 return convertFloatAPFloatToAPInt();
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002937
Dan Gohmanb10abe12008-01-29 12:08:20 +00002938 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002939 return convertDoubleAPFloatToAPInt();
Neil Booth4f881702007-09-26 21:33:42 +00002940
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00002941 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
2942 return convertQuadrupleAPFloatToAPInt();
2943
Dan Gohmanb10abe12008-01-29 12:08:20 +00002944 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesena471c2e2007-10-11 18:07:22 +00002945 return convertPPCDoubleDoubleAPFloatToAPInt();
2946
Dan Gohmanb10abe12008-01-29 12:08:20 +00002947 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattnera11ef822007-10-06 06:13:42 +00002948 "unknown format!");
2949 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002950}
2951
Neil Booth4f881702007-09-26 21:33:42 +00002952float
2953APFloat::convertToFloat() const
2954{
Chris Lattnerad785002009-09-24 21:44:20 +00002955 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
2956 "Float semantics are not IEEEsingle");
Dale Johannesen7111b022008-10-09 18:53:47 +00002957 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002958 return api.bitsToFloat();
2959}
2960
Neil Booth4f881702007-09-26 21:33:42 +00002961double
2962APFloat::convertToDouble() const
2963{
Chris Lattnerad785002009-09-24 21:44:20 +00002964 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
2965 "Float semantics are not IEEEdouble");
Dale Johannesen7111b022008-10-09 18:53:47 +00002966 APInt api = bitcastToAPInt();
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002967 return api.bitsToDouble();
2968}
2969
Dale Johannesend3d8ce32008-10-06 18:22:29 +00002970/// Integer bit is explicit in this format. Intel hardware (387 and later)
2971/// does not support these bit patterns:
2972/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
2973/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
2974/// exponent = 0, integer bit 1 ("pseudodenormal")
2975/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
2976/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002977void
Neil Booth4f881702007-09-26 21:33:42 +00002978APFloat::initFromF80LongDoubleAPInt(const APInt &api)
2979{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002980 assert(api.getBitWidth()==80);
2981 uint64_t i1 = api.getRawData()[0];
2982 uint64_t i2 = api.getRawData()[1];
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002983 uint64_t myexponent = (i2 & 0x7fff);
2984 uint64_t mysignificand = i1;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002985
2986 initialize(&APFloat::x87DoubleExtended);
Dale Johannesena72a5a02007-09-20 23:47:58 +00002987 assert(partCount()==2);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002988
Dale Johannesen1b25cb22009-03-23 21:16:53 +00002989 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00002990 if (myexponent==0 && mysignificand==0) {
2991 // exponent, significand meaningless
2992 category = fcZero;
2993 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
2994 // exponent, significand meaningless
2995 category = fcInfinity;
2996 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
2997 // exponent meaningless
2998 category = fcNaN;
Dale Johannesena72a5a02007-09-20 23:47:58 +00002999 significandParts()[0] = mysignificand;
3000 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003001 } else {
3002 category = fcNormal;
3003 exponent = myexponent - 16383;
Dale Johannesena72a5a02007-09-20 23:47:58 +00003004 significandParts()[0] = mysignificand;
3005 significandParts()[1] = 0;
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003006 if (myexponent==0) // denormal
3007 exponent = -16382;
Neil Booth4f881702007-09-26 21:33:42 +00003008 }
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003009}
3010
3011void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003012APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3013{
3014 assert(api.getBitWidth()==128);
3015 uint64_t i1 = api.getRawData()[0];
3016 uint64_t i2 = api.getRawData()[1];
3017 uint64_t myexponent = (i1 >> 52) & 0x7ff;
3018 uint64_t mysignificand = i1 & 0xfffffffffffffLL;
3019 uint64_t myexponent2 = (i2 >> 52) & 0x7ff;
3020 uint64_t mysignificand2 = i2 & 0xfffffffffffffLL;
3021
3022 initialize(&APFloat::PPCDoubleDouble);
3023 assert(partCount()==2);
3024
Evan Cheng48e8c802008-05-02 21:15:08 +00003025 sign = static_cast<unsigned int>(i1>>63);
3026 sign2 = static_cast<unsigned int>(i2>>63);
Dale Johannesena471c2e2007-10-11 18:07:22 +00003027 if (myexponent==0 && mysignificand==0) {
3028 // exponent, significand meaningless
3029 // exponent2 and significand2 are required to be 0; we don't check
3030 category = fcZero;
3031 } else if (myexponent==0x7ff && mysignificand==0) {
3032 // exponent, significand meaningless
3033 // exponent2 and significand2 are required to be 0; we don't check
3034 category = fcInfinity;
3035 } else if (myexponent==0x7ff && mysignificand!=0) {
Dan Gohman16e02092010-03-24 19:38:02 +00003036 // exponent meaningless. So is the whole second word, but keep it
Dale Johannesena471c2e2007-10-11 18:07:22 +00003037 // for determinism.
3038 category = fcNaN;
3039 exponent2 = myexponent2;
3040 significandParts()[0] = mysignificand;
3041 significandParts()[1] = mysignificand2;
3042 } else {
3043 category = fcNormal;
3044 // Note there is no category2; the second word is treated as if it is
3045 // fcNormal, although it might be something else considered by itself.
3046 exponent = myexponent - 1023;
3047 exponent2 = myexponent2 - 1023;
3048 significandParts()[0] = mysignificand;
3049 significandParts()[1] = mysignificand2;
3050 if (myexponent==0) // denormal
3051 exponent = -1022;
3052 else
3053 significandParts()[0] |= 0x10000000000000LL; // integer bit
Dan Gohman16e02092010-03-24 19:38:02 +00003054 if (myexponent2==0)
Dale Johannesena471c2e2007-10-11 18:07:22 +00003055 exponent2 = -1022;
3056 else
3057 significandParts()[1] |= 0x10000000000000LL; // integer bit
3058 }
3059}
3060
3061void
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003062APFloat::initFromQuadrupleAPInt(const APInt &api)
3063{
3064 assert(api.getBitWidth()==128);
3065 uint64_t i1 = api.getRawData()[0];
3066 uint64_t i2 = api.getRawData()[1];
3067 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3068 uint64_t mysignificand = i1;
3069 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3070
3071 initialize(&APFloat::IEEEquad);
3072 assert(partCount()==2);
3073
3074 sign = static_cast<unsigned int>(i2>>63);
3075 if (myexponent==0 &&
3076 (mysignificand==0 && mysignificand2==0)) {
3077 // exponent, significand meaningless
3078 category = fcZero;
3079 } else if (myexponent==0x7fff &&
3080 (mysignificand==0 && mysignificand2==0)) {
3081 // exponent, significand meaningless
3082 category = fcInfinity;
3083 } else if (myexponent==0x7fff &&
3084 (mysignificand!=0 || mysignificand2 !=0)) {
3085 // exponent meaningless
3086 category = fcNaN;
3087 significandParts()[0] = mysignificand;
3088 significandParts()[1] = mysignificand2;
3089 } else {
3090 category = fcNormal;
3091 exponent = myexponent - 16383;
3092 significandParts()[0] = mysignificand;
3093 significandParts()[1] = mysignificand2;
3094 if (myexponent==0) // denormal
3095 exponent = -16382;
3096 else
3097 significandParts()[1] |= 0x1000000000000LL; // integer bit
3098 }
3099}
3100
3101void
Neil Booth4f881702007-09-26 21:33:42 +00003102APFloat::initFromDoubleAPInt(const APInt &api)
3103{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003104 assert(api.getBitWidth()==64);
3105 uint64_t i = *api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003106 uint64_t myexponent = (i >> 52) & 0x7ff;
3107 uint64_t mysignificand = i & 0xfffffffffffffLL;
3108
Dale Johannesen343e7702007-08-24 00:56:33 +00003109 initialize(&APFloat::IEEEdouble);
Dale Johannesen343e7702007-08-24 00:56:33 +00003110 assert(partCount()==1);
3111
Evan Cheng48e8c802008-05-02 21:15:08 +00003112 sign = static_cast<unsigned int>(i>>63);
Dale Johannesen343e7702007-08-24 00:56:33 +00003113 if (myexponent==0 && mysignificand==0) {
3114 // exponent, significand meaningless
3115 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003116 } else if (myexponent==0x7ff && mysignificand==0) {
3117 // exponent, significand meaningless
3118 category = fcInfinity;
Dale Johanneseneaf08942007-08-31 04:03:46 +00003119 } else if (myexponent==0x7ff && mysignificand!=0) {
3120 // exponent meaningless
3121 category = fcNaN;
3122 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003123 } else {
Dale Johannesen343e7702007-08-24 00:56:33 +00003124 category = fcNormal;
3125 exponent = myexponent - 1023;
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003126 *significandParts() = mysignificand;
3127 if (myexponent==0) // denormal
3128 exponent = -1022;
3129 else
3130 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth4f881702007-09-26 21:33:42 +00003131 }
Dale Johannesen343e7702007-08-24 00:56:33 +00003132}
3133
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003134void
Neil Booth4f881702007-09-26 21:33:42 +00003135APFloat::initFromFloatAPInt(const APInt & api)
3136{
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003137 assert(api.getBitWidth()==32);
3138 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesend3b51fd2007-08-24 05:08:11 +00003139 uint32_t myexponent = (i >> 23) & 0xff;
3140 uint32_t mysignificand = i & 0x7fffff;
3141
Dale Johannesen343e7702007-08-24 00:56:33 +00003142 initialize(&APFloat::IEEEsingle);
Dale Johannesen343e7702007-08-24 00:56:33 +00003143 assert(partCount()==1);
3144
Dale Johanneseneaf08942007-08-31 04:03:46 +00003145 sign = i >> 31;
Dale Johannesen343e7702007-08-24 00:56:33 +00003146 if (myexponent==0 && mysignificand==0) {
3147 // exponent, significand meaningless
3148 category = fcZero;
Dale Johannesen343e7702007-08-24 00:56:33 +00003149 } else if (myexponent==0xff && mysignificand==0) {
3150 // exponent, significand meaningless
3151 category = fcInfinity;
Dale Johannesen902ff942007-09-25 17:25:00 +00003152 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesen343e7702007-08-24 00:56:33 +00003153 // sign, exponent, significand meaningless
Dale Johanneseneaf08942007-08-31 04:03:46 +00003154 category = fcNaN;
3155 *significandParts() = mysignificand;
Dale Johannesen343e7702007-08-24 00:56:33 +00003156 } else {
3157 category = fcNormal;
Dale Johannesen343e7702007-08-24 00:56:33 +00003158 exponent = myexponent - 127; //bias
Dale Johannesen58c2e4c2007-09-05 20:39:49 +00003159 *significandParts() = mysignificand;
3160 if (myexponent==0) // denormal
3161 exponent = -126;
3162 else
3163 *significandParts() |= 0x800000; // integer bit
Dale Johannesen343e7702007-08-24 00:56:33 +00003164 }
3165}
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003166
Chris Lattnercc4287a2009-10-16 02:13:51 +00003167void
3168APFloat::initFromHalfAPInt(const APInt & api)
3169{
3170 assert(api.getBitWidth()==16);
3171 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesena223aed2009-10-23 04:02:51 +00003172 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattnercc4287a2009-10-16 02:13:51 +00003173 uint32_t mysignificand = i & 0x3ff;
3174
3175 initialize(&APFloat::IEEEhalf);
3176 assert(partCount()==1);
3177
3178 sign = i >> 15;
3179 if (myexponent==0 && mysignificand==0) {
3180 // exponent, significand meaningless
3181 category = fcZero;
3182 } else if (myexponent==0x1f && mysignificand==0) {
3183 // exponent, significand meaningless
3184 category = fcInfinity;
3185 } else if (myexponent==0x1f && mysignificand!=0) {
3186 // sign, exponent, significand meaningless
3187 category = fcNaN;
3188 *significandParts() = mysignificand;
3189 } else {
3190 category = fcNormal;
3191 exponent = myexponent - 15; //bias
3192 *significandParts() = mysignificand;
3193 if (myexponent==0) // denormal
3194 exponent = -14;
3195 else
3196 *significandParts() |= 0x400; // integer bit
3197 }
3198}
3199
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003200/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesena471c2e2007-10-11 18:07:22 +00003201/// we infer the floating point type from the size of the APInt. The
3202/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3203/// when the size is anything else).
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003204void
Dale Johannesena471c2e2007-10-11 18:07:22 +00003205APFloat::initFromAPInt(const APInt& api, bool isIEEE)
Neil Booth4f881702007-09-26 21:33:42 +00003206{
Chris Lattnercc4287a2009-10-16 02:13:51 +00003207 if (api.getBitWidth() == 16)
3208 return initFromHalfAPInt(api);
3209 else if (api.getBitWidth() == 32)
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003210 return initFromFloatAPInt(api);
3211 else if (api.getBitWidth()==64)
3212 return initFromDoubleAPInt(api);
3213 else if (api.getBitWidth()==80)
3214 return initFromF80LongDoubleAPInt(api);
Anton Korobeynikov7e844f12009-08-21 22:10:30 +00003215 else if (api.getBitWidth()==128)
3216 return (isIEEE ?
3217 initFromQuadrupleAPInt(api) : initFromPPCDoubleDoubleAPInt(api));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003218 else
Torok Edwinc23197a2009-07-14 16:55:14 +00003219 llvm_unreachable(0);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003220}
3221
Nadav Rotem093399c2011-02-17 21:22:27 +00003222APFloat
3223APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3224{
3225 return APFloat(APInt::getAllOnesValue(BitWidth), isIEEE);
3226}
3227
John McCall00e65de2009-12-24 08:56:26 +00003228APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3229 APFloat Val(Sem, fcNormal, Negative);
3230
3231 // We want (in interchange format):
3232 // sign = {Negative}
3233 // exponent = 1..10
3234 // significand = 1..1
3235
3236 Val.exponent = Sem.maxExponent; // unbiased
3237
3238 // 1-initialize all bits....
3239 Val.zeroSignificand();
3240 integerPart *significand = Val.significandParts();
3241 unsigned N = partCountForBits(Sem.precision);
3242 for (unsigned i = 0; i != N; ++i)
3243 significand[i] = ~((integerPart) 0);
3244
3245 // ...and then clear the top bits for internal consistency.
Eli Friedman7247a5f2011-10-12 21:51:36 +00003246 if (Sem.precision % integerPartWidth != 0)
3247 significand[N-1] &=
3248 (((integerPart) 1) << (Sem.precision % integerPartWidth)) - 1;
John McCall00e65de2009-12-24 08:56:26 +00003249
3250 return Val;
3251}
3252
3253APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3254 APFloat Val(Sem, fcNormal, Negative);
3255
3256 // We want (in interchange format):
3257 // sign = {Negative}
3258 // exponent = 0..0
3259 // significand = 0..01
3260
3261 Val.exponent = Sem.minExponent; // unbiased
3262 Val.zeroSignificand();
3263 Val.significandParts()[0] = 1;
3264 return Val;
3265}
3266
3267APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
3268 APFloat Val(Sem, fcNormal, Negative);
3269
3270 // We want (in interchange format):
3271 // sign = {Negative}
3272 // exponent = 0..0
3273 // significand = 10..0
3274
3275 Val.exponent = Sem.minExponent;
3276 Val.zeroSignificand();
Dan Gohman16e02092010-03-24 19:38:02 +00003277 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
3278 (((integerPart) 1) << ((Sem.precision % integerPartWidth) - 1));
John McCall00e65de2009-12-24 08:56:26 +00003279
3280 return Val;
3281}
3282
Bill Wendlingf09a8b52011-03-18 09:09:44 +00003283APFloat::APFloat(const APInt& api, bool isIEEE) : exponent2(0), sign2(0) {
Dale Johannesena471c2e2007-10-11 18:07:22 +00003284 initFromAPInt(api, isIEEE);
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003285}
3286
Bill Wendlingf09a8b52011-03-18 09:09:44 +00003287APFloat::APFloat(float f) : exponent2(0), sign2(0) {
Jay Foade4d19c92010-11-28 21:04:48 +00003288 initFromAPInt(APInt::floatToBits(f));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003289}
3290
Bill Wendlingf09a8b52011-03-18 09:09:44 +00003291APFloat::APFloat(double d) : exponent2(0), sign2(0) {
Jay Foade4d19c92010-11-28 21:04:48 +00003292 initFromAPInt(APInt::doubleToBits(d));
Dale Johannesen3f6eb742007-09-11 18:32:33 +00003293}
John McCall00e65de2009-12-24 08:56:26 +00003294
3295namespace {
3296 static void append(SmallVectorImpl<char> &Buffer,
3297 unsigned N, const char *Str) {
3298 unsigned Start = Buffer.size();
3299 Buffer.set_size(Start + N);
3300 memcpy(&Buffer[Start], Str, N);
3301 }
3302
3303 template <unsigned N>
3304 void append(SmallVectorImpl<char> &Buffer, const char (&Str)[N]) {
3305 append(Buffer, N, Str);
3306 }
3307
John McCall003a09c2009-12-24 12:16:56 +00003308 /// Removes data from the given significand until it is no more
3309 /// precise than is required for the desired precision.
3310 void AdjustToPrecision(APInt &significand,
3311 int &exp, unsigned FormatPrecision) {
3312 unsigned bits = significand.getActiveBits();
3313
3314 // 196/59 is a very slight overestimate of lg_2(10).
3315 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3316
3317 if (bits <= bitsRequired) return;
3318
3319 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3320 if (!tensRemovable) return;
3321
3322 exp += tensRemovable;
3323
3324 APInt divisor(significand.getBitWidth(), 1);
3325 APInt powten(significand.getBitWidth(), 10);
3326 while (true) {
3327 if (tensRemovable & 1)
3328 divisor *= powten;
3329 tensRemovable >>= 1;
3330 if (!tensRemovable) break;
3331 powten *= powten;
3332 }
3333
3334 significand = significand.udiv(divisor);
3335
3336 // Truncate the significand down to its active bit count, but
3337 // don't try to drop below 32.
John McCall6a09aff2009-12-24 23:18:09 +00003338 unsigned newPrecision = std::max(32U, significand.getActiveBits());
Jay Foad40f8f622010-12-07 08:25:19 +00003339 significand = significand.trunc(newPrecision);
John McCall003a09c2009-12-24 12:16:56 +00003340 }
3341
3342
John McCall00e65de2009-12-24 08:56:26 +00003343 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3344 int &exp, unsigned FormatPrecision) {
3345 unsigned N = buffer.size();
3346 if (N <= FormatPrecision) return;
3347
3348 // The most significant figures are the last ones in the buffer.
3349 unsigned FirstSignificant = N - FormatPrecision;
3350
3351 // Round.
3352 // FIXME: this probably shouldn't use 'round half up'.
3353
3354 // Rounding down is just a truncation, except we also want to drop
3355 // trailing zeros from the new result.
3356 if (buffer[FirstSignificant - 1] < '5') {
3357 while (buffer[FirstSignificant] == '0')
3358 FirstSignificant++;
3359
3360 exp += FirstSignificant;
3361 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3362 return;
3363 }
3364
3365 // Rounding up requires a decimal add-with-carry. If we continue
3366 // the carry, the newly-introduced zeros will just be truncated.
3367 for (unsigned I = FirstSignificant; I != N; ++I) {
3368 if (buffer[I] == '9') {
3369 FirstSignificant++;
3370 } else {
3371 buffer[I]++;
3372 break;
3373 }
3374 }
3375
3376 // If we carried through, we have exactly one digit of precision.
3377 if (FirstSignificant == N) {
3378 exp += FirstSignificant;
3379 buffer.clear();
3380 buffer.push_back('1');
3381 return;
3382 }
3383
3384 exp += FirstSignificant;
3385 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3386 }
3387}
3388
3389void APFloat::toString(SmallVectorImpl<char> &Str,
3390 unsigned FormatPrecision,
Chris Lattner0ddda3b2010-03-06 19:20:13 +00003391 unsigned FormatMaxPadding) const {
John McCall00e65de2009-12-24 08:56:26 +00003392 switch (category) {
3393 case fcInfinity:
3394 if (isNegative())
3395 return append(Str, "-Inf");
3396 else
3397 return append(Str, "+Inf");
3398
3399 case fcNaN: return append(Str, "NaN");
3400
3401 case fcZero:
3402 if (isNegative())
3403 Str.push_back('-');
3404
3405 if (!FormatMaxPadding)
3406 append(Str, "0.0E+0");
3407 else
3408 Str.push_back('0');
3409 return;
3410
3411 case fcNormal:
3412 break;
3413 }
3414
3415 if (isNegative())
3416 Str.push_back('-');
3417
3418 // Decompose the number into an APInt and an exponent.
3419 int exp = exponent - ((int) semantics->precision - 1);
3420 APInt significand(semantics->precision,
Jeffrey Yasskin3ba292d2011-07-18 21:45:40 +00003421 makeArrayRef(significandParts(),
3422 partCountForBits(semantics->precision)));
John McCall00e65de2009-12-24 08:56:26 +00003423
John McCall6a09aff2009-12-24 23:18:09 +00003424 // Set FormatPrecision if zero. We want to do this before we
3425 // truncate trailing zeros, as those are part of the precision.
3426 if (!FormatPrecision) {
3427 // It's an interesting question whether to use the nominal
3428 // precision or the active precision here for denormals.
3429
3430 // FormatPrecision = ceil(significandBits / lg_2(10))
3431 FormatPrecision = (semantics->precision * 59 + 195) / 196;
3432 }
3433
John McCall00e65de2009-12-24 08:56:26 +00003434 // Ignore trailing binary zeros.
3435 int trailingZeros = significand.countTrailingZeros();
3436 exp += trailingZeros;
3437 significand = significand.lshr(trailingZeros);
3438
3439 // Change the exponent from 2^e to 10^e.
3440 if (exp == 0) {
3441 // Nothing to do.
3442 } else if (exp > 0) {
3443 // Just shift left.
Jay Foad40f8f622010-12-07 08:25:19 +00003444 significand = significand.zext(semantics->precision + exp);
John McCall00e65de2009-12-24 08:56:26 +00003445 significand <<= exp;
3446 exp = 0;
3447 } else { /* exp < 0 */
3448 int texp = -exp;
3449
3450 // We transform this using the identity:
3451 // (N)(2^-e) == (N)(5^e)(10^-e)
3452 // This means we have to multiply N (the significand) by 5^e.
3453 // To avoid overflow, we have to operate on numbers large
3454 // enough to store N * 5^e:
3455 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCall6a09aff2009-12-24 23:18:09 +00003456 // <= semantics->precision + e * 137 / 59
3457 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohman16e02092010-03-24 19:38:02 +00003458
Eli Friedman9eb6b4d2011-10-07 23:40:49 +00003459 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall00e65de2009-12-24 08:56:26 +00003460
3461 // Multiply significand by 5^e.
3462 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad40f8f622010-12-07 08:25:19 +00003463 significand = significand.zext(precision);
John McCall00e65de2009-12-24 08:56:26 +00003464 APInt five_to_the_i(precision, 5);
3465 while (true) {
3466 if (texp & 1) significand *= five_to_the_i;
Dan Gohman16e02092010-03-24 19:38:02 +00003467
John McCall00e65de2009-12-24 08:56:26 +00003468 texp >>= 1;
3469 if (!texp) break;
3470 five_to_the_i *= five_to_the_i;
3471 }
3472 }
3473
John McCall003a09c2009-12-24 12:16:56 +00003474 AdjustToPrecision(significand, exp, FormatPrecision);
3475
John McCall00e65de2009-12-24 08:56:26 +00003476 llvm::SmallVector<char, 256> buffer;
3477
3478 // Fill the buffer.
3479 unsigned precision = significand.getBitWidth();
3480 APInt ten(precision, 10);
3481 APInt digit(precision, 0);
3482
3483 bool inTrail = true;
3484 while (significand != 0) {
3485 // digit <- significand % 10
3486 // significand <- significand / 10
3487 APInt::udivrem(significand, ten, significand, digit);
3488
3489 unsigned d = digit.getZExtValue();
3490
3491 // Drop trailing zeros.
3492 if (inTrail && !d) exp++;
3493 else {
3494 buffer.push_back((char) ('0' + d));
3495 inTrail = false;
3496 }
3497 }
3498
3499 assert(!buffer.empty() && "no characters in buffer!");
3500
3501 // Drop down to FormatPrecision.
3502 // TODO: don't do more precise calculations above than are required.
3503 AdjustToPrecision(buffer, exp, FormatPrecision);
3504
3505 unsigned NDigits = buffer.size();
3506
John McCall6a09aff2009-12-24 23:18:09 +00003507 // Check whether we should use scientific notation.
John McCall00e65de2009-12-24 08:56:26 +00003508 bool FormatScientific;
3509 if (!FormatMaxPadding)
3510 FormatScientific = true;
3511 else {
John McCall00e65de2009-12-24 08:56:26 +00003512 if (exp >= 0) {
John McCall6a09aff2009-12-24 23:18:09 +00003513 // 765e3 --> 765000
3514 // ^^^
3515 // But we shouldn't make the number look more precise than it is.
3516 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3517 NDigits + (unsigned) exp > FormatPrecision);
John McCall00e65de2009-12-24 08:56:26 +00003518 } else {
John McCall6a09aff2009-12-24 23:18:09 +00003519 // Power of the most significant digit.
3520 int MSD = exp + (int) (NDigits - 1);
3521 if (MSD >= 0) {
John McCall00e65de2009-12-24 08:56:26 +00003522 // 765e-2 == 7.65
John McCall6a09aff2009-12-24 23:18:09 +00003523 FormatScientific = false;
John McCall00e65de2009-12-24 08:56:26 +00003524 } else {
3525 // 765e-5 == 0.00765
3526 // ^ ^^
John McCall6a09aff2009-12-24 23:18:09 +00003527 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall00e65de2009-12-24 08:56:26 +00003528 }
3529 }
John McCall00e65de2009-12-24 08:56:26 +00003530 }
3531
3532 // Scientific formatting is pretty straightforward.
3533 if (FormatScientific) {
3534 exp += (NDigits - 1);
3535
3536 Str.push_back(buffer[NDigits-1]);
3537 Str.push_back('.');
3538 if (NDigits == 1)
3539 Str.push_back('0');
3540 else
3541 for (unsigned I = 1; I != NDigits; ++I)
3542 Str.push_back(buffer[NDigits-1-I]);
3543 Str.push_back('E');
3544
3545 Str.push_back(exp >= 0 ? '+' : '-');
3546 if (exp < 0) exp = -exp;
3547 SmallVector<char, 6> expbuf;
3548 do {
3549 expbuf.push_back((char) ('0' + (exp % 10)));
3550 exp /= 10;
3551 } while (exp);
3552 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3553 Str.push_back(expbuf[E-1-I]);
3554 return;
3555 }
3556
3557 // Non-scientific, positive exponents.
3558 if (exp >= 0) {
3559 for (unsigned I = 0; I != NDigits; ++I)
3560 Str.push_back(buffer[NDigits-1-I]);
3561 for (unsigned I = 0; I != (unsigned) exp; ++I)
3562 Str.push_back('0');
3563 return;
3564 }
3565
3566 // Non-scientific, negative exponents.
3567
3568 // The number of digits to the left of the decimal point.
3569 int NWholeDigits = exp + (int) NDigits;
3570
3571 unsigned I = 0;
3572 if (NWholeDigits > 0) {
3573 for (; I != (unsigned) NWholeDigits; ++I)
3574 Str.push_back(buffer[NDigits-I-1]);
3575 Str.push_back('.');
3576 } else {
3577 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3578
3579 Str.push_back('0');
3580 Str.push_back('.');
3581 for (unsigned Z = 1; Z != NZeros; ++Z)
3582 Str.push_back('0');
3583 }
3584
3585 for (; I != NDigits; ++I)
3586 Str.push_back(buffer[NDigits-I-1]);
3587}
Benjamin Kramer27460002011-03-30 15:42:27 +00003588
3589bool APFloat::getExactInverse(APFloat *inv) const {
Chris Lattner7a2bdde2011-04-15 05:18:47 +00003590 // We can only guarantee the existence of an exact inverse for IEEE floats.
Benjamin Kramer27460002011-03-30 15:42:27 +00003591 if (semantics != &IEEEhalf && semantics != &IEEEsingle &&
3592 semantics != &IEEEdouble && semantics != &IEEEquad)
3593 return false;
3594
3595 // Special floats and denormals have no exact inverse.
3596 if (category != fcNormal)
3597 return false;
3598
3599 // Check that the number is a power of two by making sure that only the
3600 // integer bit is set in the significand.
3601 if (significandLSB() != semantics->precision - 1)
3602 return false;
3603
3604 // Get the inverse.
3605 APFloat reciprocal(*semantics, 1ULL);
3606 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3607 return false;
3608
Benjamin Kramer83985122011-03-30 17:02:54 +00003609 // Avoid multiplication with a denormal, it is not safe on all platforms and
3610 // may be slower than a normal division.
3611 if (reciprocal.significandMSB() + 1 < reciprocal.semantics->precision)
3612 return false;
3613
3614 assert(reciprocal.category == fcNormal &&
3615 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3616
Benjamin Kramer27460002011-03-30 15:42:27 +00003617 if (inv)
3618 *inv = reciprocal;
3619
3620 return true;
3621}