blob: f9370b85234fd22c357afd5fdbd5b0c4c6795682 [file] [log] [blame]
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001//===-- APFloat.cpp - Implement APFloat class -----------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a class to represent arbitrary precision floating
11// point values and provide a variety of arithmetic operations on them.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattnere5256752007-12-08 19:00:03 +000015#include "llvm/ADT/APFloat.h"
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +000016#include "llvm/ADT/APSInt.h"
Mehdi Amini47b292d2016-04-16 07:51:28 +000017#include "llvm/ADT/ArrayRef.h"
Ted Kremenek6f30a072008-02-11 17:24:50 +000018#include "llvm/ADT/FoldingSet.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000019#include "llvm/ADT/Hashing.h"
Jordan Rosee1f76582013-01-18 21:45:30 +000020#include "llvm/ADT/StringExtras.h"
Chandler Carruth71bd7d12012-03-04 12:02:57 +000021#include "llvm/ADT/StringRef.h"
Torok Edwin56d06592009-07-11 20:10:48 +000022#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000023#include "llvm/Support/MathExtras.h"
Chris Lattner17f71652008-08-17 07:19:36 +000024#include <cstring>
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000025#include <limits.h>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000026
27using namespace llvm;
28
Michael Gottesman9b877e12013-06-24 09:57:57 +000029/// A macro used to combine two fcCategory enums into one key which can be used
30/// in a switch statement to classify how the interaction of two APFloat's
31/// categories affects an operation.
32///
33/// TODO: If clang source code is ever allowed to use constexpr in its own
34/// codebase, change this into a static inline function.
35#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000036
Neil Booth8f1946f2007-10-03 22:26:02 +000037/* Assumed in hexadecimal significand parsing, and conversion to
38 hexadecimal strings. */
Benjamin Kramer7000ca32014-10-12 17:56:40 +000039static_assert(integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000040
41namespace llvm {
42
43 /* Represents floating point arithmetic semantics. */
44 struct fltSemantics {
45 /* The largest E such that 2^E is representable; this matches the
46 definition of IEEE 754. */
Michael Gottesman9dc98332013-06-24 04:06:23 +000047 APFloat::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000048
49 /* The smallest E such that 2^E is a normalized number; this
50 matches the definition of IEEE 754. */
Michael Gottesman9dc98332013-06-24 04:06:23 +000051 APFloat::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000052
53 /* Number of bits in the significand. This includes the integer
54 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000055 unsigned int precision;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000056
57 /* Number of bits actually used in the semantics. */
58 unsigned int sizeInBits;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000059 };
60
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000061 const fltSemantics APFloat::IEEEhalf = { 15, -14, 11, 16 };
62 const fltSemantics APFloat::IEEEsingle = { 127, -126, 24, 32 };
63 const fltSemantics APFloat::IEEEdouble = { 1023, -1022, 53, 64 };
64 const fltSemantics APFloat::IEEEquad = { 16383, -16382, 113, 128 };
65 const fltSemantics APFloat::x87DoubleExtended = { 16383, -16382, 64, 80 };
66 const fltSemantics APFloat::Bogus = { 0, 0, 0, 0 };
Dale Johannesen007aa372007-10-11 18:07:22 +000067
Ulrich Weigandd9f7e252012-10-29 18:09:01 +000068 /* The PowerPC format consists of two doubles. It does not map cleanly
69 onto the usual format above. It is approximated using twice the
70 mantissa bits. Note that for exponents near the double minimum,
71 we no longer can represent the full 106 mantissa bits, so those
72 will be treated as denormal numbers.
73
74 FIXME: While this approximation is equivalent to what GCC uses for
75 compile-time arithmetic on PPC double-double numbers, it is not able
76 to represent all possible values held by a PPC double-double number,
77 for example: (long double) 1.0 + (long double) 0x1p-106
78 Should this be replaced by a full emulation of PPC double-double? */
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000079 const fltSemantics APFloat::PPCDoubleDouble = { 1023, -1022 + 53, 53 + 53, 128 };
Neil Boothb93d90e2007-10-12 16:02:31 +000080
81 /* A tight upper bound on number of parts required to hold the value
82 pow(5, power) is
83
Neil Booth91305512007-10-15 15:00:55 +000084 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +000085
Neil Boothb93d90e2007-10-12 16:02:31 +000086 However, whilst the result may require only this many parts,
87 because we are multiplying two values to get it, the
88 multiplication may require an extra part with the excess part
89 being zero (consider the trivial case of 1 * 1, tcFullMultiply
90 requires two parts to hold the single-part result). So we add an
91 extra one to guarantee enough space whilst multiplying. */
92 const unsigned int maxExponent = 16383;
93 const unsigned int maxPrecision = 113;
94 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Neil Booth91305512007-10-15 15:00:55 +000095 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815)
96 / (351 * integerPartWidth));
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000097}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000098
Chris Lattner91702092009-03-12 23:59:55 +000099/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000100
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000101static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000102partCountForBits(unsigned int bits)
103{
104 return ((bits) + integerPartWidth - 1) / integerPartWidth;
105}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000106
Chris Lattner91702092009-03-12 23:59:55 +0000107/* Returns 0U-9U. Return values >= 10U are not digits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000108static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000109decDigitValue(unsigned int c)
110{
111 return c - '0';
112}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000113
Chris Lattner91702092009-03-12 23:59:55 +0000114/* Return the value of a decimal exponent of the form
115 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000116
Chris Lattner91702092009-03-12 23:59:55 +0000117 If the exponent overflows, returns a large exponent with the
118 appropriate sign. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000119static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000120readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000121{
122 bool isNegative;
123 unsigned int absExponent;
124 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000125 StringRef::iterator p = begin;
126
127 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000128
Chris Lattner91702092009-03-12 23:59:55 +0000129 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000130 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000131 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000132 assert(p != end && "Exponent has no digits");
133 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000134
Chris Lattner91702092009-03-12 23:59:55 +0000135 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000136 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000137
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000138 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000139 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000140
Chris Lattner91702092009-03-12 23:59:55 +0000141 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000142 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000143
Chris Lattner91702092009-03-12 23:59:55 +0000144 value += absExponent * 10;
145 if (absExponent >= overlargeExponent) {
146 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000147 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000148 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000149 }
Chris Lattner91702092009-03-12 23:59:55 +0000150 absExponent = value;
151 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000152
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000153 assert(p == end && "Invalid exponent in exponent");
154
Chris Lattner91702092009-03-12 23:59:55 +0000155 if (isNegative)
156 return -(int) absExponent;
157 else
158 return (int) absExponent;
159}
160
161/* This is ugly and needs cleaning up, but I don't immediately see
162 how whilst remaining safe. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000163static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000164totalExponent(StringRef::iterator p, StringRef::iterator end,
165 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000166{
167 int unsignedExponent;
168 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000169 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000170
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000171 assert(p != end && "Exponent has no digits");
172
Chris Lattner91702092009-03-12 23:59:55 +0000173 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000174 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000175 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000176 assert(p != end && "Exponent has no digits");
177 }
Chris Lattner91702092009-03-12 23:59:55 +0000178
179 unsignedExponent = 0;
180 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000181 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000182 unsigned int value;
183
184 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000185 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000186
Chris Lattner91702092009-03-12 23:59:55 +0000187 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000188 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000189 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000190 break;
191 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000192 }
193
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000194 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000195 overflow = true;
196
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000197 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000198 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000199 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000200 exponent = -exponent;
201 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000202 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000203 overflow = true;
204 }
205
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000206 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000207 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000208
209 return exponent;
210}
211
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000212static StringRef::iterator
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000213skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
214 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000215{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000216 StringRef::iterator p = begin;
217 *dot = end;
Nick Lewycky095b92e2014-09-06 01:16:42 +0000218 while (p != end && *p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000219 p++;
220
Nick Lewycky095b92e2014-09-06 01:16:42 +0000221 if (p != end && *p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000222 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000223
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000224 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000225
Nick Lewycky095b92e2014-09-06 01:16:42 +0000226 while (p != end && *p == '0')
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000227 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000228 }
229
Chris Lattner91702092009-03-12 23:59:55 +0000230 return p;
231}
Neil Booth4ed401b2007-10-14 10:16:12 +0000232
Chris Lattner91702092009-03-12 23:59:55 +0000233/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000234
Chris Lattner91702092009-03-12 23:59:55 +0000235 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000236
Chris Lattner91702092009-03-12 23:59:55 +0000237 where the decimal point and exponent are optional, fill out the
238 structure D. Exponent is appropriate if the significand is
239 treated as an integer, and normalizedExponent if the significand
240 is taken to have the decimal point after a single leading
241 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000242
Chris Lattner91702092009-03-12 23:59:55 +0000243 If the value is zero, V->firstSigDigit points to a non-digit, and
244 the return exponent is zero.
245*/
246struct decimalInfo {
247 const char *firstSigDigit;
248 const char *lastSigDigit;
249 int exponent;
250 int normalizedExponent;
251};
Neil Booth4ed401b2007-10-14 10:16:12 +0000252
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000253static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000254interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
255 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000256{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000257 StringRef::iterator dot = end;
258 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000259
Chris Lattner91702092009-03-12 23:59:55 +0000260 D->firstSigDigit = p;
261 D->exponent = 0;
262 D->normalizedExponent = 0;
263
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000264 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000265 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000266 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000267 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000268 if (p == end)
269 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000270 }
Chris Lattner91702092009-03-12 23:59:55 +0000271 if (decDigitValue(*p) >= 10U)
272 break;
Chris Lattner91702092009-03-12 23:59:55 +0000273 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000274
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000275 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000276 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
277 assert(p != begin && "Significand has no digits");
278 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000279
280 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000281 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000282
Chris Lattner91702092009-03-12 23:59:55 +0000283 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000284 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000285 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000286 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000287
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000288 /* If number is all zeroes accept any exponent. */
289 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000290 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000291 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000292 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000293 do
294 p--;
295 while (p != begin && *p == '0');
296 while (p != begin && *p == '.');
297 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000298
Chris Lattner91702092009-03-12 23:59:55 +0000299 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000300 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000301 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000302 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000303 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000304 }
305
Chris Lattner91702092009-03-12 23:59:55 +0000306 D->lastSigDigit = p;
307}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000308
Chris Lattner91702092009-03-12 23:59:55 +0000309/* Return the trailing fraction of a hexadecimal number.
310 DIGITVALUE is the first hex digit of the fraction, P points to
311 the next digit. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000312static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000313trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
314 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000315{
316 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000317
Chris Lattner91702092009-03-12 23:59:55 +0000318 /* If the first trailing digit isn't 0 or 8 we can work out the
319 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000320 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000321 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000322 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000323 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000324
Eli Friedmand2eb07a2013-07-17 22:17:29 +0000325 // Otherwise we need to find the first non-zero digit.
326 while (p != end && (*p == '0' || *p == '.'))
Chris Lattner91702092009-03-12 23:59:55 +0000327 p++;
328
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000329 assert(p != end && "Invalid trailing hexadecimal fraction!");
330
Chris Lattner91702092009-03-12 23:59:55 +0000331 hexDigit = hexDigitValue(*p);
332
333 /* If we ran off the end it is exactly zero or one-half, otherwise
334 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000335 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000336 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
337 else
338 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
339}
340
341/* Return the fraction lost were a bignum truncated losing the least
342 significant BITS bits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000343static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000344lostFractionThroughTruncation(const integerPart *parts,
345 unsigned int partCount,
346 unsigned int bits)
347{
348 unsigned int lsb;
349
350 lsb = APInt::tcLSB(parts, partCount);
351
352 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000353 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000354 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000355 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000356 return lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000357 if (bits <= partCount * integerPartWidth &&
358 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000359 return lfMoreThanHalf;
360
361 return lfLessThanHalf;
362}
363
364/* Shift DST right BITS bits noting lost fraction. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000365static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000366shiftRight(integerPart *dst, unsigned int parts, unsigned int bits)
367{
368 lostFraction lost_fraction;
369
370 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
371
372 APInt::tcShiftRight(dst, parts, bits);
373
374 return lost_fraction;
375}
376
377/* Combine the effect of two lost fractions. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000378static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000379combineLostFractions(lostFraction moreSignificant,
380 lostFraction lessSignificant)
381{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000382 if (lessSignificant != lfExactlyZero) {
383 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000384 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000385 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000386 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000387 }
388
Chris Lattner91702092009-03-12 23:59:55 +0000389 return moreSignificant;
390}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000391
Chris Lattner91702092009-03-12 23:59:55 +0000392/* The error from the true value, in half-ulps, on multiplying two
393 floating point numbers, which differ from the value they
394 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
395 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000396
Chris Lattner91702092009-03-12 23:59:55 +0000397 See "How to Read Floating Point Numbers Accurately" by William D
398 Clinger. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000399static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000400HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
401{
402 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000403
Chris Lattner91702092009-03-12 23:59:55 +0000404 if (HUerr1 + HUerr2 == 0)
405 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
406 else
407 return inexactMultiply + 2 * (HUerr1 + HUerr2);
408}
Neil Booth8f1946f2007-10-03 22:26:02 +0000409
Chris Lattner91702092009-03-12 23:59:55 +0000410/* The number of ulps from the boundary (zero, or half if ISNEAREST)
411 when the least significant BITS are truncated. BITS cannot be
412 zero. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000413static integerPart
Chris Lattner91702092009-03-12 23:59:55 +0000414ulpsFromBoundary(const integerPart *parts, unsigned int bits, bool isNearest)
415{
416 unsigned int count, partBits;
417 integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000418
Evan Cheng67c90212009-10-27 21:35:42 +0000419 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000420
Chris Lattner91702092009-03-12 23:59:55 +0000421 bits--;
422 count = bits / integerPartWidth;
423 partBits = bits % integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000424
Chris Lattner91702092009-03-12 23:59:55 +0000425 part = parts[count] & (~(integerPart) 0 >> (integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000426
Chris Lattner91702092009-03-12 23:59:55 +0000427 if (isNearest)
428 boundary = (integerPart) 1 << (partBits - 1);
429 else
430 boundary = 0;
431
432 if (count == 0) {
433 if (part - boundary <= boundary - part)
434 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000435 else
Chris Lattner91702092009-03-12 23:59:55 +0000436 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000437 }
438
Chris Lattner91702092009-03-12 23:59:55 +0000439 if (part == boundary) {
440 while (--count)
441 if (parts[count])
442 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000443
Chris Lattner91702092009-03-12 23:59:55 +0000444 return parts[0];
445 } else if (part == boundary - 1) {
446 while (--count)
447 if (~parts[count])
448 return ~(integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000449
Chris Lattner91702092009-03-12 23:59:55 +0000450 return -parts[0];
451 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000452
Chris Lattner91702092009-03-12 23:59:55 +0000453 return ~(integerPart) 0; /* A lot. */
454}
Neil Boothb93d90e2007-10-12 16:02:31 +0000455
Chris Lattner91702092009-03-12 23:59:55 +0000456/* Place pow(5, power) in DST, and return the number of parts used.
457 DST must be at least one part larger than size of the answer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000458static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000459powerOf5(integerPart *dst, unsigned int power)
460{
461 static const integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125,
462 15625, 78125 };
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000463 integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
464 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000465
Chris Lattner0bf18692009-03-13 00:03:51 +0000466 unsigned int partsCount[16] = { 1 };
Chris Lattner91702092009-03-12 23:59:55 +0000467 integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
468 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000469 assert(power <= maxExponent);
470
471 p1 = dst;
472 p2 = scratch;
473
474 *p1 = firstEightPowers[power & 7];
475 power >>= 3;
476
477 result = 1;
478 pow5 = pow5s;
479
480 for (unsigned int n = 0; power; power >>= 1, n++) {
481 unsigned int pc;
482
483 pc = partsCount[n];
484
485 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
486 if (pc == 0) {
487 pc = partsCount[n - 1];
488 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
489 pc *= 2;
490 if (pow5[pc - 1] == 0)
491 pc--;
492 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000493 }
494
Chris Lattner91702092009-03-12 23:59:55 +0000495 if (power & 1) {
496 integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000497
Chris Lattner91702092009-03-12 23:59:55 +0000498 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
499 result += pc;
500 if (p2[result - 1] == 0)
501 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000502
Chris Lattner91702092009-03-12 23:59:55 +0000503 /* Now result is in p1 with partsCount parts and p2 is scratch
504 space. */
Richard Trieu7a083812016-02-18 22:09:30 +0000505 tmp = p1;
506 p1 = p2;
507 p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000508 }
509
Chris Lattner91702092009-03-12 23:59:55 +0000510 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000511 }
512
Chris Lattner91702092009-03-12 23:59:55 +0000513 if (p1 != dst)
514 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000515
Chris Lattner91702092009-03-12 23:59:55 +0000516 return result;
517}
Neil Boothb93d90e2007-10-12 16:02:31 +0000518
Chris Lattner91702092009-03-12 23:59:55 +0000519/* Zero at the end to avoid modular arithmetic when adding one; used
520 when rounding up during hexadecimal output. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000521static const char hexDigitsLower[] = "0123456789abcdef0";
522static const char hexDigitsUpper[] = "0123456789ABCDEF0";
523static const char infinityL[] = "infinity";
524static const char infinityU[] = "INFINITY";
525static const char NaNL[] = "nan";
526static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000527
Chris Lattner91702092009-03-12 23:59:55 +0000528/* Write out an integerPart in hexadecimal, starting with the most
529 significant nibble. Write out exactly COUNT hexdigits, return
530 COUNT. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000531static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000532partAsHex (char *dst, integerPart part, unsigned int count,
533 const char *hexDigitChars)
534{
535 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000536
Evan Cheng67c90212009-10-27 21:35:42 +0000537 assert(count != 0 && count <= integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000538
Chris Lattner91702092009-03-12 23:59:55 +0000539 part >>= (integerPartWidth - 4 * count);
540 while (count--) {
541 dst[count] = hexDigitChars[part & 0xf];
542 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000543 }
544
Chris Lattner91702092009-03-12 23:59:55 +0000545 return result;
546}
Neil Booth8f1946f2007-10-03 22:26:02 +0000547
Chris Lattner91702092009-03-12 23:59:55 +0000548/* Write out an unsigned decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000549static char *
Chris Lattner91702092009-03-12 23:59:55 +0000550writeUnsignedDecimal (char *dst, unsigned int n)
551{
552 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000553
Chris Lattner91702092009-03-12 23:59:55 +0000554 p = buff;
555 do
556 *p++ = '0' + n % 10;
557 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000558
Chris Lattner91702092009-03-12 23:59:55 +0000559 do
560 *dst++ = *--p;
561 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000562
Chris Lattner91702092009-03-12 23:59:55 +0000563 return dst;
564}
Neil Booth8f1946f2007-10-03 22:26:02 +0000565
Chris Lattner91702092009-03-12 23:59:55 +0000566/* Write out a signed decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000567static char *
Chris Lattner91702092009-03-12 23:59:55 +0000568writeSignedDecimal (char *dst, int value)
569{
570 if (value < 0) {
571 *dst++ = '-';
572 dst = writeUnsignedDecimal(dst, -(unsigned) value);
573 } else
574 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000575
Chris Lattner91702092009-03-12 23:59:55 +0000576 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000577}
578
579/* Constructors. */
580void
581APFloat::initialize(const fltSemantics *ourSemantics)
582{
583 unsigned int count;
584
585 semantics = ourSemantics;
586 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000587 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000588 significand.parts = new integerPart[count];
589}
590
591void
592APFloat::freeSignificand()
593{
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000594 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000595 delete [] significand.parts;
596}
597
598void
599APFloat::assign(const APFloat &rhs)
600{
601 assert(semantics == rhs.semantics);
602
603 sign = rhs.sign;
604 category = rhs.category;
605 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000606 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000607 copySignificand(rhs);
608}
609
610void
611APFloat::copySignificand(const APFloat &rhs)
612{
Michael Gottesman8136c382013-06-26 23:17:28 +0000613 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000614 assert(rhs.partCount() >= partCount());
615
616 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000617 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000618}
619
Neil Booth5fe658b2007-10-14 10:39:51 +0000620/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000621 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000622 which may not be ideal. If float, this is QNaN(0). */
John McCalldcb9a7a2010-02-28 02:51:25 +0000623void APFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill)
Neil Booth5fe658b2007-10-14 10:39:51 +0000624{
625 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000626 sign = Negative;
627
John McCallc12b1332010-02-28 12:49:50 +0000628 integerPart *significand = significandParts();
629 unsigned numParts = partCount();
630
John McCalldcb9a7a2010-02-28 02:51:25 +0000631 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000632 if (!fill || fill->getNumWords() < numParts)
633 APInt::tcSet(significand, 0, numParts);
634 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000635 APInt::tcAssign(significand, fill->getRawData(),
636 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000637
638 // Zero out the excess bits of the significand.
639 unsigned bitsToPreserve = semantics->precision - 1;
640 unsigned part = bitsToPreserve / 64;
641 bitsToPreserve %= 64;
642 significand[part] &= ((1ULL << bitsToPreserve) - 1);
643 for (part++; part != numParts; ++part)
644 significand[part] = 0;
645 }
646
647 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000648
649 if (SNaN) {
650 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000651 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000652
653 // If there are no bits set in the payload, we have to set
654 // *something* to make it a NaN instead of an infinity;
655 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000656 if (APInt::tcIsZero(significand, numParts))
657 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000658 } else {
659 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000660 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000661 }
John McCallc12b1332010-02-28 12:49:50 +0000662
663 // For x87 extended precision, we want to make a NaN, not a
664 // pseudo-NaN. Maybe we should expose the ability to make
665 // pseudo-NaNs?
666 if (semantics == &APFloat::x87DoubleExtended)
667 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000668}
669
670APFloat APFloat::makeNaN(const fltSemantics &Sem, bool SNaN, bool Negative,
671 const APInt *fill) {
672 APFloat value(Sem, uninitialized);
673 value.makeNaN(SNaN, Negative, fill);
674 return value;
Neil Booth5fe658b2007-10-14 10:39:51 +0000675}
676
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000677APFloat &
678APFloat::operator=(const APFloat &rhs)
679{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000680 if (this != &rhs) {
681 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000682 freeSignificand();
683 initialize(rhs.semantics);
684 }
685 assign(rhs);
686 }
687
688 return *this;
689}
690
Benjamin Kramer06f47782014-03-04 20:26:51 +0000691APFloat &
692APFloat::operator=(APFloat &&rhs) {
693 freeSignificand();
694
695 semantics = rhs.semantics;
696 significand = rhs.significand;
697 exponent = rhs.exponent;
698 category = rhs.category;
699 sign = rhs.sign;
700
701 rhs.semantics = &Bogus;
702 return *this;
703}
704
Dale Johannesena719a602007-08-24 00:56:33 +0000705bool
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000706APFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000707 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000708 (APInt::tcExtractBit(significandParts(),
709 semantics->precision - 1) == 0);
710}
711
712bool
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000713APFloat::isSmallest() const {
714 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000715 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000716 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000717 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000718 significandMSB() == 0;
719}
720
721bool APFloat::isSignificandAllOnes() const {
722 // Test if the significand excluding the integral bit is all ones. This allows
723 // us to test for binade boundaries.
724 const integerPart *Parts = significandParts();
725 const unsigned PartCount = partCount();
726 for (unsigned i = 0; i < PartCount - 1; i++)
727 if (~Parts[i])
728 return false;
729
730 // Set the unused high bits to all ones when we compare.
731 const unsigned NumHighBits =
732 PartCount*integerPartWidth - semantics->precision + 1;
733 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
734 "fill than integerPartWidth");
735 const integerPart HighBitFill =
736 ~integerPart(0) << (integerPartWidth - NumHighBits);
737 if (~(Parts[PartCount - 1] | HighBitFill))
738 return false;
739
740 return true;
741}
742
743bool APFloat::isSignificandAllZeros() const {
744 // Test if the significand excluding the integral bit is all zeros. This
745 // allows us to test for binade boundaries.
746 const integerPart *Parts = significandParts();
747 const unsigned PartCount = partCount();
748
749 for (unsigned i = 0; i < PartCount - 1; i++)
750 if (Parts[i])
751 return false;
752
753 const unsigned NumHighBits =
754 PartCount*integerPartWidth - semantics->precision + 1;
755 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
756 "clear than integerPartWidth");
757 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
758
759 if (Parts[PartCount - 1] & HighBitMask)
760 return false;
761
762 return true;
763}
764
765bool
766APFloat::isLargest() const {
767 // The largest number by magnitude in our format will be the floating point
768 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000769 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000770 && isSignificandAllOnes();
771}
772
773bool
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000774APFloat::isInteger() const {
775 // This could be made more efficient; I'm going for obviously correct.
776 if (!isFinite()) return false;
777 APFloat truncated = *this;
778 truncated.roundToIntegral(rmTowardZero);
779 return compare(truncated) == cmpEqual;
780}
781
782bool
Dale Johannesenbdea32d2007-08-24 22:09:56 +0000783APFloat::bitwiseIsEqual(const APFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000784 if (this == &rhs)
785 return true;
786 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000787 category != rhs.category ||
788 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000789 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000790 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000791 return true;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000792
793 if (isFiniteNonZero() && exponent != rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000794 return false;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000795
796 return std::equal(significandParts(), significandParts() + partCount(),
797 rhs.significandParts());
Dale Johannesena719a602007-08-24 00:56:33 +0000798}
799
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000800APFloat::APFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000801 initialize(&ourSemantics);
802 sign = 0;
Michael Gottesman30a90eb2013-07-27 21:49:21 +0000803 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000804 zeroSignificand();
805 exponent = ourSemantics.precision - 1;
806 significandParts()[0] = value;
807 normalize(rmNearestTiesToEven, lfExactlyZero);
808}
809
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000810APFloat::APFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000811 initialize(&ourSemantics);
812 category = fcZero;
813 sign = false;
814}
815
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000816APFloat::APFloat(const fltSemantics &ourSemantics, uninitializedTag tag) {
John McCalldcb9a7a2010-02-28 02:51:25 +0000817 // Allocates storage if necessary but does not initialize it.
818 initialize(&ourSemantics);
819}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000820
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000821APFloat::APFloat(const fltSemantics &ourSemantics, StringRef text) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000822 initialize(&ourSemantics);
823 convertFromString(text, rmNearestTiesToEven);
824}
825
Ulrich Weigande1d62f92012-10-29 18:17:42 +0000826APFloat::APFloat(const APFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000827 initialize(rhs.semantics);
828 assign(rhs);
829}
830
Benjamin Kramer06f47782014-03-04 20:26:51 +0000831APFloat::APFloat(APFloat &&rhs) : semantics(&Bogus) {
832 *this = std::move(rhs);
833}
834
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000835APFloat::~APFloat()
836{
837 freeSignificand();
838}
839
Ted Kremenek6f30a072008-02-11 17:24:50 +0000840// Profile - This method 'profiles' an APFloat for use with FoldingSet.
841void APFloat::Profile(FoldingSetNodeID& ID) const {
Dale Johannesen54306fe2008-10-09 18:53:47 +0000842 ID.Add(bitcastToAPInt());
Ted Kremenek6f30a072008-02-11 17:24:50 +0000843}
844
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000845unsigned int
846APFloat::partCount() const
847{
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000848 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000849}
850
851unsigned int
852APFloat::semanticsPrecision(const fltSemantics &semantics)
853{
854 return semantics.precision;
855}
JF Bastiena1d3c242015-08-26 02:32:45 +0000856APFloat::ExponentType
857APFloat::semanticsMaxExponent(const fltSemantics &semantics)
858{
859 return semantics.maxExponent;
860}
861APFloat::ExponentType
862APFloat::semanticsMinExponent(const fltSemantics &semantics)
863{
864 return semantics.minExponent;
865}
866unsigned int
867APFloat::semanticsSizeInBits(const fltSemantics &semantics)
868{
869 return semantics.sizeInBits;
870}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000871
872const integerPart *
873APFloat::significandParts() const
874{
875 return const_cast<APFloat *>(this)->significandParts();
876}
877
878integerPart *
879APFloat::significandParts()
880{
Evan Cheng67c90212009-10-27 21:35:42 +0000881 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000882 return significand.parts;
883 else
884 return &significand.part;
885}
886
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000887void
888APFloat::zeroSignificand()
889{
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000890 APInt::tcSet(significandParts(), 0, partCount());
891}
892
893/* Increment an fcNormal floating point number's significand. */
894void
895APFloat::incrementSignificand()
896{
897 integerPart carry;
898
899 carry = APInt::tcIncrement(significandParts(), partCount());
900
901 /* Our callers should never cause us to overflow. */
902 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000903 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000904}
905
906/* Add the significand of the RHS. Returns the carry flag. */
907integerPart
908APFloat::addSignificand(const APFloat &rhs)
909{
910 integerPart *parts;
911
912 parts = significandParts();
913
914 assert(semantics == rhs.semantics);
915 assert(exponent == rhs.exponent);
916
917 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
918}
919
920/* Subtract the significand of the RHS with a borrow flag. Returns
921 the borrow flag. */
922integerPart
923APFloat::subtractSignificand(const APFloat &rhs, integerPart borrow)
924{
925 integerPart *parts;
926
927 parts = significandParts();
928
929 assert(semantics == rhs.semantics);
930 assert(exponent == rhs.exponent);
931
932 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000933 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000934}
935
936/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
937 on to the full-precision result of the multiplication. Returns the
938 lost fraction. */
939lostFraction
940APFloat::multiplySignificand(const APFloat &rhs, const APFloat *addend)
941{
Neil Booth9acbf5a2007-09-26 21:33:42 +0000942 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000943 unsigned int partsCount, newPartsCount, precision;
944 integerPart *lhsSignificand;
945 integerPart scratch[4];
946 integerPart *fullSignificand;
947 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000948 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000949
950 assert(semantics == rhs.semantics);
951
952 precision = semantics->precision;
Lang Hames56c0eb22014-11-19 19:15:41 +0000953
954 // Allocate space for twice as many bits as the original significand, plus one
955 // extra bit for the addition to overflow into.
956 newPartsCount = partCountForBits(precision * 2 + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000957
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000958 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000959 fullSignificand = new integerPart[newPartsCount];
960 else
961 fullSignificand = scratch;
962
963 lhsSignificand = significandParts();
964 partsCount = partCount();
965
966 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000967 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000968
969 lost_fraction = lfExactlyZero;
970 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
971 exponent += rhs.exponent;
972
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000973 // Assume the operands involved in the multiplication are single-precision
974 // FP, and the two multiplicants are:
975 // *this = a23 . a22 ... a0 * 2^e1
976 // rhs = b23 . b22 ... b0 * 2^e2
977 // the result of multiplication is:
Lang Hames56c0eb22014-11-19 19:15:41 +0000978 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
979 // Note that there are three significant bits at the left-hand side of the
980 // radix point: two for the multiplication, and an overflow bit for the
981 // addition (that will always be zero at this point). Move the radix point
982 // toward left by two bits, and adjust exponent accordingly.
983 exponent += 2;
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000984
Hal Finkel171c2ec2014-10-14 19:23:07 +0000985 if (addend && addend->isNonZero()) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000986 // The intermediate result of the multiplication has "2 * precision"
987 // signicant bit; adjust the addend to be consistent with mul result.
988 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000989 Significand savedSignificand = significand;
990 const fltSemantics *savedSemantics = semantics;
991 fltSemantics extendedSemantics;
992 opStatus status;
993 unsigned int extendedPrecision;
994
Lang Hames56c0eb22014-11-19 19:15:41 +0000995 // Normalize our MSB to one below the top bit to allow for overflow.
996 extendedPrecision = 2 * precision + 1;
997 if (omsb != extendedPrecision - 1) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000998 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000999 APInt::tcShiftLeft(fullSignificand, newPartsCount,
Lang Hames56c0eb22014-11-19 19:15:41 +00001000 (extendedPrecision - 1) - omsb);
1001 exponent -= (extendedPrecision - 1) - omsb;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001002 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001003
1004 /* Create new semantics. */
1005 extendedSemantics = *semantics;
1006 extendedSemantics.precision = extendedPrecision;
1007
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001008 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001009 significand.part = fullSignificand[0];
1010 else
1011 significand.parts = fullSignificand;
1012 semantics = &extendedSemantics;
1013
1014 APFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001015 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001016 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001017 (void)status;
Lang Hames56c0eb22014-11-19 19:15:41 +00001018
1019 // Shift the significand of the addend right by one bit. This guarantees
1020 // that the high bit of the significand is zero (same as fullSignificand),
1021 // so the addition will overflow (if it does overflow at all) into the top bit.
1022 lost_fraction = extendedAddend.shiftSignificandRight(1);
1023 assert(lost_fraction == lfExactlyZero &&
1024 "Lost precision while shifting addend for fused-multiply-add.");
1025
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001026 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1027
1028 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001029 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001030 fullSignificand[0] = significand.part;
1031 significand = savedSignificand;
1032 semantics = savedSemantics;
1033
1034 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1035 }
1036
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001037 // Convert the result having "2 * precision" significant-bits back to the one
1038 // having "precision" significant-bits. First, move the radix point from
1039 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1040 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
Lang Hames56c0eb22014-11-19 19:15:41 +00001041 exponent -= precision + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001042
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001043 // In case MSB resides at the left-hand side of radix point, shift the
1044 // mantissa right by some amount to make sure the MSB reside right before
1045 // the radix point (i.e. "MSB . rest-significant-bits").
1046 //
1047 // Note that the result is not normalized when "omsb < precision". So, the
1048 // caller needs to call APFloat::normalize() if normalized value is expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001049 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001050 unsigned int bits, significantParts;
1051 lostFraction lf;
1052
1053 bits = omsb - precision;
1054 significantParts = partCountForBits(omsb);
1055 lf = shiftRight(fullSignificand, significantParts, bits);
1056 lost_fraction = combineLostFractions(lf, lost_fraction);
1057 exponent += bits;
1058 }
1059
1060 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1061
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001062 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001063 delete [] fullSignificand;
1064
1065 return lost_fraction;
1066}
1067
1068/* Multiply the significands of LHS and RHS to DST. */
1069lostFraction
1070APFloat::divideSignificand(const APFloat &rhs)
1071{
1072 unsigned int bit, i, partsCount;
1073 const integerPart *rhsSignificand;
1074 integerPart *lhsSignificand, *dividend, *divisor;
1075 integerPart scratch[4];
1076 lostFraction lost_fraction;
1077
1078 assert(semantics == rhs.semantics);
1079
1080 lhsSignificand = significandParts();
1081 rhsSignificand = rhs.significandParts();
1082 partsCount = partCount();
1083
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001084 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001085 dividend = new integerPart[partsCount * 2];
1086 else
1087 dividend = scratch;
1088
1089 divisor = dividend + partsCount;
1090
1091 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001092 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001093 dividend[i] = lhsSignificand[i];
1094 divisor[i] = rhsSignificand[i];
1095 lhsSignificand[i] = 0;
1096 }
1097
1098 exponent -= rhs.exponent;
1099
1100 unsigned int precision = semantics->precision;
1101
1102 /* Normalize the divisor. */
1103 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001104 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001105 exponent += bit;
1106 APInt::tcShiftLeft(divisor, partsCount, bit);
1107 }
1108
1109 /* Normalize the dividend. */
1110 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001111 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001112 exponent -= bit;
1113 APInt::tcShiftLeft(dividend, partsCount, bit);
1114 }
1115
Neil Boothb93d90e2007-10-12 16:02:31 +00001116 /* Ensure the dividend >= divisor initially for the loop below.
1117 Incidentally, this means that the division loop below is
1118 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001119 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001120 exponent--;
1121 APInt::tcShiftLeft(dividend, partsCount, 1);
1122 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1123 }
1124
1125 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001126 for (bit = precision; bit; bit -= 1) {
1127 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001128 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1129 APInt::tcSetBit(lhsSignificand, bit - 1);
1130 }
1131
1132 APInt::tcShiftLeft(dividend, partsCount, 1);
1133 }
1134
1135 /* Figure out the lost fraction. */
1136 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1137
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001138 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001139 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001140 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001141 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001142 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001143 lost_fraction = lfExactlyZero;
1144 else
1145 lost_fraction = lfLessThanHalf;
1146
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001147 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001148 delete [] dividend;
1149
1150 return lost_fraction;
1151}
1152
1153unsigned int
1154APFloat::significandMSB() const
1155{
1156 return APInt::tcMSB(significandParts(), partCount());
1157}
1158
1159unsigned int
1160APFloat::significandLSB() const
1161{
1162 return APInt::tcLSB(significandParts(), partCount());
1163}
1164
1165/* Note that a zero result is NOT normalized to fcZero. */
1166lostFraction
1167APFloat::shiftSignificandRight(unsigned int bits)
1168{
1169 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001170 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001171
1172 exponent += bits;
1173
1174 return shiftRight(significandParts(), partCount(), bits);
1175}
1176
1177/* Shift the significand left BITS bits, subtract BITS from its exponent. */
1178void
1179APFloat::shiftSignificandLeft(unsigned int bits)
1180{
1181 assert(bits < semantics->precision);
1182
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001183 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001184 unsigned int partsCount = partCount();
1185
1186 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1187 exponent -= bits;
1188
1189 assert(!APInt::tcIsZero(significandParts(), partsCount));
1190 }
1191}
1192
1193APFloat::cmpResult
1194APFloat::compareAbsoluteValue(const APFloat &rhs) const
1195{
1196 int compare;
1197
1198 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001199 assert(isFiniteNonZero());
1200 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001201
1202 compare = exponent - rhs.exponent;
1203
1204 /* If exponents are equal, do an unsigned bignum comparison of the
1205 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001206 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001207 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001208 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001209
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001210 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001211 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001212 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001213 return cmpLessThan;
1214 else
1215 return cmpEqual;
1216}
1217
1218/* Handle overflow. Sign is preserved. We either become infinity or
1219 the largest finite number. */
1220APFloat::opStatus
1221APFloat::handleOverflow(roundingMode rounding_mode)
1222{
1223 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001224 if (rounding_mode == rmNearestTiesToEven ||
1225 rounding_mode == rmNearestTiesToAway ||
1226 (rounding_mode == rmTowardPositive && !sign) ||
1227 (rounding_mode == rmTowardNegative && sign)) {
1228 category = fcInfinity;
1229 return (opStatus) (opOverflow | opInexact);
1230 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001231
1232 /* Otherwise we become the largest finite number. */
1233 category = fcNormal;
1234 exponent = semantics->maxExponent;
1235 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001236 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001237
1238 return opInexact;
1239}
1240
Neil Booth1ca1f802007-10-03 15:16:41 +00001241/* Returns TRUE if, when truncating the current number, with BIT the
1242 new LSB, with the given lost fraction and rounding mode, the result
1243 would need to be rounded away from zero (i.e., by increasing the
1244 signficand). This routine must work for fcZero of both signs, and
1245 fcNormal numbers. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001246bool
1247APFloat::roundAwayFromZero(roundingMode rounding_mode,
Neil Booth1ca1f802007-10-03 15:16:41 +00001248 lostFraction lost_fraction,
1249 unsigned int bit) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001250{
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001251 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001252 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001253
Neil Booth1ca1f802007-10-03 15:16:41 +00001254 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001255 assert(lost_fraction != lfExactlyZero);
1256
Mike Stump889285d2009-05-13 23:23:20 +00001257 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001258 case rmNearestTiesToAway:
1259 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1260
1261 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001262 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001263 return true;
1264
1265 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001266 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001267 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001268
1269 return false;
1270
1271 case rmTowardZero:
1272 return false;
1273
1274 case rmTowardPositive:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001275 return !sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001276
1277 case rmTowardNegative:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001278 return sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001279 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001280 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001281}
1282
1283APFloat::opStatus
1284APFloat::normalize(roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001285 lostFraction lost_fraction)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001286{
Neil Booth9acbf5a2007-09-26 21:33:42 +00001287 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001288 int exponentChange;
1289
Michael Gottesman8136c382013-06-26 23:17:28 +00001290 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001291 return opOK;
1292
1293 /* Before rounding normalize the exponent of fcNormal numbers. */
1294 omsb = significandMSB() + 1;
1295
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001296 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001297 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001298 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001299 the exponent. */
1300 exponentChange = omsb - semantics->precision;
1301
1302 /* If the resulting exponent is too high, overflow according to
1303 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001304 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001305 return handleOverflow(rounding_mode);
1306
1307 /* Subnormal numbers have exponent minExponent, and their MSB
1308 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001309 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001310 exponentChange = semantics->minExponent - exponent;
1311
1312 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001313 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001314 assert(lost_fraction == lfExactlyZero);
1315
1316 shiftSignificandLeft(-exponentChange);
1317
1318 return opOK;
1319 }
1320
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001321 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001322 lostFraction lf;
1323
1324 /* Shift right and capture any new lost fraction. */
1325 lf = shiftSignificandRight(exponentChange);
1326
1327 lost_fraction = combineLostFractions(lf, lost_fraction);
1328
1329 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001330 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001331 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001332 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001333 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001334 }
1335 }
1336
1337 /* Now round the number according to rounding_mode given the lost
1338 fraction. */
1339
1340 /* As specified in IEEE 754, since we do not trap we do not report
1341 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001342 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001343 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001344 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001345 category = fcZero;
1346
1347 return opOK;
1348 }
1349
1350 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001351 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1352 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001353 exponent = semantics->minExponent;
1354
1355 incrementSignificand();
1356 omsb = significandMSB() + 1;
1357
1358 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001359 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001360 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001361 significand right one. However if we already have the
1362 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001363 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001364 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001365
Neil Booth9acbf5a2007-09-26 21:33:42 +00001366 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001367 }
1368
1369 shiftSignificandRight(1);
1370
1371 return opInexact;
1372 }
1373 }
1374
1375 /* The normal case - we were and are not denormal, and any
1376 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001377 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001378 return opInexact;
1379
1380 /* We have a non-zero denormal. */
1381 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001382
1383 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001384 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001385 category = fcZero;
1386
1387 /* The fcZero case is a denormal that underflowed to zero. */
1388 return (opStatus) (opUnderflow | opInexact);
1389}
1390
1391APFloat::opStatus
1392APFloat::addOrSubtractSpecials(const APFloat &rhs, bool subtract)
1393{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001394 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001395 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001396 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001397
Michael Gottesman9b877e12013-06-24 09:57:57 +00001398 case PackCategoriesIntoKey(fcNaN, fcZero):
1399 case PackCategoriesIntoKey(fcNaN, fcNormal):
1400 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1401 case PackCategoriesIntoKey(fcNaN, fcNaN):
1402 case PackCategoriesIntoKey(fcNormal, fcZero):
1403 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1404 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001405 return opOK;
1406
Michael Gottesman9b877e12013-06-24 09:57:57 +00001407 case PackCategoriesIntoKey(fcZero, fcNaN):
1408 case PackCategoriesIntoKey(fcNormal, fcNaN):
1409 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Stephen Canond3278282014-06-08 16:53:31 +00001410 // We need to be sure to flip the sign here for subtraction because we
1411 // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1412 sign = rhs.sign ^ subtract;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001413 category = fcNaN;
1414 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001415 return opOK;
1416
Michael Gottesman9b877e12013-06-24 09:57:57 +00001417 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1418 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001419 category = fcInfinity;
1420 sign = rhs.sign ^ subtract;
1421 return opOK;
1422
Michael Gottesman9b877e12013-06-24 09:57:57 +00001423 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001424 assign(rhs);
1425 sign = rhs.sign ^ subtract;
1426 return opOK;
1427
Michael Gottesman9b877e12013-06-24 09:57:57 +00001428 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001429 /* Sign depends on rounding mode; handled by caller. */
1430 return opOK;
1431
Michael Gottesman9b877e12013-06-24 09:57:57 +00001432 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001433 /* Differently signed infinities can only be validly
1434 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001435 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001436 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001437 return opInvalidOp;
1438 }
1439
1440 return opOK;
1441
Michael Gottesman9b877e12013-06-24 09:57:57 +00001442 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001443 return opDivByZero;
1444 }
1445}
1446
1447/* Add or subtract two normal numbers. */
1448lostFraction
1449APFloat::addOrSubtractSignificand(const APFloat &rhs, bool subtract)
1450{
1451 integerPart carry;
1452 lostFraction lost_fraction;
1453 int bits;
1454
1455 /* Determine if the operation on the absolute values is effectively
1456 an addition or subtraction. */
Aaron Ballmand5cc45f2015-03-24 12:47:51 +00001457 subtract ^= static_cast<bool>(sign ^ rhs.sign);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001458
1459 /* Are we bigger exponent-wise than the RHS? */
1460 bits = exponent - rhs.exponent;
1461
1462 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001463 if (subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001464 APFloat temp_rhs(rhs);
1465 bool reverse;
1466
Chris Lattner3da18eb2007-08-24 03:02:34 +00001467 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001468 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1469 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001470 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001471 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1472 shiftSignificandLeft(1);
1473 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001474 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001475 lost_fraction = shiftSignificandRight(-bits - 1);
1476 temp_rhs.shiftSignificandLeft(1);
1477 reverse = true;
1478 }
1479
Chris Lattner3da18eb2007-08-24 03:02:34 +00001480 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001481 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001482 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001483 copySignificand(temp_rhs);
1484 sign = !sign;
1485 } else {
1486 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001487 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001488 }
1489
1490 /* Invert the lost fraction - it was on the RHS and
1491 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001492 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001493 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001494 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001495 lost_fraction = lfLessThanHalf;
1496
1497 /* The code above is intended to ensure that no borrow is
1498 necessary. */
1499 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001500 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001501 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001502 if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001503 APFloat temp_rhs(rhs);
1504
1505 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1506 carry = addSignificand(temp_rhs);
1507 } else {
1508 lost_fraction = shiftSignificandRight(-bits);
1509 carry = addSignificand(rhs);
1510 }
1511
1512 /* We have a guard bit; generating a carry cannot happen. */
1513 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001514 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001515 }
1516
1517 return lost_fraction;
1518}
1519
1520APFloat::opStatus
1521APFloat::multiplySpecials(const APFloat &rhs)
1522{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001523 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001524 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001525 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001526
Michael Gottesman9b877e12013-06-24 09:57:57 +00001527 case PackCategoriesIntoKey(fcNaN, fcZero):
1528 case PackCategoriesIntoKey(fcNaN, fcNormal):
1529 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1530 case PackCategoriesIntoKey(fcNaN, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001531 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001532 return opOK;
1533
Michael Gottesman9b877e12013-06-24 09:57:57 +00001534 case PackCategoriesIntoKey(fcZero, fcNaN):
1535 case PackCategoriesIntoKey(fcNormal, fcNaN):
1536 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001537 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001538 category = fcNaN;
1539 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001540 return opOK;
1541
Michael Gottesman9b877e12013-06-24 09:57:57 +00001542 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1543 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1544 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001545 category = fcInfinity;
1546 return opOK;
1547
Michael Gottesman9b877e12013-06-24 09:57:57 +00001548 case PackCategoriesIntoKey(fcZero, fcNormal):
1549 case PackCategoriesIntoKey(fcNormal, fcZero):
1550 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001551 category = fcZero;
1552 return opOK;
1553
Michael Gottesman9b877e12013-06-24 09:57:57 +00001554 case PackCategoriesIntoKey(fcZero, fcInfinity):
1555 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001556 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001557 return opInvalidOp;
1558
Michael Gottesman9b877e12013-06-24 09:57:57 +00001559 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001560 return opOK;
1561 }
1562}
1563
1564APFloat::opStatus
1565APFloat::divideSpecials(const APFloat &rhs)
1566{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001567 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001568 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001569 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001570
Michael Gottesman9b877e12013-06-24 09:57:57 +00001571 case PackCategoriesIntoKey(fcZero, fcNaN):
1572 case PackCategoriesIntoKey(fcNormal, fcNaN):
1573 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001574 category = fcNaN;
1575 copySignificand(rhs);
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001576 case PackCategoriesIntoKey(fcNaN, fcZero):
1577 case PackCategoriesIntoKey(fcNaN, fcNormal):
1578 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1579 case PackCategoriesIntoKey(fcNaN, fcNaN):
1580 sign = false;
1581 case PackCategoriesIntoKey(fcInfinity, fcZero):
1582 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1583 case PackCategoriesIntoKey(fcZero, fcInfinity):
1584 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001585 return opOK;
1586
Michael Gottesman9b877e12013-06-24 09:57:57 +00001587 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001588 category = fcZero;
1589 return opOK;
1590
Michael Gottesman9b877e12013-06-24 09:57:57 +00001591 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001592 category = fcInfinity;
1593 return opDivByZero;
1594
Michael Gottesman9b877e12013-06-24 09:57:57 +00001595 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1596 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001597 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001598 return opInvalidOp;
1599
Michael Gottesman9b877e12013-06-24 09:57:57 +00001600 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001601 return opOK;
1602 }
1603}
1604
Dale Johannesenb5721632009-01-21 00:35:19 +00001605APFloat::opStatus
1606APFloat::modSpecials(const APFloat &rhs)
1607{
Michael Gottesman9b877e12013-06-24 09:57:57 +00001608 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001609 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001610 llvm_unreachable(nullptr);
Dale Johannesenb5721632009-01-21 00:35:19 +00001611
Michael Gottesman9b877e12013-06-24 09:57:57 +00001612 case PackCategoriesIntoKey(fcNaN, fcZero):
1613 case PackCategoriesIntoKey(fcNaN, fcNormal):
1614 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1615 case PackCategoriesIntoKey(fcNaN, fcNaN):
1616 case PackCategoriesIntoKey(fcZero, fcInfinity):
1617 case PackCategoriesIntoKey(fcZero, fcNormal):
1618 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001619 return opOK;
1620
Michael Gottesman9b877e12013-06-24 09:57:57 +00001621 case PackCategoriesIntoKey(fcZero, fcNaN):
1622 case PackCategoriesIntoKey(fcNormal, fcNaN):
1623 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001624 sign = false;
Dale Johannesenb5721632009-01-21 00:35:19 +00001625 category = fcNaN;
1626 copySignificand(rhs);
1627 return opOK;
1628
Michael Gottesman9b877e12013-06-24 09:57:57 +00001629 case PackCategoriesIntoKey(fcNormal, fcZero):
1630 case PackCategoriesIntoKey(fcInfinity, fcZero):
1631 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1632 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1633 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001634 makeNaN();
1635 return opInvalidOp;
1636
Michael Gottesman9b877e12013-06-24 09:57:57 +00001637 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001638 return opOK;
1639 }
1640}
1641
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001642/* Change sign. */
1643void
1644APFloat::changeSign()
1645{
1646 /* Look mummy, this one's easy. */
1647 sign = !sign;
1648}
1649
Dale Johannesen689d17d2007-08-31 23:35:31 +00001650void
1651APFloat::clearSign()
1652{
1653 /* So is this one. */
1654 sign = 0;
1655}
1656
1657void
1658APFloat::copySign(const APFloat &rhs)
1659{
1660 /* And this one. */
1661 sign = rhs.sign;
1662}
1663
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001664/* Normalized addition or subtraction. */
1665APFloat::opStatus
1666APFloat::addOrSubtract(const APFloat &rhs, roundingMode rounding_mode,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001667 bool subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001668{
1669 opStatus fs;
1670
1671 fs = addOrSubtractSpecials(rhs, subtract);
1672
1673 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001674 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001675 lostFraction lost_fraction;
1676
1677 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1678 fs = normalize(rounding_mode, lost_fraction);
1679
1680 /* Can only be zero if we lost no fraction. */
1681 assert(category != fcZero || lost_fraction == lfExactlyZero);
1682 }
1683
1684 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1685 positive zero unless rounding to minus infinity, except that
1686 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001687 if (category == fcZero) {
1688 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001689 sign = (rounding_mode == rmTowardNegative);
1690 }
1691
1692 return fs;
1693}
1694
1695/* Normalized addition. */
1696APFloat::opStatus
1697APFloat::add(const APFloat &rhs, roundingMode rounding_mode)
1698{
1699 return addOrSubtract(rhs, rounding_mode, false);
1700}
1701
1702/* Normalized subtraction. */
1703APFloat::opStatus
1704APFloat::subtract(const APFloat &rhs, roundingMode rounding_mode)
1705{
1706 return addOrSubtract(rhs, rounding_mode, true);
1707}
1708
1709/* Normalized multiply. */
1710APFloat::opStatus
1711APFloat::multiply(const APFloat &rhs, roundingMode rounding_mode)
1712{
1713 opStatus fs;
1714
1715 sign ^= rhs.sign;
1716 fs = multiplySpecials(rhs);
1717
Michael Gottesman8136c382013-06-26 23:17:28 +00001718 if (isFiniteNonZero()) {
Craig Topperc10719f2014-04-07 04:17:22 +00001719 lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001720 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001721 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001722 fs = (opStatus) (fs | opInexact);
1723 }
1724
1725 return fs;
1726}
1727
1728/* Normalized divide. */
1729APFloat::opStatus
1730APFloat::divide(const APFloat &rhs, roundingMode rounding_mode)
1731{
1732 opStatus fs;
1733
1734 sign ^= rhs.sign;
1735 fs = divideSpecials(rhs);
1736
Michael Gottesman8136c382013-06-26 23:17:28 +00001737 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001738 lostFraction lost_fraction = divideSignificand(rhs);
1739 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001740 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001741 fs = (opStatus) (fs | opInexact);
1742 }
1743
1744 return fs;
1745}
1746
Dale Johannesenfe750172009-01-20 18:35:05 +00001747/* Normalized remainder. This is not currently correct in all cases. */
1748APFloat::opStatus
1749APFloat::remainder(const APFloat &rhs)
1750{
1751 opStatus fs;
1752 APFloat V = *this;
1753 unsigned int origSign = sign;
1754
Dale Johannesenfe750172009-01-20 18:35:05 +00001755 fs = V.divide(rhs, rmNearestTiesToEven);
1756 if (fs == opDivByZero)
1757 return fs;
1758
1759 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001760 integerPart *x = new integerPart[parts];
Dale Johannesenfe750172009-01-20 18:35:05 +00001761 bool ignored;
1762 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1763 rmNearestTiesToEven, &ignored);
1764 if (fs==opInvalidOp)
1765 return fs;
1766
1767 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1768 rmNearestTiesToEven);
1769 assert(fs==opOK); // should always work
1770
1771 fs = V.multiply(rhs, rmNearestTiesToEven);
1772 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1773
1774 fs = subtract(V, rmNearestTiesToEven);
1775 assert(fs==opOK || fs==opInexact); // likewise
1776
1777 if (isZero())
1778 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001779 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001780 return fs;
1781}
1782
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001783/* Normalized llvm frem (C fmod).
Dale Johannesenfe750172009-01-20 18:35:05 +00001784 This is not currently correct in all cases. */
Dale Johannesen689d17d2007-08-31 23:35:31 +00001785APFloat::opStatus
Stephen Canonb12db0e2015-09-21 19:29:25 +00001786APFloat::mod(const APFloat &rhs)
Dale Johannesen689d17d2007-08-31 23:35:31 +00001787{
1788 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001789 fs = modSpecials(rhs);
Dale Johannesen689d17d2007-08-31 23:35:31 +00001790
Michael Gottesman8136c382013-06-26 23:17:28 +00001791 if (isFiniteNonZero() && rhs.isFiniteNonZero()) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001792 APFloat V = *this;
1793 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001794
Dale Johannesenb5721632009-01-21 00:35:19 +00001795 fs = V.divide(rhs, rmNearestTiesToEven);
1796 if (fs == opDivByZero)
1797 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001798
Dale Johannesenb5721632009-01-21 00:35:19 +00001799 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001800 integerPart *x = new integerPart[parts];
Dale Johannesenb5721632009-01-21 00:35:19 +00001801 bool ignored;
1802 fs = V.convertToInteger(x, parts * integerPartWidth, true,
1803 rmTowardZero, &ignored);
1804 if (fs==opInvalidOp)
1805 return fs;
Dale Johannesen728687c2007-09-05 20:39:49 +00001806
Dale Johannesenb5721632009-01-21 00:35:19 +00001807 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1808 rmNearestTiesToEven);
1809 assert(fs==opOK); // should always work
Dale Johannesen728687c2007-09-05 20:39:49 +00001810
Stephen Canonb12db0e2015-09-21 19:29:25 +00001811 fs = V.multiply(rhs, rmNearestTiesToEven);
Dale Johannesenb5721632009-01-21 00:35:19 +00001812 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1813
Stephen Canonb12db0e2015-09-21 19:29:25 +00001814 fs = subtract(V, rmNearestTiesToEven);
Dale Johannesenb5721632009-01-21 00:35:19 +00001815 assert(fs==opOK || fs==opInexact); // likewise
1816
1817 if (isZero())
1818 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001819 delete[] x;
Dale Johannesenb5721632009-01-21 00:35:19 +00001820 }
Dale Johannesen689d17d2007-08-31 23:35:31 +00001821 return fs;
1822}
1823
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001824/* Normalized fused-multiply-add. */
1825APFloat::opStatus
1826APFloat::fusedMultiplyAdd(const APFloat &multiplicand,
Neil Booth9acbf5a2007-09-26 21:33:42 +00001827 const APFloat &addend,
1828 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001829{
1830 opStatus fs;
1831
1832 /* Post-multiplication sign, before addition. */
1833 sign ^= multiplicand.sign;
1834
1835 /* If and only if all arguments are normal do we need to do an
1836 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001837 if (isFiniteNonZero() &&
1838 multiplicand.isFiniteNonZero() &&
Hal Finkel171c2ec2014-10-14 19:23:07 +00001839 addend.isFinite()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001840 lostFraction lost_fraction;
1841
1842 lost_fraction = multiplySignificand(multiplicand, &addend);
1843 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001844 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001845 fs = (opStatus) (fs | opInexact);
1846
1847 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1848 positive zero unless rounding to minus infinity, except that
1849 adding two like-signed zeroes gives that zero. */
Lang Hames12b12e82015-01-04 01:20:55 +00001850 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001851 sign = (rounding_mode == rmTowardNegative);
1852 } else {
1853 fs = multiplySpecials(multiplicand);
1854
1855 /* FS can only be opOK or opInvalidOp. There is no more work
1856 to do in the latter case. The IEEE-754R standard says it is
1857 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001858 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001859
1860 If we need to do the addition we can do so with normal
1861 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001862 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001863 fs = addOrSubtract(addend, rounding_mode, false);
1864 }
1865
1866 return fs;
1867}
1868
Owen Andersona40319b2012-08-13 23:32:49 +00001869/* Rounding-mode corrrect round to integral value. */
1870APFloat::opStatus APFloat::roundToIntegral(roundingMode rounding_mode) {
1871 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001872
Owen Anderson352dfff2012-08-15 18:28:45 +00001873 // If the exponent is large enough, we know that this value is already
1874 // integral, and the arithmetic below would potentially cause it to saturate
1875 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001876 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001877 return opOK;
1878
Owen Andersona40319b2012-08-13 23:32:49 +00001879 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1880 // precision of our format, and then subtract it back off again. The choice
1881 // of rounding modes for the addition/subtraction determines the rounding mode
1882 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001883 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001884 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001885 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1886 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Owen Andersona40319b2012-08-13 23:32:49 +00001887 APFloat MagicConstant(*semantics);
1888 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1889 rmNearestTiesToEven);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001890 MagicConstant.copySign(*this);
1891
Owen Andersona40319b2012-08-13 23:32:49 +00001892 if (fs != opOK)
1893 return fs;
1894
Owen Anderson1ff74b02012-08-15 05:39:46 +00001895 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1896 bool inputSign = isNegative();
1897
Owen Andersona40319b2012-08-13 23:32:49 +00001898 fs = add(MagicConstant, rounding_mode);
1899 if (fs != opOK && fs != opInexact)
1900 return fs;
1901
1902 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001903
1904 // Restore the input sign.
1905 if (inputSign != isNegative())
1906 changeSign();
1907
Owen Andersona40319b2012-08-13 23:32:49 +00001908 return fs;
1909}
1910
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001911
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001912/* Comparison requires normalized numbers. */
1913APFloat::cmpResult
1914APFloat::compare(const APFloat &rhs) const
1915{
1916 cmpResult result;
1917
1918 assert(semantics == rhs.semantics);
1919
Michael Gottesman9b877e12013-06-24 09:57:57 +00001920 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001921 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001922 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001923
Michael Gottesman9b877e12013-06-24 09:57:57 +00001924 case PackCategoriesIntoKey(fcNaN, fcZero):
1925 case PackCategoriesIntoKey(fcNaN, fcNormal):
1926 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1927 case PackCategoriesIntoKey(fcNaN, fcNaN):
1928 case PackCategoriesIntoKey(fcZero, fcNaN):
1929 case PackCategoriesIntoKey(fcNormal, fcNaN):
1930 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001931 return cmpUnordered;
1932
Michael Gottesman9b877e12013-06-24 09:57:57 +00001933 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1934 case PackCategoriesIntoKey(fcInfinity, fcZero):
1935 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001936 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001937 return cmpLessThan;
1938 else
1939 return cmpGreaterThan;
1940
Michael Gottesman9b877e12013-06-24 09:57:57 +00001941 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1942 case PackCategoriesIntoKey(fcZero, fcInfinity):
1943 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001944 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001945 return cmpGreaterThan;
1946 else
1947 return cmpLessThan;
1948
Michael Gottesman9b877e12013-06-24 09:57:57 +00001949 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001950 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001951 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001952 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001953 return cmpLessThan;
1954 else
1955 return cmpGreaterThan;
1956
Michael Gottesman9b877e12013-06-24 09:57:57 +00001957 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001958 return cmpEqual;
1959
Michael Gottesman9b877e12013-06-24 09:57:57 +00001960 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001961 break;
1962 }
1963
1964 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001965 if (sign != rhs.sign) {
1966 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001967 result = cmpLessThan;
1968 else
1969 result = cmpGreaterThan;
1970 } else {
1971 /* Compare absolute values; invert result if negative. */
1972 result = compareAbsoluteValue(rhs);
1973
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001974 if (sign) {
1975 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001976 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001977 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001978 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001979 }
1980 }
1981
1982 return result;
1983}
1984
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001985/// APFloat::convert - convert a value of one floating point type to another.
1986/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1987/// records whether the transformation lost information, i.e. whether
1988/// converting the result back to the original type will produce the
1989/// original value (this is almost the same as return value==fsOK, but there
1990/// are edge cases where this is not so).
1991
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001992APFloat::opStatus
1993APFloat::convert(const fltSemantics &toSemantics,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001994 roundingMode rounding_mode, bool *losesInfo)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001995{
Neil Bootha8d72692007-09-22 02:56:19 +00001996 lostFraction lostFraction;
1997 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001998 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001999 int shift;
2000 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00002001
Neil Bootha8d72692007-09-22 02:56:19 +00002002 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002003 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00002004 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002005 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002006
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002007 bool X86SpecialNan = false;
2008 if (&fromSemantics == &APFloat::x87DoubleExtended &&
2009 &toSemantics != &APFloat::x87DoubleExtended && category == fcNaN &&
2010 (!(*significandParts() & 0x8000000000000000ULL) ||
2011 !(*significandParts() & 0x4000000000000000ULL))) {
2012 // x86 has some unusual NaNs which cannot be represented in any other
2013 // format; note them here.
2014 X86SpecialNan = true;
2015 }
2016
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00002017 // If this is a truncation of a denormal number, and the target semantics
2018 // has larger exponent range than the source semantics (this can happen
2019 // when truncating from PowerPC double-double to double format), the
2020 // right shift could lose result mantissa bits. Adjust exponent instead
2021 // of performing excessive shift.
2022 if (shift < 0 && isFiniteNonZero()) {
2023 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
2024 if (exponent + exponentChange < toSemantics.minExponent)
2025 exponentChange = toSemantics.minExponent - exponent;
2026 if (exponentChange < shift)
2027 exponentChange = shift;
2028 if (exponentChange < 0) {
2029 shift -= exponentChange;
2030 exponent += exponentChange;
2031 }
2032 }
2033
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002034 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00002035 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002036 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
2037
2038 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00002039 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002040 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002041 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002042 newParts = new integerPart[newPartCount];
2043 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00002044 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002045 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002046 freeSignificand();
2047 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002048 } else if (newPartCount == 1 && oldPartCount != 1) {
2049 // Switch to built-in storage for a single part.
2050 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00002051 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002052 newPart = significandParts()[0];
2053 freeSignificand();
2054 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002055 }
2056
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002057 // Now that we have the right storage, switch the semantics.
2058 semantics = &toSemantics;
2059
2060 // If this is an extension, perform the shift now that the storage is
2061 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00002062 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002063 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
2064
Michael Gottesman8136c382013-06-26 23:17:28 +00002065 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00002066 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002067 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002068 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002069 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002070
2071 // For x87 extended precision, we want to make a NaN, not a special NaN if
2072 // the input wasn't special either.
2073 if (!X86SpecialNan && semantics == &APFloat::x87DoubleExtended)
2074 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2075
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002076 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2077 // does not give you back the same bits. This is dubious, and we
2078 // don't currently do it. You're really supposed to get
2079 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002080 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002081 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002082 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002083 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002084 }
2085
2086 return fs;
2087}
2088
2089/* Convert a floating point number to an integer according to the
2090 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002091 returns an invalid operation exception and the contents of the
2092 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002093 range but the floating point number is not the exact integer, the C
2094 standard doesn't require an inexact exception to be raised. IEEE
2095 854 does require it so we do that.
2096
2097 Note that for conversions to integer type the C standard requires
2098 round-to-zero to always be used. */
2099APFloat::opStatus
Neil Booth618d0fc2007-11-01 22:43:37 +00002100APFloat::convertToSignExtendedInteger(integerPart *parts, unsigned int width,
2101 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002102 roundingMode rounding_mode,
2103 bool *isExact) const
Neil Booth618d0fc2007-11-01 22:43:37 +00002104{
2105 lostFraction lost_fraction;
2106 const integerPart *src;
2107 unsigned int dstPartsCount, truncatedBits;
2108
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002109 *isExact = false;
2110
Neil Booth618d0fc2007-11-01 22:43:37 +00002111 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002112 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002113 return opInvalidOp;
2114
2115 dstPartsCount = partCountForBits(width);
2116
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002117 if (category == fcZero) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002118 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002119 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002120 *isExact = !sign;
2121 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002122 }
2123
2124 src = significandParts();
2125
2126 /* Step 1: place our absolute value, with any fraction truncated, in
2127 the destination. */
2128 if (exponent < 0) {
2129 /* Our absolute value is less than one; truncate everything. */
2130 APInt::tcSet(parts, 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002131 /* For exponent -1 the integer bit represents .5, look at that.
2132 For smaller exponents leftmost truncated bit is 0. */
2133 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002134 } else {
2135 /* We want the most significant (exponent + 1) bits; the rest are
2136 truncated. */
2137 unsigned int bits = exponent + 1U;
2138
2139 /* Hopelessly large in magnitude? */
2140 if (bits > width)
2141 return opInvalidOp;
2142
2143 if (bits < semantics->precision) {
2144 /* We truncate (semantics->precision - bits) bits. */
2145 truncatedBits = semantics->precision - bits;
2146 APInt::tcExtract(parts, dstPartsCount, src, bits, truncatedBits);
2147 } else {
2148 /* We want at least as many bits as are available. */
2149 APInt::tcExtract(parts, dstPartsCount, src, semantics->precision, 0);
2150 APInt::tcShiftLeft(parts, dstPartsCount, bits - semantics->precision);
2151 truncatedBits = 0;
2152 }
2153 }
2154
2155 /* Step 2: work out any lost fraction, and increment the absolute
2156 value if we would round away from zero. */
2157 if (truncatedBits) {
2158 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2159 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002160 if (lost_fraction != lfExactlyZero &&
2161 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Neil Booth618d0fc2007-11-01 22:43:37 +00002162 if (APInt::tcIncrement(parts, dstPartsCount))
2163 return opInvalidOp; /* Overflow. */
2164 }
2165 } else {
2166 lost_fraction = lfExactlyZero;
2167 }
2168
2169 /* Step 3: check if we fit in the destination. */
2170 unsigned int omsb = APInt::tcMSB(parts, dstPartsCount) + 1;
2171
2172 if (sign) {
2173 if (!isSigned) {
2174 /* Negative numbers cannot be represented as unsigned. */
2175 if (omsb != 0)
2176 return opInvalidOp;
2177 } else {
2178 /* It takes omsb bits to represent the unsigned integer value.
2179 We lose a bit for the sign, but care is needed as the
2180 maximally negative integer is a special case. */
2181 if (omsb == width && APInt::tcLSB(parts, dstPartsCount) + 1 != omsb)
2182 return opInvalidOp;
2183
2184 /* This case can happen because of rounding. */
2185 if (omsb > width)
2186 return opInvalidOp;
2187 }
2188
2189 APInt::tcNegate (parts, dstPartsCount);
2190 } else {
2191 if (omsb >= width + !isSigned)
2192 return opInvalidOp;
2193 }
2194
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002195 if (lost_fraction == lfExactlyZero) {
2196 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002197 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002198 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002199 return opInexact;
2200}
2201
2202/* Same as convertToSignExtendedInteger, except we provide
2203 deterministic values in case of an invalid operation exception,
2204 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002205 for underflow or overflow.
2206 The *isExact output tells whether the result is exact, in the sense
2207 that converting it back to the original floating point type produces
2208 the original value. This is almost equivalent to result==opOK,
2209 except for negative zeroes.
2210*/
Neil Booth618d0fc2007-11-01 22:43:37 +00002211APFloat::opStatus
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002212APFloat::convertToInteger(integerPart *parts, unsigned int width,
Neil Booth9acbf5a2007-09-26 21:33:42 +00002213 bool isSigned,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002214 roundingMode rounding_mode, bool *isExact) const
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002215{
Neil Booth618d0fc2007-11-01 22:43:37 +00002216 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002217
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002218 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002219 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002220
Neil Booth618d0fc2007-11-01 22:43:37 +00002221 if (fs == opInvalidOp) {
2222 unsigned int bits, dstPartsCount;
2223
2224 dstPartsCount = partCountForBits(width);
2225
2226 if (category == fcNaN)
2227 bits = 0;
2228 else if (sign)
2229 bits = isSigned;
2230 else
2231 bits = width - isSigned;
2232
2233 APInt::tcSetLeastSignificantBits(parts, dstPartsCount, bits);
2234 if (sign && isSigned)
2235 APInt::tcShiftLeft(parts, dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002236 }
2237
Neil Booth618d0fc2007-11-01 22:43:37 +00002238 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002239}
2240
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002241/* Same as convertToInteger(integerPart*, ...), except the result is returned in
2242 an APSInt, whose initial bit-width and signed-ness are used to determine the
2243 precision of the conversion.
2244 */
2245APFloat::opStatus
2246APFloat::convertToInteger(APSInt &result,
2247 roundingMode rounding_mode, bool *isExact) const
2248{
2249 unsigned bitWidth = result.getBitWidth();
2250 SmallVector<uint64_t, 4> parts(result.getNumWords());
2251 opStatus status = convertToInteger(
2252 parts.data(), bitWidth, result.isSigned(), rounding_mode, isExact);
2253 // Keeps the original signed-ness.
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002254 result = APInt(bitWidth, parts);
Jeffrey Yasskin03b81a22011-07-15 07:04:56 +00002255 return status;
2256}
2257
Neil Booth6c1c8582007-10-07 12:07:53 +00002258/* Convert an unsigned integer SRC to a floating point number,
2259 rounding according to ROUNDING_MODE. The sign of the floating
2260 point number is not modified. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002261APFloat::opStatus
Neil Booth6c1c8582007-10-07 12:07:53 +00002262APFloat::convertFromUnsignedParts(const integerPart *src,
2263 unsigned int srcCount,
2264 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002265{
Neil Booth49c6aab2007-10-08 14:39:42 +00002266 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002267 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002268 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002269
2270 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002271 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002272 dst = significandParts();
2273 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002274 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002275
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002276 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002277 be that many; extract what we can. */
2278 if (precision <= omsb) {
2279 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002280 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002281 omsb - precision);
2282 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2283 } else {
2284 exponent = precision - 1;
2285 lost_fraction = lfExactlyZero;
2286 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002287 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002288
2289 return normalize(rounding_mode, lost_fraction);
2290}
2291
Dan Gohman35723eb2008-02-29 01:26:11 +00002292APFloat::opStatus
2293APFloat::convertFromAPInt(const APInt &Val,
2294 bool isSigned,
2295 roundingMode rounding_mode)
2296{
2297 unsigned int partCount = Val.getNumWords();
2298 APInt api = Val;
2299
2300 sign = false;
2301 if (isSigned && api.isNegative()) {
2302 sign = true;
2303 api = -api;
2304 }
2305
2306 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2307}
2308
Neil Booth03f58ab2007-10-07 12:15:41 +00002309/* Convert a two's complement integer SRC to a floating point number,
2310 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2311 integer is signed, in which case it must be sign-extended. */
2312APFloat::opStatus
2313APFloat::convertFromSignExtendedInteger(const integerPart *src,
2314 unsigned int srcCount,
2315 bool isSigned,
2316 roundingMode rounding_mode)
2317{
2318 opStatus status;
2319
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002320 if (isSigned &&
2321 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002322 integerPart *copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002323
2324 /* If we're signed and negative negate a copy. */
2325 sign = true;
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002326 copy = new integerPart[srcCount];
Neil Booth03f58ab2007-10-07 12:15:41 +00002327 APInt::tcAssign(copy, src, srcCount);
2328 APInt::tcNegate(copy, srcCount);
2329 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002330 delete [] copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002331 } else {
2332 sign = false;
2333 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2334 }
2335
2336 return status;
2337}
2338
Neil Booth5f009732007-10-07 11:45:55 +00002339/* FIXME: should this just take a const APInt reference? */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002340APFloat::opStatus
Neil Booth5f009732007-10-07 11:45:55 +00002341APFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2342 unsigned int width, bool isSigned,
2343 roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002344{
Dale Johannesen42305122007-09-21 22:09:37 +00002345 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002346 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002347
2348 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002349 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002350 sign = true;
2351 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002352 }
2353
Neil Boothba205222007-10-07 12:10:57 +00002354 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002355}
2356
2357APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002358APFloat::convertFromHexadecimalString(StringRef s, roundingMode rounding_mode)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002359{
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002360 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002361
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002362 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002363 zeroSignificand();
2364 exponent = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002365
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002366 integerPart *significand = significandParts();
2367 unsigned partsCount = partCount();
2368 unsigned bitPos = partsCount * integerPartWidth;
2369 bool computedTrailingFraction = false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002370
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002371 // Skip leading zeroes and any (hexa)decimal point.
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002372 StringRef::iterator begin = s.begin();
2373 StringRef::iterator end = s.end();
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002374 StringRef::iterator dot;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002375 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002376 StringRef::iterator firstSignificantDigit = p;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002377
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002378 while (p != end) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002379 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002380
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002381 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002382 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002383 dot = p++;
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002384 continue;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002385 }
2386
2387 hex_value = hexDigitValue(*p);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002388 if (hex_value == -1U)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002389 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002390
2391 p++;
2392
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002393 // Store the number while we have space.
2394 if (bitPos) {
2395 bitPos -= 4;
2396 hex_value <<= bitPos % integerPartWidth;
2397 significand[bitPos / integerPartWidth] |= hex_value;
2398 } else if (!computedTrailingFraction) {
2399 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2400 computedTrailingFraction = true;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002401 }
2402 }
2403
2404 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002405 assert(p != end && "Hex strings require an exponent");
2406 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2407 assert(p != begin && "Significand has no digits");
2408 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002409
2410 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002411 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002412 int expAdjustment;
2413
2414 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002415 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002416 dot = p;
2417
2418 /* Calculate the exponent adjustment implicit in the number of
2419 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002420 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002421 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002422 expAdjustment++;
2423 expAdjustment = expAdjustment * 4 - 1;
2424
2425 /* Adjust for writing the significand starting at the most
2426 significant nibble. */
2427 expAdjustment += semantics->precision;
2428 expAdjustment -= partsCount * integerPartWidth;
2429
2430 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002431 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002432 }
2433
2434 return normalize(rounding_mode, lost_fraction);
2435}
2436
2437APFloat::opStatus
Neil Boothb93d90e2007-10-12 16:02:31 +00002438APFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2439 unsigned sigPartCount, int exp,
2440 roundingMode rounding_mode)
2441{
2442 unsigned int parts, pow5PartCount;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00002443 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002444 integerPart pow5Parts[maxPowerOfFiveParts];
2445 bool isNearest;
2446
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002447 isNearest = (rounding_mode == rmNearestTiesToEven ||
2448 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002449
2450 parts = partCountForBits(semantics->precision + 11);
2451
2452 /* Calculate pow(5, abs(exp)). */
2453 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2454
2455 for (;; parts *= 2) {
2456 opStatus sigStatus, powStatus;
2457 unsigned int excessPrecision, truncatedBits;
2458
2459 calcSemantics.precision = parts * integerPartWidth - 1;
2460 excessPrecision = calcSemantics.precision - semantics->precision;
2461 truncatedBits = excessPrecision;
2462
Michael Gottesman79b09672013-06-27 21:58:19 +00002463 APFloat decSig = APFloat::getZero(calcSemantics, sign);
2464 APFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002465
2466 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2467 rmNearestTiesToEven);
2468 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2469 rmNearestTiesToEven);
2470 /* Add exp, as 10^n = 5^n * 2^n. */
2471 decSig.exponent += exp;
2472
2473 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002474 integerPart HUerr, HUdistance;
2475 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002476
2477 if (exp >= 0) {
2478 /* multiplySignificand leaves the precision-th bit set to 1. */
Craig Topperc10719f2014-04-07 04:17:22 +00002479 calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
Neil Boothb93d90e2007-10-12 16:02:31 +00002480 powHUerr = powStatus != opOK;
2481 } else {
2482 calcLostFraction = decSig.divideSignificand(pow5);
2483 /* Denormal numbers have less precision. */
2484 if (decSig.exponent < semantics->minExponent) {
2485 excessPrecision += (semantics->minExponent - decSig.exponent);
2486 truncatedBits = excessPrecision;
2487 if (excessPrecision > calcSemantics.precision)
2488 excessPrecision = calcSemantics.precision;
2489 }
2490 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002491 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002492 }
2493
2494 /* Both multiplySignificand and divideSignificand return the
2495 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002496 assert(APInt::tcExtractBit
2497 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002498
2499 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2500 powHUerr);
2501 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2502 excessPrecision, isNearest);
2503
2504 /* Are we guaranteed to round correctly if we truncate? */
2505 if (HUdistance >= HUerr) {
2506 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2507 calcSemantics.precision - excessPrecision,
2508 excessPrecision);
2509 /* Take the exponent of decSig. If we tcExtract-ed less bits
2510 above we must adjust our exponent to compensate for the
2511 implicit right shift. */
2512 exponent = (decSig.exponent + semantics->precision
2513 - (calcSemantics.precision - excessPrecision));
2514 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2515 decSig.partCount(),
2516 truncatedBits);
2517 return normalize(rounding_mode, calcLostFraction);
2518 }
2519 }
2520}
2521
2522APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002523APFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode)
Neil Boothb93d90e2007-10-12 16:02:31 +00002524{
Neil Booth4ed401b2007-10-14 10:16:12 +00002525 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002526 opStatus fs;
2527
Neil Booth4ed401b2007-10-14 10:16:12 +00002528 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002529 StringRef::iterator p = str.begin();
2530 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002531
Neil Booth91305512007-10-15 15:00:55 +00002532 /* Handle the quick cases. First the case of no significant digits,
2533 i.e. zero, and then exponents that are obviously too large or too
2534 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2535 definitely overflows if
2536
2537 (exp - 1) * L >= maxExponent
2538
2539 and definitely underflows to zero where
2540
2541 (exp + 1) * L <= minExponent - precision
2542
2543 With integer arithmetic the tightest bounds for L are
2544
2545 93/28 < L < 196/59 [ numerator <= 256 ]
2546 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2547 */
2548
Michael Gottesman228156c2013-07-01 23:54:08 +00002549 // Test if we have a zero number allowing for strings with no null terminators
2550 // and zero decimals with non-zero exponents.
2551 //
2552 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2553 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2554 // be at most one dot. On the other hand, if we have a zero with a non-zero
2555 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002556 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002557 category = fcZero;
2558 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002559
2560 /* Check whether the normalized exponent is high enough to overflow
2561 max during the log-rebasing in the max-exponent check below. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002562 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
John McCallb42cc682010-02-26 22:20:41 +00002563 fs = handleOverflow(rounding_mode);
2564
2565 /* If it wasn't, then it also wasn't high enough to overflow max
2566 during the log-rebasing in the min-exponent check. Check that it
2567 won't overflow min in either check, then perform the min-exponent
2568 check. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002569 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
John McCallb42cc682010-02-26 22:20:41 +00002570 (D.normalizedExponent + 1) * 28738 <=
2571 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002572 /* Underflow to zero and round. */
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002573 category = fcNormal;
Neil Booth91305512007-10-15 15:00:55 +00002574 zeroSignificand();
2575 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002576
2577 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002578 } else if ((D.normalizedExponent - 1) * 42039
2579 >= 12655 * semantics->maxExponent) {
2580 /* Overflow and round. */
2581 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002582 } else {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002583 integerPart *decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002584 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002585
Neil Booth4ed401b2007-10-14 10:16:12 +00002586 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002587 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002588 to hold the full significand, and an extra part required by
2589 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002590 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002591 partCount = partCountForBits(1 + 196 * partCount / 59);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002592 decSignificand = new integerPart[partCount + 1];
Neil Booth4ed401b2007-10-14 10:16:12 +00002593 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002594
Neil Booth4ed401b2007-10-14 10:16:12 +00002595 /* Convert to binary efficiently - we do almost all multiplication
2596 in an integerPart. When this would overflow do we do a single
2597 bignum multiplication, and then revert again to multiplication
2598 in an integerPart. */
2599 do {
2600 integerPart decValue, val, multiplier;
2601
2602 val = 0;
2603 multiplier = 1;
2604
2605 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002606 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002607 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002608 if (p == str.end()) {
2609 break;
2610 }
2611 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002612 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002613 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002614 multiplier *= 10;
2615 val = val * 10 + decValue;
2616 /* The maximum number that can be multiplied by ten with any
2617 digit added without overflowing an integerPart. */
2618 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2619
2620 /* Multiply out the current part. */
2621 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2622 partCount, partCount + 1, false);
2623
2624 /* If we used another part (likely but not guaranteed), increase
2625 the count. */
2626 if (decSignificand[partCount])
2627 partCount++;
2628 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002629
Neil Boothae077d22007-11-01 22:51:07 +00002630 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002631 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002632 D.exponent, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002633
2634 delete [] decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002635 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002636
2637 return fs;
2638}
2639
Michael Gottesman40e8a182013-06-24 09:58:05 +00002640bool
2641APFloat::convertFromStringSpecials(StringRef str) {
2642 if (str.equals("inf") || str.equals("INFINITY")) {
2643 makeInf(false);
2644 return true;
2645 }
2646
2647 if (str.equals("-inf") || str.equals("-INFINITY")) {
2648 makeInf(true);
2649 return true;
2650 }
2651
2652 if (str.equals("nan") || str.equals("NaN")) {
2653 makeNaN(false, false);
2654 return true;
2655 }
2656
2657 if (str.equals("-nan") || str.equals("-NaN")) {
2658 makeNaN(false, true);
2659 return true;
2660 }
2661
2662 return false;
2663}
2664
Neil Boothb93d90e2007-10-12 16:02:31 +00002665APFloat::opStatus
Benjamin Kramer92d89982010-07-14 22:38:02 +00002666APFloat::convertFromString(StringRef str, roundingMode rounding_mode)
Neil Booth9acbf5a2007-09-26 21:33:42 +00002667{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002668 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002669
Michael Gottesman40e8a182013-06-24 09:58:05 +00002670 // Handle special cases.
2671 if (convertFromStringSpecials(str))
2672 return opOK;
2673
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002674 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002675 StringRef::iterator p = str.begin();
2676 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002677 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002678 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002679 p++;
2680 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002681 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002682 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002683
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002684 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002685 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002686 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002687 rounding_mode);
2688 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002689
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002690 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002691}
Dale Johannesena719a602007-08-24 00:56:33 +00002692
Neil Booth8f1946f2007-10-03 22:26:02 +00002693/* Write out a hexadecimal representation of the floating point value
2694 to DST, which must be of sufficient size, in the C99 form
2695 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2696 excluding the terminating NUL.
2697
2698 If UPPERCASE, the output is in upper case, otherwise in lower case.
2699
2700 HEXDIGITS digits appear altogether, rounding the value if
2701 necessary. If HEXDIGITS is 0, the minimal precision to display the
2702 number precisely is used instead. If nothing would appear after
2703 the decimal point it is suppressed.
2704
2705 The decimal exponent is always printed and has at least one digit.
2706 Zero values display an exponent of zero. Infinities and NaNs
2707 appear as "infinity" or "nan" respectively.
2708
2709 The above rules are as specified by C99. There is ambiguity about
2710 what the leading hexadecimal digit should be. This implementation
2711 uses whatever is necessary so that the exponent is displayed as
2712 stored. This implies the exponent will fall within the IEEE format
2713 range, and the leading hexadecimal digit will be 0 (for denormals),
2714 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2715 any other digits zero).
2716*/
2717unsigned int
2718APFloat::convertToHexString(char *dst, unsigned int hexDigits,
2719 bool upperCase, roundingMode rounding_mode) const
2720{
2721 char *p;
2722
2723 p = dst;
2724 if (sign)
2725 *dst++ = '-';
2726
2727 switch (category) {
2728 case fcInfinity:
2729 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2730 dst += sizeof infinityL - 1;
2731 break;
2732
2733 case fcNaN:
2734 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2735 dst += sizeof NaNU - 1;
2736 break;
2737
2738 case fcZero:
2739 *dst++ = '0';
2740 *dst++ = upperCase ? 'X': 'x';
2741 *dst++ = '0';
2742 if (hexDigits > 1) {
2743 *dst++ = '.';
2744 memset (dst, '0', hexDigits - 1);
2745 dst += hexDigits - 1;
2746 }
2747 *dst++ = upperCase ? 'P': 'p';
2748 *dst++ = '0';
2749 break;
2750
2751 case fcNormal:
2752 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2753 break;
2754 }
2755
2756 *dst = 0;
2757
Evan Cheng82b9e962008-05-02 21:15:08 +00002758 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002759}
2760
2761/* Does the hard work of outputting the correctly rounded hexadecimal
2762 form of a normal floating point number with the specified number of
2763 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2764 digits necessary to print the value precisely is output. */
2765char *
2766APFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2767 bool upperCase,
2768 roundingMode rounding_mode) const
2769{
2770 unsigned int count, valueBits, shift, partsCount, outputDigits;
2771 const char *hexDigitChars;
2772 const integerPart *significand;
2773 char *p;
2774 bool roundUp;
2775
2776 *dst++ = '0';
2777 *dst++ = upperCase ? 'X': 'x';
2778
2779 roundUp = false;
2780 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2781
2782 significand = significandParts();
2783 partsCount = partCount();
2784
2785 /* +3 because the first digit only uses the single integer bit, so
2786 we have 3 virtual zero most-significant-bits. */
2787 valueBits = semantics->precision + 3;
2788 shift = integerPartWidth - valueBits % integerPartWidth;
2789
2790 /* The natural number of digits required ignoring trailing
2791 insignificant zeroes. */
2792 outputDigits = (valueBits - significandLSB () + 3) / 4;
2793
2794 /* hexDigits of zero means use the required number for the
2795 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002796 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002797 if (hexDigits) {
2798 if (hexDigits < outputDigits) {
2799 /* We are dropping non-zero bits, so need to check how to round.
2800 "bits" is the number of dropped bits. */
2801 unsigned int bits;
2802 lostFraction fraction;
2803
2804 bits = valueBits - hexDigits * 4;
2805 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2806 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2807 }
2808 outputDigits = hexDigits;
2809 }
2810
2811 /* Write the digits consecutively, and start writing in the location
2812 of the hexadecimal point. We move the most significant digit
2813 left and add the hexadecimal point later. */
2814 p = ++dst;
2815
2816 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2817
2818 while (outputDigits && count) {
2819 integerPart part;
2820
2821 /* Put the most significant integerPartWidth bits in "part". */
2822 if (--count == partsCount)
2823 part = 0; /* An imaginary higher zero part. */
2824 else
2825 part = significand[count] << shift;
2826
2827 if (count && shift)
2828 part |= significand[count - 1] >> (integerPartWidth - shift);
2829
2830 /* Convert as much of "part" to hexdigits as we can. */
2831 unsigned int curDigits = integerPartWidth / 4;
2832
2833 if (curDigits > outputDigits)
2834 curDigits = outputDigits;
2835 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2836 outputDigits -= curDigits;
2837 }
2838
2839 if (roundUp) {
2840 char *q = dst;
2841
2842 /* Note that hexDigitChars has a trailing '0'. */
2843 do {
2844 q--;
2845 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002846 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002847 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002848 } else {
2849 /* Add trailing zeroes. */
2850 memset (dst, '0', outputDigits);
2851 dst += outputDigits;
2852 }
2853
2854 /* Move the most significant digit to before the point, and if there
2855 is something after the decimal point add it. This must come
2856 after rounding above. */
2857 p[-1] = p[0];
2858 if (dst -1 == p)
2859 dst--;
2860 else
2861 p[0] = '.';
2862
2863 /* Finally output the exponent. */
2864 *dst++ = upperCase ? 'P': 'p';
2865
Neil Booth32897f52007-10-06 07:29:25 +00002866 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002867}
2868
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002869hash_code llvm::hash_value(const APFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002870 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002871 return hash_combine((uint8_t)Arg.category,
2872 // NaN has no sign, fix it at zero.
2873 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2874 Arg.semantics->precision);
2875
2876 // Normal floats need their exponent and significand hashed.
2877 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2878 Arg.semantics->precision, Arg.exponent,
2879 hash_combine_range(
2880 Arg.significandParts(),
2881 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002882}
2883
2884// Conversion from APFloat to/from host float/double. It may eventually be
2885// possible to eliminate these and have everybody deal with APFloats, but that
2886// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002887// Current implementation requires integerPartWidth==64, which is correct at
2888// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002889
Dale Johannesen728687c2007-09-05 20:39:49 +00002890// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002891// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002892
Dale Johannesen245dceb2007-09-11 18:32:33 +00002893APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00002894APFloat::convertF80LongDoubleAPFloatToAPInt() const
2895{
Dan Gohmanb456a152008-01-29 12:08:20 +00002896 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002897 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002898
2899 uint64_t myexponent, mysignificand;
2900
Michael Gottesman8136c382013-06-26 23:17:28 +00002901 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002902 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002903 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002904 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2905 myexponent = 0; // denormal
2906 } else if (category==fcZero) {
2907 myexponent = 0;
2908 mysignificand = 0;
2909 } else if (category==fcInfinity) {
2910 myexponent = 0x7fff;
2911 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002912 } else {
2913 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002914 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002915 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002916 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002917
2918 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002919 words[0] = mysignificand;
2920 words[1] = ((uint64_t)(sign & 1) << 15) |
2921 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002922 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002923}
2924
2925APInt
Dale Johannesen007aa372007-10-11 18:07:22 +00002926APFloat::convertPPCDoubleDoubleAPFloatToAPInt() const
2927{
Dan Gohmanb456a152008-01-29 12:08:20 +00002928 assert(semantics == (const llvm::fltSemantics*)&PPCDoubleDouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002929 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002930
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002931 uint64_t words[2];
2932 opStatus fs;
2933 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002934
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002935 // Convert number to double. To avoid spurious underflows, we re-
2936 // normalize against the "double" minExponent first, and only *then*
2937 // truncate the mantissa. The result of that second conversion
2938 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002939 // Declare fltSemantics before APFloat that uses it (and
2940 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002941 fltSemantics extendedSemantics = *semantics;
2942 extendedSemantics.minExponent = IEEEdouble.minExponent;
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002943 APFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002944 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2945 assert(fs == opOK && !losesInfo);
2946 (void)fs;
2947
2948 APFloat u(extended);
2949 fs = u.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2950 assert(fs == opOK || fs == opInexact);
2951 (void)fs;
2952 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2953
2954 // If conversion was exact or resulted in a special case, we're done;
2955 // just set the second double to zero. Otherwise, re-convert back to
2956 // the extended format and compute the difference. This now should
2957 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002958 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002959 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2960 assert(fs == opOK && !losesInfo);
2961 (void)fs;
2962
2963 APFloat v(extended);
2964 v.subtract(u, rmNearestTiesToEven);
2965 fs = v.convert(IEEEdouble, rmNearestTiesToEven, &losesInfo);
2966 assert(fs == opOK && !losesInfo);
2967 (void)fs;
2968 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002969 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002970 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002971 }
2972
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002973 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002974}
2975
2976APInt
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002977APFloat::convertQuadrupleAPFloatToAPInt() const
2978{
2979 assert(semantics == (const llvm::fltSemantics*)&IEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002980 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002981
2982 uint64_t myexponent, mysignificand, mysignificand2;
2983
Michael Gottesman8136c382013-06-26 23:17:28 +00002984 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002985 myexponent = exponent+16383; //bias
2986 mysignificand = significandParts()[0];
2987 mysignificand2 = significandParts()[1];
2988 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2989 myexponent = 0; // denormal
2990 } else if (category==fcZero) {
2991 myexponent = 0;
2992 mysignificand = mysignificand2 = 0;
2993 } else if (category==fcInfinity) {
2994 myexponent = 0x7fff;
2995 mysignificand = mysignificand2 = 0;
2996 } else {
2997 assert(category == fcNaN && "Unknown category!");
2998 myexponent = 0x7fff;
2999 mysignificand = significandParts()[0];
3000 mysignificand2 = significandParts()[1];
3001 }
3002
3003 uint64_t words[2];
3004 words[0] = mysignificand;
3005 words[1] = ((uint64_t)(sign & 1) << 63) |
3006 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00003007 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003008
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003009 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003010}
3011
3012APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00003013APFloat::convertDoubleAPFloatToAPInt() const
3014{
Dan Gohman58c468f2007-09-14 20:08:19 +00003015 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00003016 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00003017
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003018 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003019
Michael Gottesman8136c382013-06-26 23:17:28 +00003020 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00003021 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003022 mysignificand = *significandParts();
3023 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
3024 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00003025 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00003026 myexponent = 0;
3027 mysignificand = 0;
3028 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00003029 myexponent = 0x7ff;
3030 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003031 } else {
3032 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00003033 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003034 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003035 }
Dale Johannesena719a602007-08-24 00:56:33 +00003036
Evan Cheng82b9e962008-05-02 21:15:08 +00003037 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003038 ((myexponent & 0x7ff) << 52) |
3039 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00003040}
3041
Dale Johannesen245dceb2007-09-11 18:32:33 +00003042APInt
Neil Booth9acbf5a2007-09-26 21:33:42 +00003043APFloat::convertFloatAPFloatToAPInt() const
3044{
Dan Gohman58c468f2007-09-14 20:08:19 +00003045 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00003046 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00003047
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003048 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003049
Michael Gottesman8136c382013-06-26 23:17:28 +00003050 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00003051 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00003052 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00003053 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00003054 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00003055 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00003056 myexponent = 0;
3057 mysignificand = 0;
3058 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00003059 myexponent = 0xff;
3060 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003061 } else {
3062 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00003063 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00003064 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003065 }
Dale Johannesena719a602007-08-24 00:56:33 +00003066
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003067 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
3068 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00003069}
3070
Chris Lattner4794b2b2009-10-16 02:13:51 +00003071APInt
3072APFloat::convertHalfAPFloatToAPInt() const
3073{
3074 assert(semantics == (const llvm::fltSemantics*)&IEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00003075 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003076
3077 uint32_t myexponent, mysignificand;
3078
Michael Gottesman8136c382013-06-26 23:17:28 +00003079 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003080 myexponent = exponent+15; //bias
3081 mysignificand = (uint32_t)*significandParts();
3082 if (myexponent == 1 && !(mysignificand & 0x400))
3083 myexponent = 0; // denormal
3084 } else if (category==fcZero) {
3085 myexponent = 0;
3086 mysignificand = 0;
3087 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00003088 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003089 mysignificand = 0;
3090 } else {
3091 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00003092 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003093 mysignificand = (uint32_t)*significandParts();
3094 }
3095
3096 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
3097 (mysignificand & 0x3ff)));
3098}
3099
Dale Johannesen007aa372007-10-11 18:07:22 +00003100// This function creates an APInt that is just a bit map of the floating
3101// point constant as it would appear in memory. It is not a conversion,
3102// and treating the result as a normal integer is unlikely to be useful.
3103
Dale Johannesen245dceb2007-09-11 18:32:33 +00003104APInt
Dale Johannesen54306fe2008-10-09 18:53:47 +00003105APFloat::bitcastToAPInt() const
Neil Booth9acbf5a2007-09-26 21:33:42 +00003106{
Chris Lattner4794b2b2009-10-16 02:13:51 +00003107 if (semantics == (const llvm::fltSemantics*)&IEEEhalf)
3108 return convertHalfAPFloatToAPInt();
3109
Dan Gohmanb456a152008-01-29 12:08:20 +00003110 if (semantics == (const llvm::fltSemantics*)&IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003111 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003112
Dan Gohmanb456a152008-01-29 12:08:20 +00003113 if (semantics == (const llvm::fltSemantics*)&IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003114 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003115
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003116 if (semantics == (const llvm::fltSemantics*)&IEEEquad)
3117 return convertQuadrupleAPFloatToAPInt();
3118
Dan Gohmanb456a152008-01-29 12:08:20 +00003119 if (semantics == (const llvm::fltSemantics*)&PPCDoubleDouble)
Dale Johannesen007aa372007-10-11 18:07:22 +00003120 return convertPPCDoubleDoubleAPFloatToAPInt();
3121
Dan Gohmanb456a152008-01-29 12:08:20 +00003122 assert(semantics == (const llvm::fltSemantics*)&x87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003123 "unknown format!");
3124 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003125}
3126
Neil Booth9acbf5a2007-09-26 21:33:42 +00003127float
3128APFloat::convertToFloat() const
3129{
Chris Lattner688f9912009-09-24 21:44:20 +00003130 assert(semantics == (const llvm::fltSemantics*)&IEEEsingle &&
3131 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003132 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003133 return api.bitsToFloat();
3134}
3135
Neil Booth9acbf5a2007-09-26 21:33:42 +00003136double
3137APFloat::convertToDouble() const
3138{
Chris Lattner688f9912009-09-24 21:44:20 +00003139 assert(semantics == (const llvm::fltSemantics*)&IEEEdouble &&
3140 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003141 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003142 return api.bitsToDouble();
3143}
3144
Dale Johannesenfff29952008-10-06 18:22:29 +00003145/// Integer bit is explicit in this format. Intel hardware (387 and later)
3146/// does not support these bit patterns:
3147/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3148/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
3149/// exponent = 0, integer bit 1 ("pseudodenormal")
3150/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
3151/// At the moment, the first two are treated as NaNs, the second two as Normal.
Dale Johannesen245dceb2007-09-11 18:32:33 +00003152void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003153APFloat::initFromF80LongDoubleAPInt(const APInt &api)
3154{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003155 assert(api.getBitWidth()==80);
3156 uint64_t i1 = api.getRawData()[0];
3157 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003158 uint64_t myexponent = (i2 & 0x7fff);
3159 uint64_t mysignificand = i1;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003160
3161 initialize(&APFloat::x87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003162 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003163
Dale Johannesen93eefa02009-03-23 21:16:53 +00003164 sign = static_cast<unsigned int>(i2>>15);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003165 if (myexponent==0 && mysignificand==0) {
3166 // exponent, significand meaningless
3167 category = fcZero;
3168 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3169 // exponent, significand meaningless
3170 category = fcInfinity;
3171 } else if (myexponent==0x7fff && mysignificand!=0x8000000000000000ULL) {
3172 // exponent meaningless
3173 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003174 significandParts()[0] = mysignificand;
3175 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003176 } else {
3177 category = fcNormal;
3178 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003179 significandParts()[0] = mysignificand;
3180 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003181 if (myexponent==0) // denormal
3182 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003183 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003184}
3185
3186void
Dale Johannesen007aa372007-10-11 18:07:22 +00003187APFloat::initFromPPCDoubleDoubleAPInt(const APInt &api)
3188{
3189 assert(api.getBitWidth()==128);
3190 uint64_t i1 = api.getRawData()[0];
3191 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003192 opStatus fs;
3193 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003194
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003195 // Get the first double and convert to our format.
3196 initFromDoubleAPInt(APInt(64, i1));
3197 fs = convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3198 assert(fs == opOK && !losesInfo);
3199 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003200
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003201 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003202 if (isFiniteNonZero()) {
Tim Northover29178a32013-01-22 09:46:31 +00003203 APFloat v(IEEEdouble, APInt(64, i2));
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003204 fs = v.convert(PPCDoubleDouble, rmNearestTiesToEven, &losesInfo);
3205 assert(fs == opOK && !losesInfo);
3206 (void)fs;
3207
3208 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003209 }
3210}
3211
3212void
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003213APFloat::initFromQuadrupleAPInt(const APInt &api)
3214{
3215 assert(api.getBitWidth()==128);
3216 uint64_t i1 = api.getRawData()[0];
3217 uint64_t i2 = api.getRawData()[1];
3218 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3219 uint64_t mysignificand = i1;
3220 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3221
3222 initialize(&APFloat::IEEEquad);
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003223 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003224
3225 sign = static_cast<unsigned int>(i2>>63);
3226 if (myexponent==0 &&
3227 (mysignificand==0 && mysignificand2==0)) {
3228 // exponent, significand meaningless
3229 category = fcZero;
3230 } else if (myexponent==0x7fff &&
3231 (mysignificand==0 && mysignificand2==0)) {
3232 // exponent, significand meaningless
3233 category = fcInfinity;
3234 } else if (myexponent==0x7fff &&
3235 (mysignificand!=0 || mysignificand2 !=0)) {
3236 // exponent meaningless
3237 category = fcNaN;
3238 significandParts()[0] = mysignificand;
3239 significandParts()[1] = mysignificand2;
3240 } else {
3241 category = fcNormal;
3242 exponent = myexponent - 16383;
3243 significandParts()[0] = mysignificand;
3244 significandParts()[1] = mysignificand2;
3245 if (myexponent==0) // denormal
3246 exponent = -16382;
3247 else
3248 significandParts()[1] |= 0x1000000000000LL; // integer bit
3249 }
3250}
3251
3252void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003253APFloat::initFromDoubleAPInt(const APInt &api)
3254{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003255 assert(api.getBitWidth()==64);
3256 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003257 uint64_t myexponent = (i >> 52) & 0x7ff;
3258 uint64_t mysignificand = i & 0xfffffffffffffLL;
3259
Dale Johannesena719a602007-08-24 00:56:33 +00003260 initialize(&APFloat::IEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003261 assert(partCount()==1);
3262
Evan Cheng82b9e962008-05-02 21:15:08 +00003263 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003264 if (myexponent==0 && mysignificand==0) {
3265 // exponent, significand meaningless
3266 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003267 } else if (myexponent==0x7ff && mysignificand==0) {
3268 // exponent, significand meaningless
3269 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003270 } else if (myexponent==0x7ff && mysignificand!=0) {
3271 // exponent meaningless
3272 category = fcNaN;
3273 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003274 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003275 category = fcNormal;
3276 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003277 *significandParts() = mysignificand;
3278 if (myexponent==0) // denormal
3279 exponent = -1022;
3280 else
3281 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003282 }
Dale Johannesena719a602007-08-24 00:56:33 +00003283}
3284
Dale Johannesen245dceb2007-09-11 18:32:33 +00003285void
Neil Booth9acbf5a2007-09-26 21:33:42 +00003286APFloat::initFromFloatAPInt(const APInt & api)
3287{
Dale Johannesen245dceb2007-09-11 18:32:33 +00003288 assert(api.getBitWidth()==32);
3289 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003290 uint32_t myexponent = (i >> 23) & 0xff;
3291 uint32_t mysignificand = i & 0x7fffff;
3292
Dale Johannesena719a602007-08-24 00:56:33 +00003293 initialize(&APFloat::IEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003294 assert(partCount()==1);
3295
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003296 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003297 if (myexponent==0 && mysignificand==0) {
3298 // exponent, significand meaningless
3299 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003300 } else if (myexponent==0xff && mysignificand==0) {
3301 // exponent, significand meaningless
3302 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003303 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003304 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003305 category = fcNaN;
3306 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003307 } else {
3308 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003309 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003310 *significandParts() = mysignificand;
3311 if (myexponent==0) // denormal
3312 exponent = -126;
3313 else
3314 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003315 }
3316}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003317
Chris Lattner4794b2b2009-10-16 02:13:51 +00003318void
3319APFloat::initFromHalfAPInt(const APInt & api)
3320{
3321 assert(api.getBitWidth()==16);
3322 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003323 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003324 uint32_t mysignificand = i & 0x3ff;
3325
3326 initialize(&APFloat::IEEEhalf);
3327 assert(partCount()==1);
3328
3329 sign = i >> 15;
3330 if (myexponent==0 && mysignificand==0) {
3331 // exponent, significand meaningless
3332 category = fcZero;
3333 } else if (myexponent==0x1f && mysignificand==0) {
3334 // exponent, significand meaningless
3335 category = fcInfinity;
3336 } else if (myexponent==0x1f && mysignificand!=0) {
3337 // sign, exponent, significand meaningless
3338 category = fcNaN;
3339 *significandParts() = mysignificand;
3340 } else {
3341 category = fcNormal;
3342 exponent = myexponent - 15; //bias
3343 *significandParts() = mysignificand;
3344 if (myexponent==0) // denormal
3345 exponent = -14;
3346 else
3347 *significandParts() |= 0x400; // integer bit
3348 }
3349}
3350
Dale Johannesen245dceb2007-09-11 18:32:33 +00003351/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003352/// we infer the floating point type from the size of the APInt. The
3353/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3354/// when the size is anything else).
Dale Johannesen245dceb2007-09-11 18:32:33 +00003355void
Tim Northover29178a32013-01-22 09:46:31 +00003356APFloat::initFromAPInt(const fltSemantics* Sem, const APInt& api)
Neil Booth9acbf5a2007-09-26 21:33:42 +00003357{
Tim Northover29178a32013-01-22 09:46:31 +00003358 if (Sem == &IEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003359 return initFromHalfAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003360 if (Sem == &IEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003361 return initFromFloatAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003362 if (Sem == &IEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003363 return initFromDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003364 if (Sem == &x87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003365 return initFromF80LongDoubleAPInt(api);
Tim Northover29178a32013-01-22 09:46:31 +00003366 if (Sem == &IEEEquad)
3367 return initFromQuadrupleAPInt(api);
3368 if (Sem == &PPCDoubleDouble)
3369 return initFromPPCDoubleDoubleAPInt(api);
3370
Craig Topper2617dcc2014-04-15 06:32:26 +00003371 llvm_unreachable(nullptr);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003372}
3373
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003374APFloat
3375APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE)
3376{
Tim Northover29178a32013-01-22 09:46:31 +00003377 switch (BitWidth) {
3378 case 16:
3379 return APFloat(IEEEhalf, APInt::getAllOnesValue(BitWidth));
3380 case 32:
3381 return APFloat(IEEEsingle, APInt::getAllOnesValue(BitWidth));
3382 case 64:
3383 return APFloat(IEEEdouble, APInt::getAllOnesValue(BitWidth));
3384 case 80:
3385 return APFloat(x87DoubleExtended, APInt::getAllOnesValue(BitWidth));
3386 case 128:
3387 if (isIEEE)
3388 return APFloat(IEEEquad, APInt::getAllOnesValue(BitWidth));
3389 return APFloat(PPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
3390 default:
3391 llvm_unreachable("Unknown floating bit width");
3392 }
Nadav Rotem7cc6d122011-02-17 21:22:27 +00003393}
3394
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00003395unsigned APFloat::getSizeInBits(const fltSemantics &Sem) {
3396 return Sem.sizeInBits;
3397}
3398
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003399/// Make this number the largest magnitude normal number in the given
3400/// semantics.
3401void APFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003402 // We want (in interchange format):
3403 // sign = {Negative}
3404 // exponent = 1..10
3405 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003406 category = fcNormal;
3407 sign = Negative;
3408 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003409
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003410 // Use memset to set all but the highest integerPart to all ones.
3411 integerPart *significand = significandParts();
3412 unsigned PartCount = partCount();
3413 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003414
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003415 // Set the high integerPart especially setting all unused top bits for
3416 // internal consistency.
3417 const unsigned NumUnusedHighBits =
3418 PartCount*integerPartWidth - semantics->precision;
Alexey Samsonovba1ecbc2014-09-06 00:41:19 +00003419 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3420 ? (~integerPart(0) >> NumUnusedHighBits)
3421 : 0;
John McCall29b5c282009-12-24 08:56:26 +00003422}
3423
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003424/// Make this number the smallest magnitude denormal number in the given
3425/// semantics.
3426void APFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003427 // We want (in interchange format):
3428 // sign = {Negative}
3429 // exponent = 0..0
3430 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003431 category = fcNormal;
3432 sign = Negative;
3433 exponent = semantics->minExponent;
3434 APInt::tcSet(significandParts(), 1, partCount());
3435}
John McCall29b5c282009-12-24 08:56:26 +00003436
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003437
3438APFloat APFloat::getLargest(const fltSemantics &Sem, bool Negative) {
3439 // We want (in interchange format):
3440 // sign = {Negative}
3441 // exponent = 1..10
3442 // significand = 1..1
3443 APFloat Val(Sem, uninitialized);
3444 Val.makeLargest(Negative);
3445 return Val;
3446}
3447
3448APFloat APFloat::getSmallest(const fltSemantics &Sem, bool Negative) {
3449 // We want (in interchange format):
3450 // sign = {Negative}
3451 // exponent = 0..0
3452 // significand = 0..01
3453 APFloat Val(Sem, uninitialized);
3454 Val.makeSmallest(Negative);
John McCall29b5c282009-12-24 08:56:26 +00003455 return Val;
3456}
3457
3458APFloat APFloat::getSmallestNormalized(const fltSemantics &Sem, bool Negative) {
Michael Gottesman79b09672013-06-27 21:58:19 +00003459 APFloat Val(Sem, uninitialized);
John McCall29b5c282009-12-24 08:56:26 +00003460
3461 // We want (in interchange format):
3462 // sign = {Negative}
3463 // exponent = 0..0
3464 // significand = 10..0
3465
Michael Gottesman30a90eb2013-07-27 21:49:21 +00003466 Val.category = fcNormal;
Michael Gottesmanccaf3322013-06-27 20:40:11 +00003467 Val.zeroSignificand();
Michael Gottesman79b09672013-06-27 21:58:19 +00003468 Val.sign = Negative;
3469 Val.exponent = Sem.minExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003470 Val.significandParts()[partCountForBits(Sem.precision)-1] |=
Eli Friedmand4330422011-10-12 21:56:19 +00003471 (((integerPart) 1) << ((Sem.precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003472
3473 return Val;
3474}
3475
Tim Northover29178a32013-01-22 09:46:31 +00003476APFloat::APFloat(const fltSemantics &Sem, const APInt &API) {
3477 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003478}
3479
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003480APFloat::APFloat(float f) {
Tim Northover29178a32013-01-22 09:46:31 +00003481 initFromAPInt(&IEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003482}
3483
Ulrich Weigande1d62f92012-10-29 18:17:42 +00003484APFloat::APFloat(double d) {
Tim Northover29178a32013-01-22 09:46:31 +00003485 initFromAPInt(&IEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003486}
John McCall29b5c282009-12-24 08:56:26 +00003487
3488namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003489 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3490 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003491 }
3492
John McCalle6212ace2009-12-24 12:16:56 +00003493 /// Removes data from the given significand until it is no more
3494 /// precise than is required for the desired precision.
3495 void AdjustToPrecision(APInt &significand,
3496 int &exp, unsigned FormatPrecision) {
3497 unsigned bits = significand.getActiveBits();
3498
3499 // 196/59 is a very slight overestimate of lg_2(10).
3500 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3501
3502 if (bits <= bitsRequired) return;
3503
3504 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3505 if (!tensRemovable) return;
3506
3507 exp += tensRemovable;
3508
3509 APInt divisor(significand.getBitWidth(), 1);
3510 APInt powten(significand.getBitWidth(), 10);
3511 while (true) {
3512 if (tensRemovable & 1)
3513 divisor *= powten;
3514 tensRemovable >>= 1;
3515 if (!tensRemovable) break;
3516 powten *= powten;
3517 }
3518
3519 significand = significand.udiv(divisor);
3520
Hao Liube99cc32013-03-20 01:46:36 +00003521 // Truncate the significand down to its active bit count.
3522 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003523 }
3524
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003525
John McCall29b5c282009-12-24 08:56:26 +00003526 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3527 int &exp, unsigned FormatPrecision) {
3528 unsigned N = buffer.size();
3529 if (N <= FormatPrecision) return;
3530
3531 // The most significant figures are the last ones in the buffer.
3532 unsigned FirstSignificant = N - FormatPrecision;
3533
3534 // Round.
3535 // FIXME: this probably shouldn't use 'round half up'.
3536
3537 // Rounding down is just a truncation, except we also want to drop
3538 // trailing zeros from the new result.
3539 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003540 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003541 FirstSignificant++;
3542
3543 exp += FirstSignificant;
3544 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3545 return;
3546 }
3547
3548 // Rounding up requires a decimal add-with-carry. If we continue
3549 // the carry, the newly-introduced zeros will just be truncated.
3550 for (unsigned I = FirstSignificant; I != N; ++I) {
3551 if (buffer[I] == '9') {
3552 FirstSignificant++;
3553 } else {
3554 buffer[I]++;
3555 break;
3556 }
3557 }
3558
3559 // If we carried through, we have exactly one digit of precision.
3560 if (FirstSignificant == N) {
3561 exp += FirstSignificant;
3562 buffer.clear();
3563 buffer.push_back('1');
3564 return;
3565 }
3566
3567 exp += FirstSignificant;
3568 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3569 }
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003570}
John McCall29b5c282009-12-24 08:56:26 +00003571
3572void APFloat::toString(SmallVectorImpl<char> &Str,
3573 unsigned FormatPrecision,
Chris Lattner4c1e4db2010-03-06 19:20:13 +00003574 unsigned FormatMaxPadding) const {
John McCall29b5c282009-12-24 08:56:26 +00003575 switch (category) {
3576 case fcInfinity:
3577 if (isNegative())
3578 return append(Str, "-Inf");
3579 else
3580 return append(Str, "+Inf");
3581
3582 case fcNaN: return append(Str, "NaN");
3583
3584 case fcZero:
3585 if (isNegative())
3586 Str.push_back('-');
3587
3588 if (!FormatMaxPadding)
3589 append(Str, "0.0E+0");
3590 else
3591 Str.push_back('0');
3592 return;
3593
3594 case fcNormal:
3595 break;
3596 }
3597
3598 if (isNegative())
3599 Str.push_back('-');
3600
3601 // Decompose the number into an APInt and an exponent.
3602 int exp = exponent - ((int) semantics->precision - 1);
3603 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003604 makeArrayRef(significandParts(),
3605 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003606
John McCalldd5044a2009-12-24 23:18:09 +00003607 // Set FormatPrecision if zero. We want to do this before we
3608 // truncate trailing zeros, as those are part of the precision.
3609 if (!FormatPrecision) {
Eli Friedmane72f1322013-08-29 23:44:34 +00003610 // We use enough digits so the number can be round-tripped back to an
3611 // APFloat. The formula comes from "How to Print Floating-Point Numbers
3612 // Accurately" by Steele and White.
3613 // FIXME: Using a formula based purely on the precision is conservative;
3614 // we can print fewer digits depending on the actual value being printed.
John McCalldd5044a2009-12-24 23:18:09 +00003615
Eli Friedmane72f1322013-08-29 23:44:34 +00003616 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3617 FormatPrecision = 2 + semantics->precision * 59 / 196;
John McCalldd5044a2009-12-24 23:18:09 +00003618 }
3619
John McCall29b5c282009-12-24 08:56:26 +00003620 // Ignore trailing binary zeros.
3621 int trailingZeros = significand.countTrailingZeros();
3622 exp += trailingZeros;
3623 significand = significand.lshr(trailingZeros);
3624
3625 // Change the exponent from 2^e to 10^e.
3626 if (exp == 0) {
3627 // Nothing to do.
3628 } else if (exp > 0) {
3629 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003630 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003631 significand <<= exp;
3632 exp = 0;
3633 } else { /* exp < 0 */
3634 int texp = -exp;
3635
3636 // We transform this using the identity:
3637 // (N)(2^-e) == (N)(5^e)(10^-e)
3638 // This means we have to multiply N (the significand) by 5^e.
3639 // To avoid overflow, we have to operate on numbers large
3640 // enough to store N * 5^e:
3641 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003642 // <= semantics->precision + e * 137 / 59
3643 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003644
Eli Friedman19546412011-10-07 23:40:49 +00003645 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003646
3647 // Multiply significand by 5^e.
3648 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003649 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003650 APInt five_to_the_i(precision, 5);
3651 while (true) {
3652 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003653
John McCall29b5c282009-12-24 08:56:26 +00003654 texp >>= 1;
3655 if (!texp) break;
3656 five_to_the_i *= five_to_the_i;
3657 }
3658 }
3659
John McCalle6212ace2009-12-24 12:16:56 +00003660 AdjustToPrecision(significand, exp, FormatPrecision);
3661
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003662 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003663
3664 // Fill the buffer.
3665 unsigned precision = significand.getBitWidth();
3666 APInt ten(precision, 10);
3667 APInt digit(precision, 0);
3668
3669 bool inTrail = true;
3670 while (significand != 0) {
3671 // digit <- significand % 10
3672 // significand <- significand / 10
3673 APInt::udivrem(significand, ten, significand, digit);
3674
3675 unsigned d = digit.getZExtValue();
3676
3677 // Drop trailing zeros.
3678 if (inTrail && !d) exp++;
3679 else {
3680 buffer.push_back((char) ('0' + d));
3681 inTrail = false;
3682 }
3683 }
3684
3685 assert(!buffer.empty() && "no characters in buffer!");
3686
3687 // Drop down to FormatPrecision.
3688 // TODO: don't do more precise calculations above than are required.
3689 AdjustToPrecision(buffer, exp, FormatPrecision);
3690
3691 unsigned NDigits = buffer.size();
3692
John McCalldd5044a2009-12-24 23:18:09 +00003693 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003694 bool FormatScientific;
3695 if (!FormatMaxPadding)
3696 FormatScientific = true;
3697 else {
John McCall29b5c282009-12-24 08:56:26 +00003698 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003699 // 765e3 --> 765000
3700 // ^^^
3701 // But we shouldn't make the number look more precise than it is.
3702 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3703 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003704 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003705 // Power of the most significant digit.
3706 int MSD = exp + (int) (NDigits - 1);
3707 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003708 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003709 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003710 } else {
3711 // 765e-5 == 0.00765
3712 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003713 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003714 }
3715 }
John McCall29b5c282009-12-24 08:56:26 +00003716 }
3717
3718 // Scientific formatting is pretty straightforward.
3719 if (FormatScientific) {
3720 exp += (NDigits - 1);
3721
3722 Str.push_back(buffer[NDigits-1]);
3723 Str.push_back('.');
3724 if (NDigits == 1)
3725 Str.push_back('0');
3726 else
3727 for (unsigned I = 1; I != NDigits; ++I)
3728 Str.push_back(buffer[NDigits-1-I]);
3729 Str.push_back('E');
3730
3731 Str.push_back(exp >= 0 ? '+' : '-');
3732 if (exp < 0) exp = -exp;
3733 SmallVector<char, 6> expbuf;
3734 do {
3735 expbuf.push_back((char) ('0' + (exp % 10)));
3736 exp /= 10;
3737 } while (exp);
3738 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3739 Str.push_back(expbuf[E-1-I]);
3740 return;
3741 }
3742
3743 // Non-scientific, positive exponents.
3744 if (exp >= 0) {
3745 for (unsigned I = 0; I != NDigits; ++I)
3746 Str.push_back(buffer[NDigits-1-I]);
3747 for (unsigned I = 0; I != (unsigned) exp; ++I)
3748 Str.push_back('0');
3749 return;
3750 }
3751
3752 // Non-scientific, negative exponents.
3753
3754 // The number of digits to the left of the decimal point.
3755 int NWholeDigits = exp + (int) NDigits;
3756
3757 unsigned I = 0;
3758 if (NWholeDigits > 0) {
3759 for (; I != (unsigned) NWholeDigits; ++I)
3760 Str.push_back(buffer[NDigits-I-1]);
3761 Str.push_back('.');
3762 } else {
3763 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3764
3765 Str.push_back('0');
3766 Str.push_back('.');
3767 for (unsigned Z = 1; Z != NZeros; ++Z)
3768 Str.push_back('0');
3769 }
3770
3771 for (; I != NDigits; ++I)
3772 Str.push_back(buffer[NDigits-I-1]);
3773}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003774
3775bool APFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003776 // Special floats and denormals have no exact inverse.
Michael Gottesman8136c382013-06-26 23:17:28 +00003777 if (!isFiniteNonZero())
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003778 return false;
3779
3780 // Check that the number is a power of two by making sure that only the
3781 // integer bit is set in the significand.
3782 if (significandLSB() != semantics->precision - 1)
3783 return false;
3784
3785 // Get the inverse.
3786 APFloat reciprocal(*semantics, 1ULL);
3787 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3788 return false;
3789
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003790 // Avoid multiplication with a denormal, it is not safe on all platforms and
3791 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003792 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003793 return false;
3794
Michael Gottesman8136c382013-06-26 23:17:28 +00003795 assert(reciprocal.isFiniteNonZero() &&
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003796 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3797
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003798 if (inv)
3799 *inv = reciprocal;
3800
3801 return true;
3802}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003803
3804bool APFloat::isSignaling() const {
3805 if (!isNaN())
3806 return false;
3807
3808 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3809 // first bit of the trailing significand being 0.
3810 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3811}
3812
3813/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3814///
3815/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3816/// appropriate sign switching before/after the computation.
3817APFloat::opStatus APFloat::next(bool nextDown) {
3818 // If we are performing nextDown, swap sign so we have -x.
3819 if (nextDown)
3820 changeSign();
3821
3822 // Compute nextUp(x)
3823 opStatus result = opOK;
3824
3825 // Handle each float category separately.
3826 switch (category) {
3827 case fcInfinity:
3828 // nextUp(+inf) = +inf
3829 if (!isNegative())
3830 break;
3831 // nextUp(-inf) = -getLargest()
3832 makeLargest(true);
3833 break;
3834 case fcNaN:
3835 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3836 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3837 // change the payload.
3838 if (isSignaling()) {
3839 result = opInvalidOp;
Alp Tokercb402912014-01-24 17:20:08 +00003840 // For consistency, propagate the sign of the sNaN to the qNaN.
Craig Topperc10719f2014-04-07 04:17:22 +00003841 makeNaN(false, isNegative(), nullptr);
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003842 }
3843 break;
3844 case fcZero:
3845 // nextUp(pm 0) = +getSmallest()
3846 makeSmallest(false);
3847 break;
3848 case fcNormal:
3849 // nextUp(-getSmallest()) = -0
3850 if (isSmallest() && isNegative()) {
3851 APInt::tcSet(significandParts(), 0, partCount());
3852 category = fcZero;
3853 exponent = 0;
3854 break;
3855 }
3856
3857 // nextUp(getLargest()) == INFINITY
3858 if (isLargest() && !isNegative()) {
3859 APInt::tcSet(significandParts(), 0, partCount());
3860 category = fcInfinity;
3861 exponent = semantics->maxExponent + 1;
3862 break;
3863 }
3864
3865 // nextUp(normal) == normal + inc.
3866 if (isNegative()) {
3867 // If we are negative, we need to decrement the significand.
3868
3869 // We only cross a binade boundary that requires adjusting the exponent
3870 // if:
3871 // 1. exponent != semantics->minExponent. This implies we are not in the
3872 // smallest binade or are dealing with denormals.
3873 // 2. Our significand excluding the integral bit is all zeros.
3874 bool WillCrossBinadeBoundary =
3875 exponent != semantics->minExponent && isSignificandAllZeros();
3876
3877 // Decrement the significand.
3878 //
3879 // We always do this since:
Alp Tokerf907b892013-12-05 05:44:44 +00003880 // 1. If we are dealing with a non-binade decrement, by definition we
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003881 // just decrement the significand.
3882 // 2. If we are dealing with a normal -> normal binade decrement, since
3883 // we have an explicit integral bit the fact that all bits but the
3884 // integral bit are zero implies that subtracting one will yield a
3885 // significand with 0 integral bit and 1 in all other spots. Thus we
3886 // must just adjust the exponent and set the integral bit to 1.
3887 // 3. If we are dealing with a normal -> denormal binade decrement,
3888 // since we set the integral bit to 0 when we represent denormals, we
3889 // just decrement the significand.
3890 integerPart *Parts = significandParts();
3891 APInt::tcDecrement(Parts, partCount());
3892
3893 if (WillCrossBinadeBoundary) {
3894 // Our result is a normal number. Do the following:
3895 // 1. Set the integral bit to 1.
3896 // 2. Decrement the exponent.
3897 APInt::tcSetBit(Parts, semantics->precision - 1);
3898 exponent--;
3899 }
3900 } else {
3901 // If we are positive, we need to increment the significand.
3902
3903 // We only cross a binade boundary that requires adjusting the exponent if
3904 // the input is not a denormal and all of said input's significand bits
3905 // are set. If all of said conditions are true: clear the significand, set
3906 // the integral bit to 1, and increment the exponent. If we have a
3907 // denormal always increment since moving denormals and the numbers in the
3908 // smallest normal binade have the same exponent in our representation.
3909 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3910
3911 if (WillCrossBinadeBoundary) {
3912 integerPart *Parts = significandParts();
3913 APInt::tcSet(Parts, 0, partCount());
3914 APInt::tcSetBit(Parts, semantics->precision - 1);
3915 assert(exponent != semantics->maxExponent &&
3916 "We can not increment an exponent beyond the maxExponent allowed"
3917 " by the given floating point semantics.");
3918 exponent++;
3919 } else {
3920 incrementSignificand();
3921 }
3922 }
3923 break;
3924 }
3925
3926 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3927 if (nextDown)
3928 changeSign();
3929
3930 return result;
3931}
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003932
3933void
3934APFloat::makeInf(bool Negative) {
3935 category = fcInfinity;
3936 sign = Negative;
3937 exponent = semantics->maxExponent + 1;
3938 APInt::tcSet(significandParts(), 0, partCount());
3939}
3940
3941void
3942APFloat::makeZero(bool Negative) {
3943 category = fcZero;
3944 sign = Negative;
3945 exponent = semantics->minExponent-1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003946 APInt::tcSet(significandParts(), 0, partCount());
3947}
3948
3949void APFloat::makeQuiet() {
3950 assert(isNaN());
3951 APInt::tcSetBit(significandParts(), semantics->precision - 2);
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003952}
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003953
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003954int llvm::ilogb(const APFloat &Arg) {
3955 if (Arg.isNaN())
3956 return APFloat::IEK_NaN;
3957 if (Arg.isZero())
3958 return APFloat::IEK_Zero;
3959 if (Arg.isInfinity())
3960 return APFloat::IEK_Inf;
3961 if (!Arg.isDenormal())
3962 return Arg.exponent;
3963
3964 APFloat Normalized(Arg);
3965 int SignificandBits = Arg.getSemantics().precision - 1;
3966
3967 Normalized.exponent += SignificandBits;
3968 Normalized.normalize(APFloat::rmNearestTiesToEven, lfExactlyZero);
3969 return Normalized.exponent - SignificandBits;
3970}
3971
Matt Arsenaultafa31cf2016-03-13 05:11:51 +00003972APFloat llvm::scalbn(APFloat X, int Exp, APFloat::roundingMode RoundingMode) {
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003973 auto MaxExp = X.getSemantics().maxExponent;
3974 auto MinExp = X.getSemantics().minExponent;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003975
Matt Arsenaultafa31cf2016-03-13 05:11:51 +00003976 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
3977 // overflow; clamp it to a safe range before adding, but ensure that the range
3978 // is large enough that the clamp does not change the result. The range we
3979 // need to support is the difference between the largest possible exponent and
3980 // the normalized exponent of half the smallest denormal.
3981
3982 int SignificandBits = X.getSemantics().precision - 1;
3983 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
3984
3985 // Clamp to one past the range ends to let normalize handle overlflow.
3986 X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement);
3987 X.normalize(RoundingMode, lfExactlyZero);
Matt Arsenaultea00b492016-03-23 23:51:45 +00003988 if (X.isNaN())
3989 X.makeQuiet();
Richard Trieu6ae37962015-04-30 23:07:00 +00003990 return X;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003991}
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003992
3993APFloat llvm::frexp(const APFloat &Val, int &Exp, APFloat::roundingMode RM) {
3994 Exp = ilogb(Val);
3995
3996 // Quiet signalling nans.
3997 if (Exp == APFloat::IEK_NaN) {
3998 APFloat Quiet(Val);
3999 Quiet.makeQuiet();
4000 return Quiet;
4001 }
4002
4003 if (Exp == APFloat::IEK_Inf)
4004 return Val;
4005
4006 // 1 is added because frexp is defined to return a normalized fraction in
4007 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
4008 Exp = Exp == APFloat::IEK_Zero ? 0 : Exp + 1;
4009 return scalbn(Val, -Exp, RM);
4010}