blob: e9e429c8031b65f5efb0ef0a0340a53b4e5ae248 [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"
Nico Weber432a3882018-04-30 14:59:11 +000022#include "llvm/Config/llvm-config.h"
Tim Shen44bde892016-12-12 21:59:30 +000023#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000024#include "llvm/Support/ErrorHandling.h"
Dale Johannesen918c33c2007-08-24 05:08:11 +000025#include "llvm/Support/MathExtras.h"
Tim Shen44bde892016-12-12 21:59:30 +000026#include "llvm/Support/raw_ostream.h"
Chris Lattner17f71652008-08-17 07:19:36 +000027#include <cstring>
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +000028#include <limits.h>
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000029
Tim Shen601ba8c2017-01-27 02:11:07 +000030#define APFLOAT_DISPATCH_ON_SEMANTICS(METHOD_CALL) \
31 do { \
32 if (usesLayout<IEEEFloat>(getSemantics())) \
33 return U.IEEE.METHOD_CALL; \
34 if (usesLayout<DoubleAPFloat>(getSemantics())) \
35 return U.Double.METHOD_CALL; \
36 llvm_unreachable("Unexpected semantics"); \
37 } while (false)
38
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000039using namespace llvm;
40
Michael Gottesman9b877e12013-06-24 09:57:57 +000041/// A macro used to combine two fcCategory enums into one key which can be used
42/// in a switch statement to classify how the interaction of two APFloat's
43/// categories affects an operation.
44///
45/// TODO: If clang source code is ever allowed to use constexpr in its own
46/// codebase, change this into a static inline function.
47#define PackCategoriesIntoKey(_lhs, _rhs) ((_lhs) * 4 + (_rhs))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000048
Neil Booth8f1946f2007-10-03 22:26:02 +000049/* Assumed in hexadecimal significand parsing, and conversion to
50 hexadecimal strings. */
Craig Topperc85be522017-06-18 18:15:41 +000051static_assert(APFloatBase::integerPartWidth % 4 == 0, "Part width must be divisible by 4!");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000052
53namespace llvm {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000054 /* Represents floating point arithmetic semantics. */
55 struct fltSemantics {
56 /* The largest E such that 2^E is representable; this matches the
57 definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000058 APFloatBase::ExponentType maxExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000059
60 /* The smallest E such that 2^E is a normalized number; this
61 matches the definition of IEEE 754. */
Tim Shen85de51d2016-10-25 19:55:59 +000062 APFloatBase::ExponentType minExponent;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000063
64 /* Number of bits in the significand. This includes the integer
65 bit. */
Neil Booth146fdb32007-10-12 15:33:27 +000066 unsigned int precision;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +000067
68 /* Number of bits actually used in the semantics. */
69 unsigned int sizeInBits;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +000070 };
71
Stephan Bergmann17c7f702016-12-14 11:57:17 +000072 static const fltSemantics semIEEEhalf = {15, -14, 11, 16};
73 static const fltSemantics semIEEEsingle = {127, -126, 24, 32};
74 static const fltSemantics semIEEEdouble = {1023, -1022, 53, 64};
75 static const fltSemantics semIEEEquad = {16383, -16382, 113, 128};
76 static const fltSemantics semX87DoubleExtended = {16383, -16382, 64, 80};
77 static const fltSemantics semBogus = {0, 0, 0, 0};
Dale Johannesen007aa372007-10-11 18:07:22 +000078
Tim Shen7117e692017-01-26 00:11:07 +000079 /* The IBM double-double semantics. Such a number consists of a pair of IEEE
80 64-bit doubles (Hi, Lo), where |Hi| > |Lo|, and if normal,
81 (double)(Hi + Lo) == Hi. The numeric value it's modeling is Hi + Lo.
82 Therefore it has two 53-bit mantissa parts that aren't necessarily adjacent
83 to each other, and two 11-bit exponents.
Michal Gorny21c12042017-01-03 16:33:50 +000084
85 Note: we need to make the value different from semBogus as otherwise
86 an unsafe optimization may collapse both values to a single address,
87 and we heavily rely on them having distinct addresses. */
88 static const fltSemantics semPPCDoubleDouble = {-1, 0, 0, 0};
Tim Shen139a58f2016-10-27 22:52:40 +000089
Tim Shenfd1e5aa2017-01-23 22:39:35 +000090 /* These are legacy semantics for the fallback, inaccrurate implementation of
91 IBM double-double, if the accurate semPPCDoubleDouble doesn't handle the
Tim Shen7117e692017-01-26 00:11:07 +000092 operation. It's equivalent to having an IEEE number with consecutive 106
93 bits of mantissa and 11 bits of exponent.
94
95 It's not equivalent to IBM double-double. For example, a legit IBM
96 double-double, 1 + epsilon:
97
98 1 + epsilon = 1 + (1 >> 1076)
99
100 is not representable by a consecutive 106 bits of mantissa.
Tim Shen139a58f2016-10-27 22:52:40 +0000101
Tim Shenfd1e5aa2017-01-23 22:39:35 +0000102 Currently, these semantics are used in the following way:
103
Tim Shen7117e692017-01-26 00:11:07 +0000104 semPPCDoubleDouble -> (IEEEdouble, IEEEdouble) ->
105 (64-bit APInt, 64-bit APInt) -> (128-bit APInt) ->
106 semPPCDoubleDoubleLegacy -> IEEE operations
Tim Shenfd1e5aa2017-01-23 22:39:35 +0000107
108 We use bitcastToAPInt() to get the bit representation (in APInt) of the
109 underlying IEEEdouble, then use the APInt constructor to construct the
110 legacy IEEE float.
111
112 TODO: Implement all operations in semPPCDoubleDouble, and delete these
113 semantics. */
114 static const fltSemantics semPPCDoubleDoubleLegacy = {1023, -1022 + 53,
115 53 + 53, 128};
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000116
117 const fltSemantics &APFloatBase::IEEEhalf() {
118 return semIEEEhalf;
119 }
120 const fltSemantics &APFloatBase::IEEEsingle() {
121 return semIEEEsingle;
122 }
123 const fltSemantics &APFloatBase::IEEEdouble() {
124 return semIEEEdouble;
125 }
126 const fltSemantics &APFloatBase::IEEEquad() {
127 return semIEEEquad;
128 }
129 const fltSemantics &APFloatBase::x87DoubleExtended() {
130 return semX87DoubleExtended;
131 }
132 const fltSemantics &APFloatBase::Bogus() {
133 return semBogus;
134 }
135 const fltSemantics &APFloatBase::PPCDoubleDouble() {
136 return semPPCDoubleDouble;
137 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000138
139 /* A tight upper bound on number of parts required to hold the value
140 pow(5, power) is
141
Neil Booth91305512007-10-15 15:00:55 +0000142 power * 815 / (351 * integerPartWidth) + 1
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000143
Neil Boothb93d90e2007-10-12 16:02:31 +0000144 However, whilst the result may require only this many parts,
145 because we are multiplying two values to get it, the
146 multiplication may require an extra part with the excess part
147 being zero (consider the trivial case of 1 * 1, tcFullMultiply
148 requires two parts to hold the single-part result). So we add an
149 extra one to guarantee enough space whilst multiplying. */
150 const unsigned int maxExponent = 16383;
151 const unsigned int maxPrecision = 113;
152 const unsigned int maxPowerOfFiveExponent = maxExponent + maxPrecision - 1;
Craig Topperc85be522017-06-18 18:15:41 +0000153 const unsigned int maxPowerOfFiveParts = 2 + ((maxPowerOfFiveExponent * 815) / (351 * APFloatBase::integerPartWidth));
Tim Shen85de51d2016-10-25 19:55:59 +0000154
155 unsigned int APFloatBase::semanticsPrecision(const fltSemantics &semantics) {
156 return semantics.precision;
157 }
158 APFloatBase::ExponentType
159 APFloatBase::semanticsMaxExponent(const fltSemantics &semantics) {
160 return semantics.maxExponent;
161 }
162 APFloatBase::ExponentType
163 APFloatBase::semanticsMinExponent(const fltSemantics &semantics) {
164 return semantics.minExponent;
165 }
166 unsigned int APFloatBase::semanticsSizeInBits(const fltSemantics &semantics) {
167 return semantics.sizeInBits;
168 }
169
170 unsigned APFloatBase::getSizeInBits(const fltSemantics &Sem) {
171 return Sem.sizeInBits;
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000172}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000173
Chris Lattner91702092009-03-12 23:59:55 +0000174/* A bunch of private, handy routines. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000175
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000176static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000177partCountForBits(unsigned int bits)
178{
Craig Topperc85be522017-06-18 18:15:41 +0000179 return ((bits) + APFloatBase::integerPartWidth - 1) / APFloatBase::integerPartWidth;
Chris Lattner91702092009-03-12 23:59:55 +0000180}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000181
Chris Lattner91702092009-03-12 23:59:55 +0000182/* Returns 0U-9U. Return values >= 10U are not digits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000183static inline unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000184decDigitValue(unsigned int c)
185{
186 return c - '0';
187}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000188
Chris Lattner91702092009-03-12 23:59:55 +0000189/* Return the value of a decimal exponent of the form
190 [+-]ddddddd.
Neil Booth4ed401b2007-10-14 10:16:12 +0000191
Chris Lattner91702092009-03-12 23:59:55 +0000192 If the exponent overflows, returns a large exponent with the
193 appropriate sign. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000194static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000195readExponent(StringRef::iterator begin, StringRef::iterator end)
Chris Lattner91702092009-03-12 23:59:55 +0000196{
197 bool isNegative;
198 unsigned int absExponent;
199 const unsigned int overlargeExponent = 24000; /* FIXME. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000200 StringRef::iterator p = begin;
201
202 assert(p != end && "Exponent has no digits");
Neil Booth4ed401b2007-10-14 10:16:12 +0000203
Chris Lattner91702092009-03-12 23:59:55 +0000204 isNegative = (*p == '-');
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000205 if (*p == '-' || *p == '+') {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000206 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000207 assert(p != end && "Exponent has no digits");
208 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000209
Chris Lattner91702092009-03-12 23:59:55 +0000210 absExponent = decDigitValue(*p++);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000211 assert(absExponent < 10U && "Invalid character in exponent");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000212
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000213 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000214 unsigned int value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000215
Chris Lattner91702092009-03-12 23:59:55 +0000216 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000217 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000218
Chris Lattner91702092009-03-12 23:59:55 +0000219 value += absExponent * 10;
220 if (absExponent >= overlargeExponent) {
221 absExponent = overlargeExponent;
Dale Johannesen370c77c2010-08-19 17:58:35 +0000222 p = end; /* outwit assert below */
Chris Lattner91702092009-03-12 23:59:55 +0000223 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000224 }
Chris Lattner91702092009-03-12 23:59:55 +0000225 absExponent = value;
226 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000227
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000228 assert(p == end && "Invalid exponent in exponent");
229
Chris Lattner91702092009-03-12 23:59:55 +0000230 if (isNegative)
231 return -(int) absExponent;
232 else
233 return (int) absExponent;
234}
235
236/* This is ugly and needs cleaning up, but I don't immediately see
237 how whilst remaining safe. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000238static int
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000239totalExponent(StringRef::iterator p, StringRef::iterator end,
240 int exponentAdjustment)
Chris Lattner91702092009-03-12 23:59:55 +0000241{
242 int unsignedExponent;
243 bool negative, overflow;
Ted Kremenek3c4408c2011-01-23 17:05:06 +0000244 int exponent = 0;
Chris Lattner91702092009-03-12 23:59:55 +0000245
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000246 assert(p != end && "Exponent has no digits");
247
Chris Lattner91702092009-03-12 23:59:55 +0000248 negative = *p == '-';
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000249 if (*p == '-' || *p == '+') {
Chris Lattner91702092009-03-12 23:59:55 +0000250 p++;
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000251 assert(p != end && "Exponent has no digits");
252 }
Chris Lattner91702092009-03-12 23:59:55 +0000253
254 unsignedExponent = 0;
255 overflow = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000256 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000257 unsigned int value;
258
259 value = decDigitValue(*p);
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000260 assert(value < 10U && "Invalid character in exponent");
Chris Lattner91702092009-03-12 23:59:55 +0000261
Chris Lattner91702092009-03-12 23:59:55 +0000262 unsignedExponent = unsignedExponent * 10 + value;
Richard Smith156d9202012-08-24 00:01:19 +0000263 if (unsignedExponent > 32767) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000264 overflow = true;
Richard Smith156d9202012-08-24 00:01:19 +0000265 break;
266 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000267 }
268
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000269 if (exponentAdjustment > 32767 || exponentAdjustment < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000270 overflow = true;
271
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000272 if (!overflow) {
Chris Lattner91702092009-03-12 23:59:55 +0000273 exponent = unsignedExponent;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000274 if (negative)
Chris Lattner91702092009-03-12 23:59:55 +0000275 exponent = -exponent;
276 exponent += exponentAdjustment;
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000277 if (exponent > 32767 || exponent < -32768)
Chris Lattner91702092009-03-12 23:59:55 +0000278 overflow = true;
279 }
280
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000281 if (overflow)
Abramo Bagnaraa41d7ae2011-01-06 16:55:14 +0000282 exponent = negative ? -32768: 32767;
Chris Lattner91702092009-03-12 23:59:55 +0000283
284 return exponent;
285}
286
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000287static StringRef::iterator
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000288skipLeadingZeroesAndAnyDot(StringRef::iterator begin, StringRef::iterator end,
289 StringRef::iterator *dot)
Chris Lattner91702092009-03-12 23:59:55 +0000290{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000291 StringRef::iterator p = begin;
292 *dot = end;
Nick Lewycky095b92e2014-09-06 01:16:42 +0000293 while (p != end && *p == '0')
Chris Lattner91702092009-03-12 23:59:55 +0000294 p++;
295
Nick Lewycky095b92e2014-09-06 01:16:42 +0000296 if (p != end && *p == '.') {
Chris Lattner91702092009-03-12 23:59:55 +0000297 *dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000298
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000299 assert(end - begin != 1 && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000300
Nick Lewycky095b92e2014-09-06 01:16:42 +0000301 while (p != end && *p == '0')
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000302 p++;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000303 }
304
Chris Lattner91702092009-03-12 23:59:55 +0000305 return p;
306}
Neil Booth4ed401b2007-10-14 10:16:12 +0000307
Chris Lattner91702092009-03-12 23:59:55 +0000308/* Given a normal decimal floating point number of the form
Neil Booth4ed401b2007-10-14 10:16:12 +0000309
Chris Lattner91702092009-03-12 23:59:55 +0000310 dddd.dddd[eE][+-]ddd
Neil Booth91305512007-10-15 15:00:55 +0000311
Chris Lattner91702092009-03-12 23:59:55 +0000312 where the decimal point and exponent are optional, fill out the
313 structure D. Exponent is appropriate if the significand is
314 treated as an integer, and normalizedExponent if the significand
315 is taken to have the decimal point after a single leading
316 non-zero digit.
Neil Booth4ed401b2007-10-14 10:16:12 +0000317
Chris Lattner91702092009-03-12 23:59:55 +0000318 If the value is zero, V->firstSigDigit points to a non-digit, and
319 the return exponent is zero.
320*/
321struct decimalInfo {
322 const char *firstSigDigit;
323 const char *lastSigDigit;
324 int exponent;
325 int normalizedExponent;
326};
Neil Booth4ed401b2007-10-14 10:16:12 +0000327
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000328static void
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000329interpretDecimal(StringRef::iterator begin, StringRef::iterator end,
330 decimalInfo *D)
Chris Lattner91702092009-03-12 23:59:55 +0000331{
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000332 StringRef::iterator dot = end;
333 StringRef::iterator p = skipLeadingZeroesAndAnyDot (begin, end, &dot);
Neil Booth4ed401b2007-10-14 10:16:12 +0000334
Chris Lattner91702092009-03-12 23:59:55 +0000335 D->firstSigDigit = p;
336 D->exponent = 0;
337 D->normalizedExponent = 0;
338
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000339 for (; p != end; ++p) {
Chris Lattner91702092009-03-12 23:59:55 +0000340 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000341 assert(dot == end && "String contains multiple dots");
Chris Lattner91702092009-03-12 23:59:55 +0000342 dot = p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000343 if (p == end)
344 break;
Neil Booth4ed401b2007-10-14 10:16:12 +0000345 }
Chris Lattner91702092009-03-12 23:59:55 +0000346 if (decDigitValue(*p) >= 10U)
347 break;
Chris Lattner91702092009-03-12 23:59:55 +0000348 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000349
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000350 if (p != end) {
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000351 assert((*p == 'e' || *p == 'E') && "Invalid character in significand");
352 assert(p != begin && "Significand has no digits");
353 assert((dot == end || p - begin != 1) && "Significand has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000354
355 /* p points to the first non-digit in the string */
Erick Tryzelaarda666c82009-08-20 23:30:43 +0000356 D->exponent = readExponent(p + 1, end);
Neil Booth4ed401b2007-10-14 10:16:12 +0000357
Chris Lattner91702092009-03-12 23:59:55 +0000358 /* Implied decimal point? */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000359 if (dot == end)
Chris Lattner91702092009-03-12 23:59:55 +0000360 dot = p;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000361 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000362
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000363 /* If number is all zeroes accept any exponent. */
364 if (p != D->firstSigDigit) {
Chris Lattner91702092009-03-12 23:59:55 +0000365 /* Drop insignificant trailing zeroes. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000366 if (p != begin) {
Neil Booth4ed401b2007-10-14 10:16:12 +0000367 do
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000368 do
369 p--;
370 while (p != begin && *p == '0');
371 while (p != begin && *p == '.');
372 }
Neil Booth4ed401b2007-10-14 10:16:12 +0000373
Chris Lattner91702092009-03-12 23:59:55 +0000374 /* Adjust the exponents for any decimal point. */
Michael Gottesman9dc98332013-06-24 04:06:23 +0000375 D->exponent += static_cast<APFloat::ExponentType>((dot - p) - (dot > p));
Chris Lattner91702092009-03-12 23:59:55 +0000376 D->normalizedExponent = (D->exponent +
Michael Gottesman9dc98332013-06-24 04:06:23 +0000377 static_cast<APFloat::ExponentType>((p - D->firstSigDigit)
Chris Lattner91702092009-03-12 23:59:55 +0000378 - (dot > D->firstSigDigit && dot < p)));
Neil Booth4ed401b2007-10-14 10:16:12 +0000379 }
380
Chris Lattner91702092009-03-12 23:59:55 +0000381 D->lastSigDigit = p;
382}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000383
Chris Lattner91702092009-03-12 23:59:55 +0000384/* Return the trailing fraction of a hexadecimal number.
385 DIGITVALUE is the first hex digit of the fraction, P points to
386 the next digit. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000387static lostFraction
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000388trailingHexadecimalFraction(StringRef::iterator p, StringRef::iterator end,
389 unsigned int digitValue)
Chris Lattner91702092009-03-12 23:59:55 +0000390{
391 unsigned int hexDigit;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000392
Chris Lattner91702092009-03-12 23:59:55 +0000393 /* If the first trailing digit isn't 0 or 8 we can work out the
394 fraction immediately. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000395 if (digitValue > 8)
Chris Lattner91702092009-03-12 23:59:55 +0000396 return lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000397 else if (digitValue < 8 && digitValue > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000398 return lfLessThanHalf;
Chris Lattner91702092009-03-12 23:59:55 +0000399
Eli Friedmand2eb07a2013-07-17 22:17:29 +0000400 // Otherwise we need to find the first non-zero digit.
401 while (p != end && (*p == '0' || *p == '.'))
Chris Lattner91702092009-03-12 23:59:55 +0000402 p++;
403
Erick Tryzelaar19f63b22009-08-16 23:36:19 +0000404 assert(p != end && "Invalid trailing hexadecimal fraction!");
405
Chris Lattner91702092009-03-12 23:59:55 +0000406 hexDigit = hexDigitValue(*p);
407
408 /* If we ran off the end it is exactly zero or one-half, otherwise
409 a little more. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000410 if (hexDigit == -1U)
Chris Lattner91702092009-03-12 23:59:55 +0000411 return digitValue == 0 ? lfExactlyZero: lfExactlyHalf;
412 else
413 return digitValue == 0 ? lfLessThanHalf: lfMoreThanHalf;
414}
415
416/* Return the fraction lost were a bignum truncated losing the least
417 significant BITS bits. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000418static lostFraction
Craig Topperc85be522017-06-18 18:15:41 +0000419lostFractionThroughTruncation(const APFloatBase::integerPart *parts,
Chris Lattner91702092009-03-12 23:59:55 +0000420 unsigned int partCount,
421 unsigned int bits)
422{
423 unsigned int lsb;
424
425 lsb = APInt::tcLSB(parts, partCount);
426
427 /* Note this is guaranteed true if bits == 0, or LSB == -1U. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000428 if (bits <= lsb)
Chris Lattner91702092009-03-12 23:59:55 +0000429 return lfExactlyZero;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000430 if (bits == lsb + 1)
Chris Lattner91702092009-03-12 23:59:55 +0000431 return lfExactlyHalf;
Craig Topperc85be522017-06-18 18:15:41 +0000432 if (bits <= partCount * APFloatBase::integerPartWidth &&
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000433 APInt::tcExtractBit(parts, bits - 1))
Chris Lattner91702092009-03-12 23:59:55 +0000434 return lfMoreThanHalf;
435
436 return lfLessThanHalf;
437}
438
439/* Shift DST right BITS bits noting lost fraction. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000440static lostFraction
Craig Topperc85be522017-06-18 18:15:41 +0000441shiftRight(APFloatBase::integerPart *dst, unsigned int parts, unsigned int bits)
Chris Lattner91702092009-03-12 23:59:55 +0000442{
443 lostFraction lost_fraction;
444
445 lost_fraction = lostFractionThroughTruncation(dst, parts, bits);
446
447 APInt::tcShiftRight(dst, parts, bits);
448
449 return lost_fraction;
450}
451
452/* Combine the effect of two lost fractions. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000453static lostFraction
Chris Lattner91702092009-03-12 23:59:55 +0000454combineLostFractions(lostFraction moreSignificant,
455 lostFraction lessSignificant)
456{
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000457 if (lessSignificant != lfExactlyZero) {
458 if (moreSignificant == lfExactlyZero)
Chris Lattner91702092009-03-12 23:59:55 +0000459 moreSignificant = lfLessThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000460 else if (moreSignificant == lfExactlyHalf)
Chris Lattner91702092009-03-12 23:59:55 +0000461 moreSignificant = lfMoreThanHalf;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000462 }
463
Chris Lattner91702092009-03-12 23:59:55 +0000464 return moreSignificant;
465}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000466
Chris Lattner91702092009-03-12 23:59:55 +0000467/* The error from the true value, in half-ulps, on multiplying two
468 floating point numbers, which differ from the value they
469 approximate by at most HUE1 and HUE2 half-ulps, is strictly less
470 than the returned value.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000471
Chris Lattner91702092009-03-12 23:59:55 +0000472 See "How to Read Floating Point Numbers Accurately" by William D
473 Clinger. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000474static unsigned int
Chris Lattner91702092009-03-12 23:59:55 +0000475HUerrBound(bool inexactMultiply, unsigned int HUerr1, unsigned int HUerr2)
476{
477 assert(HUerr1 < 2 || HUerr2 < 2 || (HUerr1 + HUerr2 < 8));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000478
Chris Lattner91702092009-03-12 23:59:55 +0000479 if (HUerr1 + HUerr2 == 0)
480 return inexactMultiply * 2; /* <= inexactMultiply half-ulps. */
481 else
482 return inexactMultiply + 2 * (HUerr1 + HUerr2);
483}
Neil Booth8f1946f2007-10-03 22:26:02 +0000484
Chris Lattner91702092009-03-12 23:59:55 +0000485/* The number of ulps from the boundary (zero, or half if ISNEAREST)
486 when the least significant BITS are truncated. BITS cannot be
487 zero. */
Craig Topperc85be522017-06-18 18:15:41 +0000488static APFloatBase::integerPart
489ulpsFromBoundary(const APFloatBase::integerPart *parts, unsigned int bits,
490 bool isNearest) {
Chris Lattner91702092009-03-12 23:59:55 +0000491 unsigned int count, partBits;
Craig Topperc85be522017-06-18 18:15:41 +0000492 APFloatBase::integerPart part, boundary;
Neil Boothd3985922007-10-07 08:51:21 +0000493
Evan Cheng67c90212009-10-27 21:35:42 +0000494 assert(bits != 0);
Neil Booth8f1946f2007-10-03 22:26:02 +0000495
Chris Lattner91702092009-03-12 23:59:55 +0000496 bits--;
Craig Topperc85be522017-06-18 18:15:41 +0000497 count = bits / APFloatBase::integerPartWidth;
498 partBits = bits % APFloatBase::integerPartWidth + 1;
Neil Boothb93d90e2007-10-12 16:02:31 +0000499
Craig Topperc85be522017-06-18 18:15:41 +0000500 part = parts[count] & (~(APFloatBase::integerPart) 0 >> (APFloatBase::integerPartWidth - partBits));
Neil Boothb93d90e2007-10-12 16:02:31 +0000501
Chris Lattner91702092009-03-12 23:59:55 +0000502 if (isNearest)
Craig Topperc85be522017-06-18 18:15:41 +0000503 boundary = (APFloatBase::integerPart) 1 << (partBits - 1);
Chris Lattner91702092009-03-12 23:59:55 +0000504 else
505 boundary = 0;
506
507 if (count == 0) {
508 if (part - boundary <= boundary - part)
509 return part - boundary;
Neil Boothb93d90e2007-10-12 16:02:31 +0000510 else
Chris Lattner91702092009-03-12 23:59:55 +0000511 return boundary - part;
Neil Boothb93d90e2007-10-12 16:02:31 +0000512 }
513
Chris Lattner91702092009-03-12 23:59:55 +0000514 if (part == boundary) {
515 while (--count)
516 if (parts[count])
Craig Topperc85be522017-06-18 18:15:41 +0000517 return ~(APFloatBase::integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000518
Chris Lattner91702092009-03-12 23:59:55 +0000519 return parts[0];
520 } else if (part == boundary - 1) {
521 while (--count)
522 if (~parts[count])
Craig Topperc85be522017-06-18 18:15:41 +0000523 return ~(APFloatBase::integerPart) 0; /* A lot. */
Neil Boothb93d90e2007-10-12 16:02:31 +0000524
Chris Lattner91702092009-03-12 23:59:55 +0000525 return -parts[0];
526 }
Neil Boothb93d90e2007-10-12 16:02:31 +0000527
Craig Topperc85be522017-06-18 18:15:41 +0000528 return ~(APFloatBase::integerPart) 0; /* A lot. */
Chris Lattner91702092009-03-12 23:59:55 +0000529}
Neil Boothb93d90e2007-10-12 16:02:31 +0000530
Chris Lattner91702092009-03-12 23:59:55 +0000531/* Place pow(5, power) in DST, and return the number of parts used.
532 DST must be at least one part larger than size of the answer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000533static unsigned int
Craig Topperc85be522017-06-18 18:15:41 +0000534powerOf5(APFloatBase::integerPart *dst, unsigned int power) {
535 static const APFloatBase::integerPart firstEightPowers[] = { 1, 5, 25, 125, 625, 3125, 15625, 78125 };
536 APFloatBase::integerPart pow5s[maxPowerOfFiveParts * 2 + 5];
Chris Lattnerb858c0e2009-03-13 00:24:01 +0000537 pow5s[0] = 78125 * 5;
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000538
Chris Lattner0bf18692009-03-13 00:03:51 +0000539 unsigned int partsCount[16] = { 1 };
Craig Topperc85be522017-06-18 18:15:41 +0000540 APFloatBase::integerPart scratch[maxPowerOfFiveParts], *p1, *p2, *pow5;
Chris Lattner91702092009-03-12 23:59:55 +0000541 unsigned int result;
Chris Lattner91702092009-03-12 23:59:55 +0000542 assert(power <= maxExponent);
543
544 p1 = dst;
545 p2 = scratch;
546
547 *p1 = firstEightPowers[power & 7];
548 power >>= 3;
549
550 result = 1;
551 pow5 = pow5s;
552
553 for (unsigned int n = 0; power; power >>= 1, n++) {
554 unsigned int pc;
555
556 pc = partsCount[n];
557
558 /* Calculate pow(5,pow(2,n+3)) if we haven't yet. */
559 if (pc == 0) {
560 pc = partsCount[n - 1];
561 APInt::tcFullMultiply(pow5, pow5 - pc, pow5 - pc, pc, pc);
562 pc *= 2;
563 if (pow5[pc - 1] == 0)
564 pc--;
565 partsCount[n] = pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000566 }
567
Chris Lattner91702092009-03-12 23:59:55 +0000568 if (power & 1) {
Craig Topperc85be522017-06-18 18:15:41 +0000569 APFloatBase::integerPart *tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000570
Chris Lattner91702092009-03-12 23:59:55 +0000571 APInt::tcFullMultiply(p2, p1, pow5, result, pc);
572 result += pc;
573 if (p2[result - 1] == 0)
574 result--;
Neil Boothb93d90e2007-10-12 16:02:31 +0000575
Chris Lattner91702092009-03-12 23:59:55 +0000576 /* Now result is in p1 with partsCount parts and p2 is scratch
577 space. */
Richard Trieu7a083812016-02-18 22:09:30 +0000578 tmp = p1;
579 p1 = p2;
580 p2 = tmp;
Neil Boothb93d90e2007-10-12 16:02:31 +0000581 }
582
Chris Lattner91702092009-03-12 23:59:55 +0000583 pow5 += pc;
Neil Boothb93d90e2007-10-12 16:02:31 +0000584 }
585
Chris Lattner91702092009-03-12 23:59:55 +0000586 if (p1 != dst)
587 APInt::tcAssign(dst, p1, result);
Neil Boothb93d90e2007-10-12 16:02:31 +0000588
Chris Lattner91702092009-03-12 23:59:55 +0000589 return result;
590}
Neil Boothb93d90e2007-10-12 16:02:31 +0000591
Chris Lattner91702092009-03-12 23:59:55 +0000592/* Zero at the end to avoid modular arithmetic when adding one; used
593 when rounding up during hexadecimal output. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000594static const char hexDigitsLower[] = "0123456789abcdef0";
595static const char hexDigitsUpper[] = "0123456789ABCDEF0";
596static const char infinityL[] = "infinity";
597static const char infinityU[] = "INFINITY";
598static const char NaNL[] = "nan";
599static const char NaNU[] = "NAN";
Neil Boothb93d90e2007-10-12 16:02:31 +0000600
Chris Lattner91702092009-03-12 23:59:55 +0000601/* Write out an integerPart in hexadecimal, starting with the most
602 significant nibble. Write out exactly COUNT hexdigits, return
603 COUNT. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000604static unsigned int
Craig Topperc85be522017-06-18 18:15:41 +0000605partAsHex (char *dst, APFloatBase::integerPart part, unsigned int count,
Chris Lattner91702092009-03-12 23:59:55 +0000606 const char *hexDigitChars)
607{
608 unsigned int result = count;
Neil Boothb93d90e2007-10-12 16:02:31 +0000609
Craig Topperc85be522017-06-18 18:15:41 +0000610 assert(count != 0 && count <= APFloatBase::integerPartWidth / 4);
Neil Boothb93d90e2007-10-12 16:02:31 +0000611
Craig Topperc85be522017-06-18 18:15:41 +0000612 part >>= (APFloatBase::integerPartWidth - 4 * count);
Chris Lattner91702092009-03-12 23:59:55 +0000613 while (count--) {
614 dst[count] = hexDigitChars[part & 0xf];
615 part >>= 4;
Neil Boothb93d90e2007-10-12 16:02:31 +0000616 }
617
Chris Lattner91702092009-03-12 23:59:55 +0000618 return result;
619}
Neil Booth8f1946f2007-10-03 22:26:02 +0000620
Chris Lattner91702092009-03-12 23:59:55 +0000621/* Write out an unsigned decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000622static char *
Chris Lattner91702092009-03-12 23:59:55 +0000623writeUnsignedDecimal (char *dst, unsigned int n)
624{
625 char buff[40], *p;
Neil Booth8f1946f2007-10-03 22:26:02 +0000626
Chris Lattner91702092009-03-12 23:59:55 +0000627 p = buff;
628 do
629 *p++ = '0' + n % 10;
630 while (n /= 10);
Neil Booth8f1946f2007-10-03 22:26:02 +0000631
Chris Lattner91702092009-03-12 23:59:55 +0000632 do
633 *dst++ = *--p;
634 while (p != buff);
Neil Booth8f1946f2007-10-03 22:26:02 +0000635
Chris Lattner91702092009-03-12 23:59:55 +0000636 return dst;
637}
Neil Booth8f1946f2007-10-03 22:26:02 +0000638
Chris Lattner91702092009-03-12 23:59:55 +0000639/* Write out a signed decimal integer. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +0000640static char *
Chris Lattner91702092009-03-12 23:59:55 +0000641writeSignedDecimal (char *dst, int value)
642{
643 if (value < 0) {
644 *dst++ = '-';
645 dst = writeUnsignedDecimal(dst, -(unsigned) value);
646 } else
647 dst = writeUnsignedDecimal(dst, value);
Neil Booth8f1946f2007-10-03 22:26:02 +0000648
Chris Lattner91702092009-03-12 23:59:55 +0000649 return dst;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000650}
651
Tim Shen85de51d2016-10-25 19:55:59 +0000652namespace detail {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000653/* Constructors. */
Tim Shen85de51d2016-10-25 19:55:59 +0000654void IEEEFloat::initialize(const fltSemantics *ourSemantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000655 unsigned int count;
656
657 semantics = ourSemantics;
658 count = partCount();
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000659 if (count > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000660 significand.parts = new integerPart[count];
661}
662
Tim Shen85de51d2016-10-25 19:55:59 +0000663void IEEEFloat::freeSignificand() {
Manuel Klimekd0cf5b22013-06-03 13:03:05 +0000664 if (needsCleanup())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000665 delete [] significand.parts;
666}
667
Tim Shen85de51d2016-10-25 19:55:59 +0000668void IEEEFloat::assign(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000669 assert(semantics == rhs.semantics);
670
671 sign = rhs.sign;
672 category = rhs.category;
673 exponent = rhs.exponent;
Michael Gottesman8136c382013-06-26 23:17:28 +0000674 if (isFiniteNonZero() || category == fcNaN)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000675 copySignificand(rhs);
676}
677
Tim Shen85de51d2016-10-25 19:55:59 +0000678void IEEEFloat::copySignificand(const IEEEFloat &rhs) {
Michael Gottesman8136c382013-06-26 23:17:28 +0000679 assert(isFiniteNonZero() || category == fcNaN);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000680 assert(rhs.partCount() >= partCount());
681
682 APInt::tcAssign(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +0000683 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000684}
685
Neil Booth5fe658b2007-10-14 10:39:51 +0000686/* Make this number a NaN, with an arbitrary but deterministic value
Dale Johannesen1f864982009-01-21 20:32:55 +0000687 for the significand. If double or longer, this is a signalling NaN,
Mike Stump799bf582009-05-30 03:49:43 +0000688 which may not be ideal. If float, this is QNaN(0). */
Tim Shen85de51d2016-10-25 19:55:59 +0000689void IEEEFloat::makeNaN(bool SNaN, bool Negative, const APInt *fill) {
Neil Booth5fe658b2007-10-14 10:39:51 +0000690 category = fcNaN;
John McCalldcb9a7a2010-02-28 02:51:25 +0000691 sign = Negative;
692
John McCallc12b1332010-02-28 12:49:50 +0000693 integerPart *significand = significandParts();
694 unsigned numParts = partCount();
695
John McCalldcb9a7a2010-02-28 02:51:25 +0000696 // Set the significand bits to the fill.
John McCallc12b1332010-02-28 12:49:50 +0000697 if (!fill || fill->getNumWords() < numParts)
698 APInt::tcSet(significand, 0, numParts);
699 if (fill) {
John McCallc6dbe302010-03-01 18:38:45 +0000700 APInt::tcAssign(significand, fill->getRawData(),
701 std::min(fill->getNumWords(), numParts));
John McCallc12b1332010-02-28 12:49:50 +0000702
703 // Zero out the excess bits of the significand.
704 unsigned bitsToPreserve = semantics->precision - 1;
705 unsigned part = bitsToPreserve / 64;
706 bitsToPreserve %= 64;
707 significand[part] &= ((1ULL << bitsToPreserve) - 1);
708 for (part++; part != numParts; ++part)
709 significand[part] = 0;
710 }
711
712 unsigned QNaNBit = semantics->precision - 2;
John McCalldcb9a7a2010-02-28 02:51:25 +0000713
714 if (SNaN) {
715 // We always have to clear the QNaN bit to make it an SNaN.
John McCallc12b1332010-02-28 12:49:50 +0000716 APInt::tcClearBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000717
718 // If there are no bits set in the payload, we have to set
719 // *something* to make it a NaN instead of an infinity;
720 // conventionally, this is the next bit down from the QNaN bit.
John McCallc12b1332010-02-28 12:49:50 +0000721 if (APInt::tcIsZero(significand, numParts))
722 APInt::tcSetBit(significand, QNaNBit - 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000723 } else {
724 // We always have to set the QNaN bit to make it a QNaN.
John McCallc12b1332010-02-28 12:49:50 +0000725 APInt::tcSetBit(significand, QNaNBit);
John McCalldcb9a7a2010-02-28 02:51:25 +0000726 }
John McCallc12b1332010-02-28 12:49:50 +0000727
728 // For x87 extended precision, we want to make a NaN, not a
729 // pseudo-NaN. Maybe we should expose the ability to make
730 // pseudo-NaNs?
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000731 if (semantics == &semX87DoubleExtended)
John McCallc12b1332010-02-28 12:49:50 +0000732 APInt::tcSetBit(significand, QNaNBit + 1);
John McCalldcb9a7a2010-02-28 02:51:25 +0000733}
734
Tim Shen85de51d2016-10-25 19:55:59 +0000735IEEEFloat &IEEEFloat::operator=(const IEEEFloat &rhs) {
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000736 if (this != &rhs) {
737 if (semantics != rhs.semantics) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000738 freeSignificand();
739 initialize(rhs.semantics);
740 }
741 assign(rhs);
742 }
743
744 return *this;
745}
746
Tim Shen85de51d2016-10-25 19:55:59 +0000747IEEEFloat &IEEEFloat::operator=(IEEEFloat &&rhs) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000748 freeSignificand();
749
750 semantics = rhs.semantics;
751 significand = rhs.significand;
752 exponent = rhs.exponent;
753 category = rhs.category;
754 sign = rhs.sign;
755
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000756 rhs.semantics = &semBogus;
Benjamin Kramer06f47782014-03-04 20:26:51 +0000757 return *this;
758}
759
Tim Shen85de51d2016-10-25 19:55:59 +0000760bool IEEEFloat::isDenormal() const {
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000761 return isFiniteNonZero() && (exponent == semantics->minExponent) &&
Simon Pilgrima2849592017-03-20 13:53:59 +0000762 (APInt::tcExtractBit(significandParts(),
Shuxin Yang4fb504f2013-01-07 18:59:35 +0000763 semantics->precision - 1) == 0);
764}
765
Tim Shen85de51d2016-10-25 19:55:59 +0000766bool IEEEFloat::isSmallest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000767 // The smallest number by magnitude in our format will be the smallest
Michael Gottesmana7cc1242013-06-19 07:34:21 +0000768 // denormal, i.e. the floating point number with exponent being minimum
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000769 // exponent and significand bitwise equal to 1 (i.e. with MSB equal to 0).
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000770 return isFiniteNonZero() && exponent == semantics->minExponent &&
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000771 significandMSB() == 0;
772}
773
Tim Shen85de51d2016-10-25 19:55:59 +0000774bool IEEEFloat::isSignificandAllOnes() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000775 // Test if the significand excluding the integral bit is all ones. This allows
776 // us to test for binade boundaries.
777 const integerPart *Parts = significandParts();
778 const unsigned PartCount = partCount();
779 for (unsigned i = 0; i < PartCount - 1; i++)
780 if (~Parts[i])
781 return false;
782
783 // Set the unused high bits to all ones when we compare.
784 const unsigned NumHighBits =
785 PartCount*integerPartWidth - semantics->precision + 1;
786 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
787 "fill than integerPartWidth");
788 const integerPart HighBitFill =
789 ~integerPart(0) << (integerPartWidth - NumHighBits);
790 if (~(Parts[PartCount - 1] | HighBitFill))
791 return false;
792
793 return true;
794}
795
Tim Shen85de51d2016-10-25 19:55:59 +0000796bool IEEEFloat::isSignificandAllZeros() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000797 // Test if the significand excluding the integral bit is all zeros. This
798 // allows us to test for binade boundaries.
799 const integerPart *Parts = significandParts();
800 const unsigned PartCount = partCount();
801
802 for (unsigned i = 0; i < PartCount - 1; i++)
803 if (Parts[i])
804 return false;
805
806 const unsigned NumHighBits =
807 PartCount*integerPartWidth - semantics->precision + 1;
808 assert(NumHighBits <= integerPartWidth && "Can not have more high bits to "
809 "clear than integerPartWidth");
810 const integerPart HighBitMask = ~integerPart(0) >> NumHighBits;
811
812 if (Parts[PartCount - 1] & HighBitMask)
813 return false;
814
815 return true;
816}
817
Tim Shen85de51d2016-10-25 19:55:59 +0000818bool IEEEFloat::isLargest() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000819 // The largest number by magnitude in our format will be the floating point
820 // number with maximum exponent and with significand that is all ones.
Michael Gottesman3cb77ab2013-06-19 21:23:18 +0000821 return isFiniteNonZero() && exponent == semantics->maxExponent
Michael Gottesman0c622ea2013-05-30 18:07:13 +0000822 && isSignificandAllOnes();
823}
824
Tim Shen85de51d2016-10-25 19:55:59 +0000825bool IEEEFloat::isInteger() const {
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000826 // This could be made more efficient; I'm going for obviously correct.
827 if (!isFinite()) return false;
Tim Shen85de51d2016-10-25 19:55:59 +0000828 IEEEFloat truncated = *this;
Stephen Canon1bfc89b2015-11-16 21:52:48 +0000829 truncated.roundToIntegral(rmTowardZero);
830 return compare(truncated) == cmpEqual;
831}
832
Tim Shen85de51d2016-10-25 19:55:59 +0000833bool IEEEFloat::bitwiseIsEqual(const IEEEFloat &rhs) const {
Dale Johannesena719a602007-08-24 00:56:33 +0000834 if (this == &rhs)
835 return true;
836 if (semantics != rhs.semantics ||
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000837 category != rhs.category ||
838 sign != rhs.sign)
Dale Johannesena719a602007-08-24 00:56:33 +0000839 return false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000840 if (category==fcZero || category==fcInfinity)
Dale Johannesena719a602007-08-24 00:56:33 +0000841 return true;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000842
843 if (isFiniteNonZero() && exponent != rhs.exponent)
Dale Johannesen3cf889f2007-08-31 04:03:46 +0000844 return false;
Benjamin Kramer103fc942015-08-21 16:44:52 +0000845
846 return std::equal(significandParts(), significandParts() + partCount(),
847 rhs.significandParts());
Dale Johannesena719a602007-08-24 00:56:33 +0000848}
849
Tim Shen85de51d2016-10-25 19:55:59 +0000850IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, integerPart value) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000851 initialize(&ourSemantics);
852 sign = 0;
Michael Gottesman30a90eb2013-07-27 21:49:21 +0000853 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000854 zeroSignificand();
855 exponent = ourSemantics.precision - 1;
856 significandParts()[0] = value;
857 normalize(rmNearestTiesToEven, lfExactlyZero);
858}
859
Tim Shen85de51d2016-10-25 19:55:59 +0000860IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics) {
Chris Lattnerac6271e2009-09-17 01:08:43 +0000861 initialize(&ourSemantics);
862 category = fcZero;
863 sign = false;
864}
865
Tim Shenb49915482016-10-28 22:45:33 +0000866// Delegate to the previous constructor, because later copy constructor may
867// actually inspects category, which can't be garbage.
868IEEEFloat::IEEEFloat(const fltSemantics &ourSemantics, uninitializedTag tag)
Tim Shen1bab9cf2016-10-29 00:51:41 +0000869 : IEEEFloat(ourSemantics) {}
Chris Lattnerac6271e2009-09-17 01:08:43 +0000870
Tim Shen85de51d2016-10-25 19:55:59 +0000871IEEEFloat::IEEEFloat(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000872 initialize(rhs.semantics);
873 assign(rhs);
874}
875
Stephan Bergmann17c7f702016-12-14 11:57:17 +0000876IEEEFloat::IEEEFloat(IEEEFloat &&rhs) : semantics(&semBogus) {
Benjamin Kramer06f47782014-03-04 20:26:51 +0000877 *this = std::move(rhs);
878}
879
Tim Shen85de51d2016-10-25 19:55:59 +0000880IEEEFloat::~IEEEFloat() { freeSignificand(); }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000881
Tim Shen85de51d2016-10-25 19:55:59 +0000882unsigned int IEEEFloat::partCount() const {
Dale Johannesen146a0ea2007-09-20 23:47:58 +0000883 return partCountForBits(semantics->precision + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000884}
885
Craig Topperc85be522017-06-18 18:15:41 +0000886const IEEEFloat::integerPart *IEEEFloat::significandParts() const {
Tim Shen85de51d2016-10-25 19:55:59 +0000887 return const_cast<IEEEFloat *>(this)->significandParts();
JF Bastiena1d3c242015-08-26 02:32:45 +0000888}
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000889
Craig Topperc85be522017-06-18 18:15:41 +0000890IEEEFloat::integerPart *IEEEFloat::significandParts() {
Evan Cheng67c90212009-10-27 21:35:42 +0000891 if (partCount() > 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000892 return significand.parts;
893 else
894 return &significand.part;
895}
896
Tim Shen85de51d2016-10-25 19:55:59 +0000897void IEEEFloat::zeroSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000898 APInt::tcSet(significandParts(), 0, partCount());
899}
900
901/* Increment an fcNormal floating point number's significand. */
Tim Shen85de51d2016-10-25 19:55:59 +0000902void IEEEFloat::incrementSignificand() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000903 integerPart carry;
904
905 carry = APInt::tcIncrement(significandParts(), partCount());
906
907 /* Our callers should never cause us to overflow. */
908 assert(carry == 0);
Duncan Sandsa41634e2011-08-12 14:54:45 +0000909 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000910}
911
912/* Add the significand of the RHS. Returns the carry flag. */
Craig Topperc85be522017-06-18 18:15:41 +0000913IEEEFloat::integerPart IEEEFloat::addSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000914 integerPart *parts;
915
916 parts = significandParts();
917
918 assert(semantics == rhs.semantics);
919 assert(exponent == rhs.exponent);
920
921 return APInt::tcAdd(parts, rhs.significandParts(), 0, partCount());
922}
923
924/* Subtract the significand of the RHS with a borrow flag. Returns
925 the borrow flag. */
Craig Topperc85be522017-06-18 18:15:41 +0000926IEEEFloat::integerPart IEEEFloat::subtractSignificand(const IEEEFloat &rhs,
927 integerPart borrow) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000928 integerPart *parts;
929
930 parts = significandParts();
931
932 assert(semantics == rhs.semantics);
933 assert(exponent == rhs.exponent);
934
935 return APInt::tcSubtract(parts, rhs.significandParts(), borrow,
Neil Booth9acbf5a2007-09-26 21:33:42 +0000936 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000937}
938
939/* Multiply the significand of the RHS. If ADDEND is non-NULL, add it
940 on to the full-precision result of the multiplication. Returns the
941 lost fraction. */
Tim Shen85de51d2016-10-25 19:55:59 +0000942lostFraction IEEEFloat::multiplySignificand(const IEEEFloat &rhs,
943 const IEEEFloat *addend) {
Neil Booth9acbf5a2007-09-26 21:33:42 +0000944 unsigned int omsb; // One, not zero, based MSB.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000945 unsigned int partsCount, newPartsCount, precision;
946 integerPart *lhsSignificand;
947 integerPart scratch[4];
948 integerPart *fullSignificand;
949 lostFraction lost_fraction;
Dale Johannesen4f0bd682008-10-09 23:00:39 +0000950 bool ignored;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000951
952 assert(semantics == rhs.semantics);
953
954 precision = semantics->precision;
Lang Hames56c0eb22014-11-19 19:15:41 +0000955
956 // Allocate space for twice as many bits as the original significand, plus one
957 // extra bit for the addition to overflow into.
958 newPartsCount = partCountForBits(precision * 2 + 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000959
Dan Gohmanb452d4e2010-03-24 19:38:02 +0000960 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000961 fullSignificand = new integerPart[newPartsCount];
962 else
963 fullSignificand = scratch;
964
965 lhsSignificand = significandParts();
966 partsCount = partCount();
967
968 APInt::tcFullMultiply(fullSignificand, lhsSignificand,
Neil Booth0ea72a92007-10-06 00:24:48 +0000969 rhs.significandParts(), partsCount, partsCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000970
971 lost_fraction = lfExactlyZero;
972 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
973 exponent += rhs.exponent;
974
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000975 // Assume the operands involved in the multiplication are single-precision
976 // FP, and the two multiplicants are:
977 // *this = a23 . a22 ... a0 * 2^e1
978 // rhs = b23 . b22 ... b0 * 2^e2
979 // the result of multiplication is:
Lang Hames56c0eb22014-11-19 19:15:41 +0000980 // *this = c48 c47 c46 . c45 ... c0 * 2^(e1+e2)
Simon Pilgrima2849592017-03-20 13:53:59 +0000981 // Note that there are three significant bits at the left-hand side of the
Lang Hames56c0eb22014-11-19 19:15:41 +0000982 // radix point: two for the multiplication, and an overflow bit for the
983 // addition (that will always be zero at this point). Move the radix point
984 // toward left by two bits, and adjust exponent accordingly.
985 exponent += 2;
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000986
Hal Finkel171c2ec2014-10-14 19:23:07 +0000987 if (addend && addend->isNonZero()) {
Simon Pilgrima2849592017-03-20 13:53:59 +0000988 // The intermediate result of the multiplication has "2 * precision"
Shuxin Yangbbddbac2013-05-13 18:03:12 +0000989 // signicant bit; adjust the addend to be consistent with mul result.
990 //
Chris Lattnerfe02c1f2007-08-20 22:49:32 +0000991 Significand savedSignificand = significand;
992 const fltSemantics *savedSemantics = semantics;
993 fltSemantics extendedSemantics;
994 opStatus status;
995 unsigned int extendedPrecision;
996
Lang Hames56c0eb22014-11-19 19:15:41 +0000997 // Normalize our MSB to one below the top bit to allow for overflow.
998 extendedPrecision = 2 * precision + 1;
999 if (omsb != extendedPrecision - 1) {
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001000 assert(extendedPrecision > omsb);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001001 APInt::tcShiftLeft(fullSignificand, newPartsCount,
Lang Hames56c0eb22014-11-19 19:15:41 +00001002 (extendedPrecision - 1) - omsb);
1003 exponent -= (extendedPrecision - 1) - omsb;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001004 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001005
1006 /* Create new semantics. */
1007 extendedSemantics = *semantics;
1008 extendedSemantics.precision = extendedPrecision;
1009
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001010 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001011 significand.part = fullSignificand[0];
1012 else
1013 significand.parts = fullSignificand;
1014 semantics = &extendedSemantics;
1015
Tim Shen85de51d2016-10-25 19:55:59 +00001016 IEEEFloat extendedAddend(*addend);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001017 status = extendedAddend.convert(extendedSemantics, rmTowardZero, &ignored);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001018 assert(status == opOK);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001019 (void)status;
Lang Hames56c0eb22014-11-19 19:15:41 +00001020
1021 // Shift the significand of the addend right by one bit. This guarantees
1022 // that the high bit of the significand is zero (same as fullSignificand),
1023 // so the addition will overflow (if it does overflow at all) into the top bit.
1024 lost_fraction = extendedAddend.shiftSignificandRight(1);
1025 assert(lost_fraction == lfExactlyZero &&
1026 "Lost precision while shifting addend for fused-multiply-add.");
1027
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001028 lost_fraction = addOrSubtractSignificand(extendedAddend, false);
1029
1030 /* Restore our state. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001031 if (newPartsCount == 1)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001032 fullSignificand[0] = significand.part;
1033 significand = savedSignificand;
1034 semantics = savedSemantics;
1035
1036 omsb = APInt::tcMSB(fullSignificand, newPartsCount) + 1;
1037 }
1038
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001039 // Convert the result having "2 * precision" significant-bits back to the one
Simon Pilgrima2849592017-03-20 13:53:59 +00001040 // having "precision" significant-bits. First, move the radix point from
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001041 // poision "2*precision - 1" to "precision - 1". The exponent need to be
1042 // adjusted by "2*precision - 1" - "precision - 1" = "precision".
Lang Hames56c0eb22014-11-19 19:15:41 +00001043 exponent -= precision + 1;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001044
Shuxin Yangbbddbac2013-05-13 18:03:12 +00001045 // In case MSB resides at the left-hand side of radix point, shift the
1046 // mantissa right by some amount to make sure the MSB reside right before
1047 // the radix point (i.e. "MSB . rest-significant-bits").
1048 //
1049 // Note that the result is not normalized when "omsb < precision". So, the
Tim Shen85de51d2016-10-25 19:55:59 +00001050 // caller needs to call IEEEFloat::normalize() if normalized value is
1051 // expected.
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001052 if (omsb > precision) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001053 unsigned int bits, significantParts;
1054 lostFraction lf;
1055
1056 bits = omsb - precision;
1057 significantParts = partCountForBits(omsb);
1058 lf = shiftRight(fullSignificand, significantParts, bits);
1059 lost_fraction = combineLostFractions(lf, lost_fraction);
1060 exponent += bits;
1061 }
1062
1063 APInt::tcAssign(lhsSignificand, fullSignificand, partsCount);
1064
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001065 if (newPartsCount > 4)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001066 delete [] fullSignificand;
1067
1068 return lost_fraction;
1069}
1070
1071/* Multiply the significands of LHS and RHS to DST. */
Tim Shen85de51d2016-10-25 19:55:59 +00001072lostFraction IEEEFloat::divideSignificand(const IEEEFloat &rhs) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001073 unsigned int bit, i, partsCount;
1074 const integerPart *rhsSignificand;
1075 integerPart *lhsSignificand, *dividend, *divisor;
1076 integerPart scratch[4];
1077 lostFraction lost_fraction;
1078
1079 assert(semantics == rhs.semantics);
1080
1081 lhsSignificand = significandParts();
1082 rhsSignificand = rhs.significandParts();
1083 partsCount = partCount();
1084
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001085 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001086 dividend = new integerPart[partsCount * 2];
1087 else
1088 dividend = scratch;
1089
1090 divisor = dividend + partsCount;
1091
1092 /* Copy the dividend and divisor as they will be modified in-place. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001093 for (i = 0; i < partsCount; i++) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001094 dividend[i] = lhsSignificand[i];
1095 divisor[i] = rhsSignificand[i];
1096 lhsSignificand[i] = 0;
1097 }
1098
1099 exponent -= rhs.exponent;
1100
1101 unsigned int precision = semantics->precision;
1102
1103 /* Normalize the divisor. */
1104 bit = precision - APInt::tcMSB(divisor, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001105 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001106 exponent += bit;
1107 APInt::tcShiftLeft(divisor, partsCount, bit);
1108 }
1109
1110 /* Normalize the dividend. */
1111 bit = precision - APInt::tcMSB(dividend, partsCount) - 1;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001112 if (bit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001113 exponent -= bit;
1114 APInt::tcShiftLeft(dividend, partsCount, bit);
1115 }
1116
Neil Boothb93d90e2007-10-12 16:02:31 +00001117 /* Ensure the dividend >= divisor initially for the loop below.
1118 Incidentally, this means that the division loop below is
1119 guaranteed to set the integer bit to one. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001120 if (APInt::tcCompare(dividend, divisor, partsCount) < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001121 exponent--;
1122 APInt::tcShiftLeft(dividend, partsCount, 1);
1123 assert(APInt::tcCompare(dividend, divisor, partsCount) >= 0);
1124 }
1125
1126 /* Long division. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001127 for (bit = precision; bit; bit -= 1) {
1128 if (APInt::tcCompare(dividend, divisor, partsCount) >= 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001129 APInt::tcSubtract(dividend, divisor, 0, partsCount);
1130 APInt::tcSetBit(lhsSignificand, bit - 1);
1131 }
1132
1133 APInt::tcShiftLeft(dividend, partsCount, 1);
1134 }
1135
1136 /* Figure out the lost fraction. */
1137 int cmp = APInt::tcCompare(dividend, divisor, partsCount);
1138
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001139 if (cmp > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001140 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001141 else if (cmp == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001142 lost_fraction = lfExactlyHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001143 else if (APInt::tcIsZero(dividend, partsCount))
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001144 lost_fraction = lfExactlyZero;
1145 else
1146 lost_fraction = lfLessThanHalf;
1147
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001148 if (partsCount > 2)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001149 delete [] dividend;
1150
1151 return lost_fraction;
1152}
1153
Tim Shen85de51d2016-10-25 19:55:59 +00001154unsigned int IEEEFloat::significandMSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001155 return APInt::tcMSB(significandParts(), partCount());
1156}
1157
Tim Shen85de51d2016-10-25 19:55:59 +00001158unsigned int IEEEFloat::significandLSB() const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001159 return APInt::tcLSB(significandParts(), partCount());
1160}
1161
1162/* Note that a zero result is NOT normalized to fcZero. */
Tim Shen85de51d2016-10-25 19:55:59 +00001163lostFraction IEEEFloat::shiftSignificandRight(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001164 /* Our exponent should not overflow. */
Michael Gottesman9dc98332013-06-24 04:06:23 +00001165 assert((ExponentType) (exponent + bits) >= exponent);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001166
1167 exponent += bits;
1168
1169 return shiftRight(significandParts(), partCount(), bits);
1170}
1171
1172/* Shift the significand left BITS bits, subtract BITS from its exponent. */
Tim Shen85de51d2016-10-25 19:55:59 +00001173void IEEEFloat::shiftSignificandLeft(unsigned int bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001174 assert(bits < semantics->precision);
1175
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001176 if (bits) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001177 unsigned int partsCount = partCount();
1178
1179 APInt::tcShiftLeft(significandParts(), partsCount, bits);
1180 exponent -= bits;
1181
1182 assert(!APInt::tcIsZero(significandParts(), partsCount));
1183 }
1184}
1185
Tim Shen85de51d2016-10-25 19:55:59 +00001186IEEEFloat::cmpResult
1187IEEEFloat::compareAbsoluteValue(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001188 int compare;
1189
1190 assert(semantics == rhs.semantics);
Michael Gottesman8136c382013-06-26 23:17:28 +00001191 assert(isFiniteNonZero());
1192 assert(rhs.isFiniteNonZero());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001193
1194 compare = exponent - rhs.exponent;
1195
1196 /* If exponents are equal, do an unsigned bignum comparison of the
1197 significands. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001198 if (compare == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001199 compare = APInt::tcCompare(significandParts(), rhs.significandParts(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001200 partCount());
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001201
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001202 if (compare > 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001203 return cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001204 else if (compare < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001205 return cmpLessThan;
1206 else
1207 return cmpEqual;
1208}
1209
1210/* Handle overflow. Sign is preserved. We either become infinity or
1211 the largest finite number. */
Tim Shen85de51d2016-10-25 19:55:59 +00001212IEEEFloat::opStatus IEEEFloat::handleOverflow(roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001213 /* Infinity? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001214 if (rounding_mode == rmNearestTiesToEven ||
1215 rounding_mode == rmNearestTiesToAway ||
1216 (rounding_mode == rmTowardPositive && !sign) ||
1217 (rounding_mode == rmTowardNegative && sign)) {
1218 category = fcInfinity;
1219 return (opStatus) (opOverflow | opInexact);
1220 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001221
1222 /* Otherwise we become the largest finite number. */
1223 category = fcNormal;
1224 exponent = semantics->maxExponent;
1225 APInt::tcSetLeastSignificantBits(significandParts(), partCount(),
Neil Booth9acbf5a2007-09-26 21:33:42 +00001226 semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001227
1228 return opInexact;
1229}
1230
Neil Booth1ca1f802007-10-03 15:16:41 +00001231/* Returns TRUE if, when truncating the current number, with BIT the
1232 new LSB, with the given lost fraction and rounding mode, the result
1233 would need to be rounded away from zero (i.e., by increasing the
1234 signficand). This routine must work for fcZero of both signs, and
1235 fcNormal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001236bool IEEEFloat::roundAwayFromZero(roundingMode rounding_mode,
1237 lostFraction lost_fraction,
1238 unsigned int bit) const {
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001239 /* NaNs and infinities should not have lost fractions. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001240 assert(isFiniteNonZero() || category == fcZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001241
Neil Booth1ca1f802007-10-03 15:16:41 +00001242 /* Current callers never pass this so we don't handle it. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001243 assert(lost_fraction != lfExactlyZero);
1244
Mike Stump889285d2009-05-13 23:23:20 +00001245 switch (rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001246 case rmNearestTiesToAway:
1247 return lost_fraction == lfExactlyHalf || lost_fraction == lfMoreThanHalf;
1248
1249 case rmNearestTiesToEven:
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001250 if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001251 return true;
1252
1253 /* Our zeroes don't have a significand to test. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001254 if (lost_fraction == lfExactlyHalf && category != fcZero)
Neil Booth1ca1f802007-10-03 15:16:41 +00001255 return APInt::tcExtractBit(significandParts(), bit);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001256
1257 return false;
1258
1259 case rmTowardZero:
1260 return false;
1261
1262 case rmTowardPositive:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001263 return !sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001264
1265 case rmTowardNegative:
David Blaikiedc3f01e2015-03-09 01:57:13 +00001266 return sign;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001267 }
Chandler Carruthf3e85022012-01-10 18:08:01 +00001268 llvm_unreachable("Invalid rounding mode found");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001269}
1270
Tim Shen85de51d2016-10-25 19:55:59 +00001271IEEEFloat::opStatus IEEEFloat::normalize(roundingMode rounding_mode,
1272 lostFraction lost_fraction) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001273 unsigned int omsb; /* One, not zero, based MSB. */
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001274 int exponentChange;
1275
Michael Gottesman8136c382013-06-26 23:17:28 +00001276 if (!isFiniteNonZero())
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001277 return opOK;
1278
1279 /* Before rounding normalize the exponent of fcNormal numbers. */
1280 omsb = significandMSB() + 1;
1281
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001282 if (omsb) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001283 /* OMSB is numbered from 1. We want to place it in the integer
Nick Lewyckyf66daac2011-10-03 21:30:08 +00001284 bit numbered PRECISION if possible, with a compensating change in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001285 the exponent. */
1286 exponentChange = omsb - semantics->precision;
1287
1288 /* If the resulting exponent is too high, overflow according to
1289 the rounding mode. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001290 if (exponent + exponentChange > semantics->maxExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001291 return handleOverflow(rounding_mode);
1292
1293 /* Subnormal numbers have exponent minExponent, and their MSB
1294 is forced based on that. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001295 if (exponent + exponentChange < semantics->minExponent)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001296 exponentChange = semantics->minExponent - exponent;
1297
1298 /* Shifting left is easy as we don't lose precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001299 if (exponentChange < 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001300 assert(lost_fraction == lfExactlyZero);
1301
1302 shiftSignificandLeft(-exponentChange);
1303
1304 return opOK;
1305 }
1306
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001307 if (exponentChange > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001308 lostFraction lf;
1309
1310 /* Shift right and capture any new lost fraction. */
1311 lf = shiftSignificandRight(exponentChange);
1312
1313 lost_fraction = combineLostFractions(lf, lost_fraction);
1314
1315 /* Keep OMSB up-to-date. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001316 if (omsb > (unsigned) exponentChange)
Neil Boothb93d90e2007-10-12 16:02:31 +00001317 omsb -= exponentChange;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001318 else
Neil Booth9acbf5a2007-09-26 21:33:42 +00001319 omsb = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001320 }
1321 }
1322
1323 /* Now round the number according to rounding_mode given the lost
1324 fraction. */
1325
1326 /* As specified in IEEE 754, since we do not trap we do not report
1327 underflow for exact results. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001328 if (lost_fraction == lfExactlyZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001329 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001330 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001331 category = fcZero;
1332
1333 return opOK;
1334 }
1335
1336 /* Increment the significand if we're rounding away from zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001337 if (roundAwayFromZero(rounding_mode, lost_fraction, 0)) {
1338 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001339 exponent = semantics->minExponent;
1340
1341 incrementSignificand();
1342 omsb = significandMSB() + 1;
1343
1344 /* Did the significand increment overflow? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001345 if (omsb == (unsigned) semantics->precision + 1) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001346 /* Renormalize by incrementing the exponent and shifting our
Neil Booth9acbf5a2007-09-26 21:33:42 +00001347 significand right one. However if we already have the
1348 maximum exponent we overflow to infinity. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001349 if (exponent == semantics->maxExponent) {
Neil Booth9acbf5a2007-09-26 21:33:42 +00001350 category = fcInfinity;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001351
Neil Booth9acbf5a2007-09-26 21:33:42 +00001352 return (opStatus) (opOverflow | opInexact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001353 }
1354
1355 shiftSignificandRight(1);
1356
1357 return opInexact;
1358 }
1359 }
1360
1361 /* The normal case - we were and are not denormal, and any
1362 significand increment above didn't overflow. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001363 if (omsb == semantics->precision)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001364 return opInexact;
1365
1366 /* We have a non-zero denormal. */
1367 assert(omsb < semantics->precision);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001368
1369 /* Canonicalize zeroes. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001370 if (omsb == 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001371 category = fcZero;
1372
1373 /* The fcZero case is a denormal that underflowed to zero. */
1374 return (opStatus) (opUnderflow | opInexact);
1375}
1376
Tim Shen85de51d2016-10-25 19:55:59 +00001377IEEEFloat::opStatus IEEEFloat::addOrSubtractSpecials(const IEEEFloat &rhs,
1378 bool subtract) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001379 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001380 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001381 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001382
Michael Gottesman9b877e12013-06-24 09:57:57 +00001383 case PackCategoriesIntoKey(fcNaN, fcZero):
1384 case PackCategoriesIntoKey(fcNaN, fcNormal):
1385 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1386 case PackCategoriesIntoKey(fcNaN, fcNaN):
1387 case PackCategoriesIntoKey(fcNormal, fcZero):
1388 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1389 case PackCategoriesIntoKey(fcInfinity, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001390 return opOK;
1391
Michael Gottesman9b877e12013-06-24 09:57:57 +00001392 case PackCategoriesIntoKey(fcZero, fcNaN):
1393 case PackCategoriesIntoKey(fcNormal, fcNaN):
1394 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Stephen Canond3278282014-06-08 16:53:31 +00001395 // We need to be sure to flip the sign here for subtraction because we
1396 // don't have a separate negate operation so -NaN becomes 0 - NaN here.
1397 sign = rhs.sign ^ subtract;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001398 category = fcNaN;
1399 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001400 return opOK;
1401
Michael Gottesman9b877e12013-06-24 09:57:57 +00001402 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1403 case PackCategoriesIntoKey(fcZero, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001404 category = fcInfinity;
1405 sign = rhs.sign ^ subtract;
1406 return opOK;
1407
Michael Gottesman9b877e12013-06-24 09:57:57 +00001408 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001409 assign(rhs);
1410 sign = rhs.sign ^ subtract;
1411 return opOK;
1412
Michael Gottesman9b877e12013-06-24 09:57:57 +00001413 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001414 /* Sign depends on rounding mode; handled by caller. */
1415 return opOK;
1416
Michael Gottesman9b877e12013-06-24 09:57:57 +00001417 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001418 /* Differently signed infinities can only be validly
1419 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001420 if (((sign ^ rhs.sign)!=0) != subtract) {
Neil Booth5fe658b2007-10-14 10:39:51 +00001421 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001422 return opInvalidOp;
1423 }
1424
1425 return opOK;
1426
Michael Gottesman9b877e12013-06-24 09:57:57 +00001427 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001428 return opDivByZero;
1429 }
1430}
1431
1432/* Add or subtract two normal numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001433lostFraction IEEEFloat::addOrSubtractSignificand(const IEEEFloat &rhs,
1434 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001435 integerPart carry;
1436 lostFraction lost_fraction;
1437 int bits;
1438
1439 /* Determine if the operation on the absolute values is effectively
1440 an addition or subtraction. */
Aaron Ballmand5cc45f2015-03-24 12:47:51 +00001441 subtract ^= static_cast<bool>(sign ^ rhs.sign);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001442
1443 /* Are we bigger exponent-wise than the RHS? */
1444 bits = exponent - rhs.exponent;
1445
1446 /* Subtraction is more subtle than one might naively expect. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001447 if (subtract) {
Tim Shen85de51d2016-10-25 19:55:59 +00001448 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001449 bool reverse;
1450
Chris Lattner3da18eb2007-08-24 03:02:34 +00001451 if (bits == 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001452 reverse = compareAbsoluteValue(temp_rhs) == cmpLessThan;
1453 lost_fraction = lfExactlyZero;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001454 } else if (bits > 0) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001455 lost_fraction = temp_rhs.shiftSignificandRight(bits - 1);
1456 shiftSignificandLeft(1);
1457 reverse = false;
Chris Lattner3da18eb2007-08-24 03:02:34 +00001458 } else {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001459 lost_fraction = shiftSignificandRight(-bits - 1);
1460 temp_rhs.shiftSignificandLeft(1);
1461 reverse = true;
1462 }
1463
Chris Lattner3da18eb2007-08-24 03:02:34 +00001464 if (reverse) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001465 carry = temp_rhs.subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001466 (*this, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001467 copySignificand(temp_rhs);
1468 sign = !sign;
1469 } else {
1470 carry = subtractSignificand
Neil Booth9acbf5a2007-09-26 21:33:42 +00001471 (temp_rhs, lost_fraction != lfExactlyZero);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001472 }
1473
1474 /* Invert the lost fraction - it was on the RHS and
1475 subtracted. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001476 if (lost_fraction == lfLessThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001477 lost_fraction = lfMoreThanHalf;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001478 else if (lost_fraction == lfMoreThanHalf)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001479 lost_fraction = lfLessThanHalf;
1480
1481 /* The code above is intended to ensure that no borrow is
1482 necessary. */
1483 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001484 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001485 } else {
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001486 if (bits > 0) {
Tim Shen85de51d2016-10-25 19:55:59 +00001487 IEEEFloat temp_rhs(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001488
1489 lost_fraction = temp_rhs.shiftSignificandRight(bits);
1490 carry = addSignificand(temp_rhs);
1491 } else {
1492 lost_fraction = shiftSignificandRight(-bits);
1493 carry = addSignificand(rhs);
1494 }
1495
1496 /* We have a guard bit; generating a carry cannot happen. */
1497 assert(!carry);
Duncan Sandsa41634e2011-08-12 14:54:45 +00001498 (void)carry;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001499 }
1500
1501 return lost_fraction;
1502}
1503
Tim Shen85de51d2016-10-25 19:55:59 +00001504IEEEFloat::opStatus IEEEFloat::multiplySpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001505 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001506 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001507 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001508
Michael Gottesman9b877e12013-06-24 09:57:57 +00001509 case PackCategoriesIntoKey(fcNaN, fcZero):
1510 case PackCategoriesIntoKey(fcNaN, fcNormal):
1511 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1512 case PackCategoriesIntoKey(fcNaN, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001513 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001514 return opOK;
1515
Michael Gottesman9b877e12013-06-24 09:57:57 +00001516 case PackCategoriesIntoKey(fcZero, fcNaN):
1517 case PackCategoriesIntoKey(fcNormal, fcNaN):
1518 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001519 sign = false;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001520 category = fcNaN;
1521 copySignificand(rhs);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001522 return opOK;
1523
Michael Gottesman9b877e12013-06-24 09:57:57 +00001524 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1525 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1526 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001527 category = fcInfinity;
1528 return opOK;
1529
Michael Gottesman9b877e12013-06-24 09:57:57 +00001530 case PackCategoriesIntoKey(fcZero, fcNormal):
1531 case PackCategoriesIntoKey(fcNormal, fcZero):
1532 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001533 category = fcZero;
1534 return opOK;
1535
Michael Gottesman9b877e12013-06-24 09:57:57 +00001536 case PackCategoriesIntoKey(fcZero, fcInfinity):
1537 case PackCategoriesIntoKey(fcInfinity, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001538 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001539 return opInvalidOp;
1540
Michael Gottesman9b877e12013-06-24 09:57:57 +00001541 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001542 return opOK;
1543 }
1544}
1545
Tim Shen85de51d2016-10-25 19:55:59 +00001546IEEEFloat::opStatus IEEEFloat::divideSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001547 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001548 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001549 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001550
Michael Gottesman9b877e12013-06-24 09:57:57 +00001551 case PackCategoriesIntoKey(fcZero, fcNaN):
1552 case PackCategoriesIntoKey(fcNormal, fcNaN):
1553 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001554 category = fcNaN;
1555 copySignificand(rhs);
Galina Kistanova5c4f1a92017-05-30 03:30:34 +00001556 LLVM_FALLTHROUGH;
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001557 case PackCategoriesIntoKey(fcNaN, fcZero):
1558 case PackCategoriesIntoKey(fcNaN, fcNormal):
1559 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1560 case PackCategoriesIntoKey(fcNaN, fcNaN):
1561 sign = false;
Galina Kistanova5c4f1a92017-05-30 03:30:34 +00001562 LLVM_FALLTHROUGH;
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001563 case PackCategoriesIntoKey(fcInfinity, fcZero):
1564 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1565 case PackCategoriesIntoKey(fcZero, fcInfinity):
1566 case PackCategoriesIntoKey(fcZero, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001567 return opOK;
1568
Michael Gottesman9b877e12013-06-24 09:57:57 +00001569 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001570 category = fcZero;
1571 return opOK;
1572
Michael Gottesman9b877e12013-06-24 09:57:57 +00001573 case PackCategoriesIntoKey(fcNormal, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001574 category = fcInfinity;
1575 return opDivByZero;
1576
Michael Gottesman9b877e12013-06-24 09:57:57 +00001577 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1578 case PackCategoriesIntoKey(fcZero, fcZero):
Neil Booth5fe658b2007-10-14 10:39:51 +00001579 makeNaN();
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001580 return opInvalidOp;
1581
Michael Gottesman9b877e12013-06-24 09:57:57 +00001582 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001583 return opOK;
1584 }
1585}
1586
Tim Shen85de51d2016-10-25 19:55:59 +00001587IEEEFloat::opStatus IEEEFloat::modSpecials(const IEEEFloat &rhs) {
Michael Gottesman9b877e12013-06-24 09:57:57 +00001588 switch (PackCategoriesIntoKey(category, rhs.category)) {
Dale Johannesenb5721632009-01-21 00:35:19 +00001589 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001590 llvm_unreachable(nullptr);
Dale Johannesenb5721632009-01-21 00:35:19 +00001591
Michael Gottesman9b877e12013-06-24 09:57:57 +00001592 case PackCategoriesIntoKey(fcNaN, fcZero):
1593 case PackCategoriesIntoKey(fcNaN, fcNormal):
1594 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1595 case PackCategoriesIntoKey(fcNaN, fcNaN):
1596 case PackCategoriesIntoKey(fcZero, fcInfinity):
1597 case PackCategoriesIntoKey(fcZero, fcNormal):
1598 case PackCategoriesIntoKey(fcNormal, fcInfinity):
Dale Johannesenb5721632009-01-21 00:35:19 +00001599 return opOK;
1600
Michael Gottesman9b877e12013-06-24 09:57:57 +00001601 case PackCategoriesIntoKey(fcZero, fcNaN):
1602 case PackCategoriesIntoKey(fcNormal, fcNaN):
1603 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Michael Gottesmanb0e688e2013-07-27 21:49:25 +00001604 sign = false;
Dale Johannesenb5721632009-01-21 00:35:19 +00001605 category = fcNaN;
1606 copySignificand(rhs);
1607 return opOK;
1608
Michael Gottesman9b877e12013-06-24 09:57:57 +00001609 case PackCategoriesIntoKey(fcNormal, fcZero):
1610 case PackCategoriesIntoKey(fcInfinity, fcZero):
1611 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1612 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
1613 case PackCategoriesIntoKey(fcZero, fcZero):
Dale Johannesenb5721632009-01-21 00:35:19 +00001614 makeNaN();
1615 return opInvalidOp;
1616
Michael Gottesman9b877e12013-06-24 09:57:57 +00001617 case PackCategoriesIntoKey(fcNormal, fcNormal):
Dale Johannesenb5721632009-01-21 00:35:19 +00001618 return opOK;
1619 }
1620}
1621
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001622/* Change sign. */
Tim Shen85de51d2016-10-25 19:55:59 +00001623void IEEEFloat::changeSign() {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001624 /* Look mummy, this one's easy. */
1625 sign = !sign;
1626}
1627
1628/* Normalized addition or subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001629IEEEFloat::opStatus IEEEFloat::addOrSubtract(const IEEEFloat &rhs,
1630 roundingMode rounding_mode,
1631 bool subtract) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001632 opStatus fs;
1633
1634 fs = addOrSubtractSpecials(rhs, subtract);
1635
1636 /* This return code means it was not a simple case. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001637 if (fs == opDivByZero) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001638 lostFraction lost_fraction;
1639
1640 lost_fraction = addOrSubtractSignificand(rhs, subtract);
1641 fs = normalize(rounding_mode, lost_fraction);
1642
1643 /* Can only be zero if we lost no fraction. */
1644 assert(category != fcZero || lost_fraction == lfExactlyZero);
1645 }
1646
1647 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1648 positive zero unless rounding to minus infinity, except that
1649 adding two like-signed zeroes gives that zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001650 if (category == fcZero) {
1651 if (rhs.category != fcZero || (sign == rhs.sign) == subtract)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001652 sign = (rounding_mode == rmTowardNegative);
1653 }
1654
1655 return fs;
1656}
1657
1658/* Normalized addition. */
Tim Shen85de51d2016-10-25 19:55:59 +00001659IEEEFloat::opStatus IEEEFloat::add(const IEEEFloat &rhs,
1660 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001661 return addOrSubtract(rhs, rounding_mode, false);
1662}
1663
1664/* Normalized subtraction. */
Tim Shen85de51d2016-10-25 19:55:59 +00001665IEEEFloat::opStatus IEEEFloat::subtract(const IEEEFloat &rhs,
1666 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001667 return addOrSubtract(rhs, rounding_mode, true);
1668}
1669
1670/* Normalized multiply. */
Tim Shen85de51d2016-10-25 19:55:59 +00001671IEEEFloat::opStatus IEEEFloat::multiply(const IEEEFloat &rhs,
1672 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001673 opStatus fs;
1674
1675 sign ^= rhs.sign;
1676 fs = multiplySpecials(rhs);
1677
Michael Gottesman8136c382013-06-26 23:17:28 +00001678 if (isFiniteNonZero()) {
Craig Topperc10719f2014-04-07 04:17:22 +00001679 lostFraction lost_fraction = multiplySignificand(rhs, nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001680 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001681 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001682 fs = (opStatus) (fs | opInexact);
1683 }
1684
1685 return fs;
1686}
1687
1688/* Normalized divide. */
Tim Shen85de51d2016-10-25 19:55:59 +00001689IEEEFloat::opStatus IEEEFloat::divide(const IEEEFloat &rhs,
1690 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001691 opStatus fs;
1692
1693 sign ^= rhs.sign;
1694 fs = divideSpecials(rhs);
1695
Michael Gottesman8136c382013-06-26 23:17:28 +00001696 if (isFiniteNonZero()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001697 lostFraction lost_fraction = divideSignificand(rhs);
1698 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001699 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001700 fs = (opStatus) (fs | opInexact);
1701 }
1702
1703 return fs;
1704}
1705
Dale Johannesenfe750172009-01-20 18:35:05 +00001706/* Normalized remainder. This is not currently correct in all cases. */
Tim Shen85de51d2016-10-25 19:55:59 +00001707IEEEFloat::opStatus IEEEFloat::remainder(const IEEEFloat &rhs) {
Dale Johannesenfe750172009-01-20 18:35:05 +00001708 opStatus fs;
Tim Shen85de51d2016-10-25 19:55:59 +00001709 IEEEFloat V = *this;
Dale Johannesenfe750172009-01-20 18:35:05 +00001710 unsigned int origSign = sign;
1711
Dale Johannesenfe750172009-01-20 18:35:05 +00001712 fs = V.divide(rhs, rmNearestTiesToEven);
1713 if (fs == opDivByZero)
1714 return fs;
1715
1716 int parts = partCount();
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001717 integerPart *x = new integerPart[parts];
Dale Johannesenfe750172009-01-20 18:35:05 +00001718 bool ignored;
Simon Pilgrim00b34992017-03-20 14:40:12 +00001719 fs = V.convertToInteger(makeMutableArrayRef(x, parts),
1720 parts * integerPartWidth, true, rmNearestTiesToEven,
1721 &ignored);
1722 if (fs == opInvalidOp) {
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001723 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001724 return fs;
Sylvestre Ledru3ce346d2016-11-08 10:00:45 +00001725 }
Dale Johannesenfe750172009-01-20 18:35:05 +00001726
1727 fs = V.convertFromZeroExtendedInteger(x, parts * integerPartWidth, true,
1728 rmNearestTiesToEven);
1729 assert(fs==opOK); // should always work
1730
1731 fs = V.multiply(rhs, rmNearestTiesToEven);
1732 assert(fs==opOK || fs==opInexact); // should not overflow or underflow
1733
1734 fs = subtract(V, rmNearestTiesToEven);
1735 assert(fs==opOK || fs==opInexact); // likewise
1736
1737 if (isZero())
1738 sign = origSign; // IEEE754 requires this
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00001739 delete[] x;
Dale Johannesenfe750172009-01-20 18:35:05 +00001740 return fs;
1741}
1742
Stephen Canon157c8692017-03-31 20:31:33 +00001743/* Normalized llvm frem (C fmod). */
Tim Shen85de51d2016-10-25 19:55:59 +00001744IEEEFloat::opStatus IEEEFloat::mod(const IEEEFloat &rhs) {
Dale Johannesen689d17d2007-08-31 23:35:31 +00001745 opStatus fs;
Dale Johannesenb5721632009-01-21 00:35:19 +00001746 fs = modSpecials(rhs);
Serguei Katkovf2c28512017-11-01 07:56:55 +00001747 unsigned int origSign = sign;
Dale Johannesen689d17d2007-08-31 23:35:31 +00001748
Stephen Canon157c8692017-03-31 20:31:33 +00001749 while (isFiniteNonZero() && rhs.isFiniteNonZero() &&
1750 compareAbsoluteValue(rhs) != cmpLessThan) {
1751 IEEEFloat V = scalbn(rhs, ilogb(*this) - ilogb(rhs), rmNearestTiesToEven);
1752 if (compareAbsoluteValue(V) == cmpLessThan)
1753 V = scalbn(V, -1, rmNearestTiesToEven);
1754 V.sign = sign;
Fangrui Songf78650a2018-07-30 19:41:25 +00001755
Stephen Canonb12db0e2015-09-21 19:29:25 +00001756 fs = subtract(V, rmNearestTiesToEven);
Stephen Canon157c8692017-03-31 20:31:33 +00001757 assert(fs==opOK);
Dale Johannesenb5721632009-01-21 00:35:19 +00001758 }
Serguei Katkovf2c28512017-11-01 07:56:55 +00001759 if (isZero())
1760 sign = origSign; // fmod requires this
Dale Johannesen689d17d2007-08-31 23:35:31 +00001761 return fs;
1762}
1763
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001764/* Normalized fused-multiply-add. */
Tim Shen85de51d2016-10-25 19:55:59 +00001765IEEEFloat::opStatus IEEEFloat::fusedMultiplyAdd(const IEEEFloat &multiplicand,
1766 const IEEEFloat &addend,
1767 roundingMode rounding_mode) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001768 opStatus fs;
1769
1770 /* Post-multiplication sign, before addition. */
1771 sign ^= multiplicand.sign;
1772
1773 /* If and only if all arguments are normal do we need to do an
1774 extended-precision calculation. */
Michael Gottesman8136c382013-06-26 23:17:28 +00001775 if (isFiniteNonZero() &&
1776 multiplicand.isFiniteNonZero() &&
Hal Finkel171c2ec2014-10-14 19:23:07 +00001777 addend.isFinite()) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001778 lostFraction lost_fraction;
1779
1780 lost_fraction = multiplySignificand(multiplicand, &addend);
1781 fs = normalize(rounding_mode, lost_fraction);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001782 if (lost_fraction != lfExactlyZero)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001783 fs = (opStatus) (fs | opInexact);
1784
1785 /* If two numbers add (exactly) to zero, IEEE 754 decrees it is a
1786 positive zero unless rounding to minus infinity, except that
1787 adding two like-signed zeroes gives that zero. */
Lang Hames12b12e82015-01-04 01:20:55 +00001788 if (category == fcZero && !(fs & opUnderflow) && sign != addend.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001789 sign = (rounding_mode == rmTowardNegative);
1790 } else {
1791 fs = multiplySpecials(multiplicand);
1792
1793 /* FS can only be opOK or opInvalidOp. There is no more work
1794 to do in the latter case. The IEEE-754R standard says it is
1795 implementation-defined in this case whether, if ADDEND is a
Dale Johannesen3cf889f2007-08-31 04:03:46 +00001796 quiet NaN, we raise invalid op; this implementation does so.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001797
1798 If we need to do the addition we can do so with normal
1799 precision. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001800 if (fs == opOK)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001801 fs = addOrSubtract(addend, rounding_mode, false);
1802 }
1803
1804 return fs;
1805}
1806
Owen Andersona40319b2012-08-13 23:32:49 +00001807/* Rounding-mode corrrect round to integral value. */
Tim Shen85de51d2016-10-25 19:55:59 +00001808IEEEFloat::opStatus IEEEFloat::roundToIntegral(roundingMode rounding_mode) {
Owen Andersona40319b2012-08-13 23:32:49 +00001809 opStatus fs;
Owen Andersona40319b2012-08-13 23:32:49 +00001810
Owen Anderson352dfff2012-08-15 18:28:45 +00001811 // If the exponent is large enough, we know that this value is already
1812 // integral, and the arithmetic below would potentially cause it to saturate
1813 // to +/-Inf. Bail out early instead.
Michael Gottesman8136c382013-06-26 23:17:28 +00001814 if (isFiniteNonZero() && exponent+1 >= (int)semanticsPrecision(*semantics))
Owen Anderson352dfff2012-08-15 18:28:45 +00001815 return opOK;
1816
Owen Andersona40319b2012-08-13 23:32:49 +00001817 // The algorithm here is quite simple: we add 2^(p-1), where p is the
1818 // precision of our format, and then subtract it back off again. The choice
1819 // of rounding modes for the addition/subtraction determines the rounding mode
1820 // for our integral rounding as well.
Owen Andersonbe7e2972012-08-15 16:42:53 +00001821 // NOTE: When the input value is negative, we do subtraction followed by
Owen Anderson1ff74b02012-08-15 05:39:46 +00001822 // addition instead.
Owen Anderson0b357222012-08-14 18:51:15 +00001823 APInt IntegerConstant(NextPowerOf2(semanticsPrecision(*semantics)), 1);
1824 IntegerConstant <<= semanticsPrecision(*semantics)-1;
Tim Shen85de51d2016-10-25 19:55:59 +00001825 IEEEFloat MagicConstant(*semantics);
Owen Andersona40319b2012-08-13 23:32:49 +00001826 fs = MagicConstant.convertFromAPInt(IntegerConstant, false,
1827 rmNearestTiesToEven);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00001828 MagicConstant.sign = sign;
Owen Anderson1ff74b02012-08-15 05:39:46 +00001829
Owen Andersona40319b2012-08-13 23:32:49 +00001830 if (fs != opOK)
1831 return fs;
1832
Owen Anderson1ff74b02012-08-15 05:39:46 +00001833 // Preserve the input sign so that we can handle 0.0/-0.0 cases correctly.
1834 bool inputSign = isNegative();
1835
Owen Andersona40319b2012-08-13 23:32:49 +00001836 fs = add(MagicConstant, rounding_mode);
1837 if (fs != opOK && fs != opInexact)
1838 return fs;
1839
1840 fs = subtract(MagicConstant, rounding_mode);
Owen Anderson1ff74b02012-08-15 05:39:46 +00001841
1842 // Restore the input sign.
1843 if (inputSign != isNegative())
1844 changeSign();
1845
Owen Andersona40319b2012-08-13 23:32:49 +00001846 return fs;
1847}
1848
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00001849
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001850/* Comparison requires normalized numbers. */
Tim Shen85de51d2016-10-25 19:55:59 +00001851IEEEFloat::cmpResult IEEEFloat::compare(const IEEEFloat &rhs) const {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001852 cmpResult result;
1853
1854 assert(semantics == rhs.semantics);
1855
Michael Gottesman9b877e12013-06-24 09:57:57 +00001856 switch (PackCategoriesIntoKey(category, rhs.category)) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001857 default:
Craig Topper2617dcc2014-04-15 06:32:26 +00001858 llvm_unreachable(nullptr);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001859
Michael Gottesman9b877e12013-06-24 09:57:57 +00001860 case PackCategoriesIntoKey(fcNaN, fcZero):
1861 case PackCategoriesIntoKey(fcNaN, fcNormal):
1862 case PackCategoriesIntoKey(fcNaN, fcInfinity):
1863 case PackCategoriesIntoKey(fcNaN, fcNaN):
1864 case PackCategoriesIntoKey(fcZero, fcNaN):
1865 case PackCategoriesIntoKey(fcNormal, fcNaN):
1866 case PackCategoriesIntoKey(fcInfinity, fcNaN):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001867 return cmpUnordered;
1868
Michael Gottesman9b877e12013-06-24 09:57:57 +00001869 case PackCategoriesIntoKey(fcInfinity, fcNormal):
1870 case PackCategoriesIntoKey(fcInfinity, fcZero):
1871 case PackCategoriesIntoKey(fcNormal, fcZero):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001872 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001873 return cmpLessThan;
1874 else
1875 return cmpGreaterThan;
1876
Michael Gottesman9b877e12013-06-24 09:57:57 +00001877 case PackCategoriesIntoKey(fcNormal, fcInfinity):
1878 case PackCategoriesIntoKey(fcZero, fcInfinity):
1879 case PackCategoriesIntoKey(fcZero, fcNormal):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001880 if (rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001881 return cmpGreaterThan;
1882 else
1883 return cmpLessThan;
1884
Michael Gottesman9b877e12013-06-24 09:57:57 +00001885 case PackCategoriesIntoKey(fcInfinity, fcInfinity):
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001886 if (sign == rhs.sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001887 return cmpEqual;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001888 else if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001889 return cmpLessThan;
1890 else
1891 return cmpGreaterThan;
1892
Michael Gottesman9b877e12013-06-24 09:57:57 +00001893 case PackCategoriesIntoKey(fcZero, fcZero):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001894 return cmpEqual;
1895
Michael Gottesman9b877e12013-06-24 09:57:57 +00001896 case PackCategoriesIntoKey(fcNormal, fcNormal):
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001897 break;
1898 }
1899
1900 /* Two normal numbers. Do they have the same sign? */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001901 if (sign != rhs.sign) {
1902 if (sign)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001903 result = cmpLessThan;
1904 else
1905 result = cmpGreaterThan;
1906 } else {
1907 /* Compare absolute values; invert result if negative. */
1908 result = compareAbsoluteValue(rhs);
1909
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001910 if (sign) {
1911 if (result == cmpLessThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001912 result = cmpGreaterThan;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00001913 else if (result == cmpGreaterThan)
Neil Booth9acbf5a2007-09-26 21:33:42 +00001914 result = cmpLessThan;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001915 }
1916 }
1917
1918 return result;
1919}
1920
Tim Shen85de51d2016-10-25 19:55:59 +00001921/// IEEEFloat::convert - convert a value of one floating point type to another.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00001922/// The return value corresponds to the IEEE754 exceptions. *losesInfo
1923/// records whether the transformation lost information, i.e. whether
1924/// converting the result back to the original type will produce the
1925/// original value (this is almost the same as return value==fsOK, but there
1926/// are edge cases where this is not so).
1927
Tim Shen85de51d2016-10-25 19:55:59 +00001928IEEEFloat::opStatus IEEEFloat::convert(const fltSemantics &toSemantics,
1929 roundingMode rounding_mode,
1930 bool *losesInfo) {
Neil Bootha8d72692007-09-22 02:56:19 +00001931 lostFraction lostFraction;
1932 unsigned int newPartCount, oldPartCount;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001933 opStatus fs;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001934 int shift;
1935 const fltSemantics &fromSemantics = *semantics;
Neil Booth9acbf5a2007-09-26 21:33:42 +00001936
Neil Bootha8d72692007-09-22 02:56:19 +00001937 lostFraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001938 newPartCount = partCountForBits(toSemantics.precision + 1);
Neil Bootha8d72692007-09-22 02:56:19 +00001939 oldPartCount = partCount();
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001940 shift = toSemantics.precision - fromSemantics.precision;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001941
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001942 bool X86SpecialNan = false;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001943 if (&fromSemantics == &semX87DoubleExtended &&
1944 &toSemantics != &semX87DoubleExtended && category == fcNaN &&
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001945 (!(*significandParts() & 0x8000000000000000ULL) ||
1946 !(*significandParts() & 0x4000000000000000ULL))) {
1947 // x86 has some unusual NaNs which cannot be represented in any other
1948 // format; note them here.
1949 X86SpecialNan = true;
1950 }
1951
Ulrich Weigand1d4dbda2013-07-16 13:03:25 +00001952 // If this is a truncation of a denormal number, and the target semantics
1953 // has larger exponent range than the source semantics (this can happen
1954 // when truncating from PowerPC double-double to double format), the
1955 // right shift could lose result mantissa bits. Adjust exponent instead
1956 // of performing excessive shift.
1957 if (shift < 0 && isFiniteNonZero()) {
1958 int exponentChange = significandMSB() + 1 - fromSemantics.precision;
1959 if (exponent + exponentChange < toSemantics.minExponent)
1960 exponentChange = toSemantics.minExponent - exponent;
1961 if (exponentChange < shift)
1962 exponentChange = shift;
1963 if (exponentChange < 0) {
1964 shift -= exponentChange;
1965 exponent += exponentChange;
1966 }
1967 }
1968
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001969 // If this is a truncation, perform the shift before we narrow the storage.
Michael Gottesman8136c382013-06-26 23:17:28 +00001970 if (shift < 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001971 lostFraction = shiftRight(significandParts(), oldPartCount, -shift);
1972
1973 // Fix the storage so it can hold to new value.
Neil Bootha8d72692007-09-22 02:56:19 +00001974 if (newPartCount > oldPartCount) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001975 // The new type requires more storage; make it available.
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001976 integerPart *newParts;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001977 newParts = new integerPart[newPartCount];
1978 APInt::tcSet(newParts, 0, newPartCount);
Michael Gottesman8136c382013-06-26 23:17:28 +00001979 if (isFiniteNonZero() || category==fcNaN)
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00001980 APInt::tcAssign(newParts, significandParts(), oldPartCount);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001981 freeSignificand();
1982 significand.parts = newParts;
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001983 } else if (newPartCount == 1 && oldPartCount != 1) {
1984 // Switch to built-in storage for a single part.
1985 integerPart newPart = 0;
Michael Gottesman8136c382013-06-26 23:17:28 +00001986 if (isFiniteNonZero() || category==fcNaN)
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001987 newPart = significandParts()[0];
1988 freeSignificand();
1989 significand.part = newPart;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00001990 }
1991
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001992 // Now that we have the right storage, switch the semantics.
1993 semantics = &toSemantics;
1994
1995 // If this is an extension, perform the shift now that the storage is
1996 // available.
Michael Gottesman8136c382013-06-26 23:17:28 +00001997 if (shift > 0 && (isFiniteNonZero() || category==fcNaN))
Eli Friedmana84ad7d2011-11-26 03:38:02 +00001998 APInt::tcShiftLeft(significandParts(), newPartCount, shift);
1999
Michael Gottesman8136c382013-06-26 23:17:28 +00002000 if (isFiniteNonZero()) {
Neil Bootha8d72692007-09-22 02:56:19 +00002001 fs = normalize(rounding_mode, lostFraction);
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002002 *losesInfo = (fs != opOK);
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002003 } else if (category == fcNaN) {
Eli Friedmana84ad7d2011-11-26 03:38:02 +00002004 *losesInfo = lostFraction != lfExactlyZero || X86SpecialNan;
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002005
2006 // For x87 extended precision, we want to make a NaN, not a special NaN if
2007 // the input wasn't special either.
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002008 if (!X86SpecialNan && semantics == &semX87DoubleExtended)
Benjamin Kramerb361adb2013-01-25 17:01:00 +00002009 APInt::tcSetBit(significandParts(), semantics->precision - 1);
2010
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00002011 // gcc forces the Quiet bit on, which means (float)(double)(float_sNan)
2012 // does not give you back the same bits. This is dubious, and we
2013 // don't currently do it. You're really supposed to get
2014 // an invalid operation signal at runtime, but nobody does that.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002015 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002016 } else {
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002017 *losesInfo = false;
Eli Friedman31f01162011-11-28 18:50:37 +00002018 fs = opOK;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002019 }
2020
2021 return fs;
2022}
2023
2024/* Convert a floating point number to an integer according to the
2025 rounding mode. If the rounded integer value is out of range this
Neil Booth618d0fc2007-11-01 22:43:37 +00002026 returns an invalid operation exception and the contents of the
2027 destination parts are unspecified. If the rounded value is in
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002028 range but the floating point number is not the exact integer, the C
2029 standard doesn't require an inexact exception to be raised. IEEE
2030 854 does require it so we do that.
2031
2032 Note that for conversions to integer type the C standard requires
2033 round-to-zero to always be used. */
Tim Shen85de51d2016-10-25 19:55:59 +00002034IEEEFloat::opStatus IEEEFloat::convertToSignExtendedInteger(
Simon Pilgrim00b34992017-03-20 14:40:12 +00002035 MutableArrayRef<integerPart> parts, unsigned int width, bool isSigned,
Tim Shen85de51d2016-10-25 19:55:59 +00002036 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002037 lostFraction lost_fraction;
2038 const integerPart *src;
2039 unsigned int dstPartsCount, truncatedBits;
2040
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002041 *isExact = false;
2042
Neil Booth618d0fc2007-11-01 22:43:37 +00002043 /* Handle the three special cases first. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002044 if (category == fcInfinity || category == fcNaN)
Neil Booth618d0fc2007-11-01 22:43:37 +00002045 return opInvalidOp;
2046
2047 dstPartsCount = partCountForBits(width);
Simon Pilgrim00b34992017-03-20 14:40:12 +00002048 assert(dstPartsCount <= parts.size() && "Integer too big");
Neil Booth618d0fc2007-11-01 22:43:37 +00002049
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002050 if (category == fcZero) {
Simon Pilgrim00b34992017-03-20 14:40:12 +00002051 APInt::tcSet(parts.data(), 0, dstPartsCount);
Dale Johannesen7221af32008-10-07 00:40:01 +00002052 // Negative zero can't be represented as an int.
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002053 *isExact = !sign;
2054 return opOK;
Neil Booth618d0fc2007-11-01 22:43:37 +00002055 }
2056
2057 src = significandParts();
2058
2059 /* Step 1: place our absolute value, with any fraction truncated, in
2060 the destination. */
2061 if (exponent < 0) {
2062 /* Our absolute value is less than one; truncate everything. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002063 APInt::tcSet(parts.data(), 0, dstPartsCount);
Dale Johannesen740e9872009-01-19 21:17:05 +00002064 /* For exponent -1 the integer bit represents .5, look at that.
2065 For smaller exponents leftmost truncated bit is 0. */
2066 truncatedBits = semantics->precision -1U - exponent;
Neil Booth618d0fc2007-11-01 22:43:37 +00002067 } else {
2068 /* We want the most significant (exponent + 1) bits; the rest are
2069 truncated. */
2070 unsigned int bits = exponent + 1U;
2071
2072 /* Hopelessly large in magnitude? */
2073 if (bits > width)
2074 return opInvalidOp;
2075
2076 if (bits < semantics->precision) {
2077 /* We truncate (semantics->precision - bits) bits. */
2078 truncatedBits = semantics->precision - bits;
Simon Pilgrim00b34992017-03-20 14:40:12 +00002079 APInt::tcExtract(parts.data(), dstPartsCount, src, bits, truncatedBits);
Neil Booth618d0fc2007-11-01 22:43:37 +00002080 } else {
2081 /* We want at least as many bits as are available. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002082 APInt::tcExtract(parts.data(), dstPartsCount, src, semantics->precision,
2083 0);
2084 APInt::tcShiftLeft(parts.data(), dstPartsCount,
2085 bits - semantics->precision);
Neil Booth618d0fc2007-11-01 22:43:37 +00002086 truncatedBits = 0;
2087 }
2088 }
2089
2090 /* Step 2: work out any lost fraction, and increment the absolute
2091 value if we would round away from zero. */
2092 if (truncatedBits) {
2093 lost_fraction = lostFractionThroughTruncation(src, partCount(),
2094 truncatedBits);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002095 if (lost_fraction != lfExactlyZero &&
2096 roundAwayFromZero(rounding_mode, lost_fraction, truncatedBits)) {
Simon Pilgrim00b34992017-03-20 14:40:12 +00002097 if (APInt::tcIncrement(parts.data(), dstPartsCount))
Neil Booth618d0fc2007-11-01 22:43:37 +00002098 return opInvalidOp; /* Overflow. */
2099 }
2100 } else {
2101 lost_fraction = lfExactlyZero;
2102 }
2103
2104 /* Step 3: check if we fit in the destination. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002105 unsigned int omsb = APInt::tcMSB(parts.data(), dstPartsCount) + 1;
Neil Booth618d0fc2007-11-01 22:43:37 +00002106
2107 if (sign) {
2108 if (!isSigned) {
2109 /* Negative numbers cannot be represented as unsigned. */
2110 if (omsb != 0)
2111 return opInvalidOp;
2112 } else {
2113 /* It takes omsb bits to represent the unsigned integer value.
2114 We lose a bit for the sign, but care is needed as the
2115 maximally negative integer is a special case. */
Simon Pilgrim00b34992017-03-20 14:40:12 +00002116 if (omsb == width &&
2117 APInt::tcLSB(parts.data(), dstPartsCount) + 1 != omsb)
Neil Booth618d0fc2007-11-01 22:43:37 +00002118 return opInvalidOp;
2119
2120 /* This case can happen because of rounding. */
2121 if (omsb > width)
2122 return opInvalidOp;
2123 }
2124
Simon Pilgrim00b34992017-03-20 14:40:12 +00002125 APInt::tcNegate (parts.data(), dstPartsCount);
Neil Booth618d0fc2007-11-01 22:43:37 +00002126 } else {
2127 if (omsb >= width + !isSigned)
2128 return opInvalidOp;
2129 }
2130
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002131 if (lost_fraction == lfExactlyZero) {
2132 *isExact = true;
Neil Booth618d0fc2007-11-01 22:43:37 +00002133 return opOK;
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002134 } else
Neil Booth618d0fc2007-11-01 22:43:37 +00002135 return opInexact;
2136}
2137
2138/* Same as convertToSignExtendedInteger, except we provide
2139 deterministic values in case of an invalid operation exception,
2140 namely zero for NaNs and the minimal or maximal value respectively
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002141 for underflow or overflow.
2142 The *isExact output tells whether the result is exact, in the sense
2143 that converting it back to the original floating point type produces
2144 the original value. This is almost equivalent to result==opOK,
2145 except for negative zeroes.
2146*/
Simon Pilgrim00b34992017-03-20 14:40:12 +00002147IEEEFloat::opStatus
2148IEEEFloat::convertToInteger(MutableArrayRef<integerPart> parts,
2149 unsigned int width, bool isSigned,
2150 roundingMode rounding_mode, bool *isExact) const {
Neil Booth618d0fc2007-11-01 22:43:37 +00002151 opStatus fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002152
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002153 fs = convertToSignExtendedInteger(parts, width, isSigned, rounding_mode,
Dale Johannesen4f0bd682008-10-09 23:00:39 +00002154 isExact);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002155
Neil Booth618d0fc2007-11-01 22:43:37 +00002156 if (fs == opInvalidOp) {
2157 unsigned int bits, dstPartsCount;
2158
2159 dstPartsCount = partCountForBits(width);
Simon Pilgrim00b34992017-03-20 14:40:12 +00002160 assert(dstPartsCount <= parts.size() && "Integer too big");
Neil Booth618d0fc2007-11-01 22:43:37 +00002161
2162 if (category == fcNaN)
2163 bits = 0;
2164 else if (sign)
2165 bits = isSigned;
2166 else
2167 bits = width - isSigned;
2168
Simon Pilgrim00b34992017-03-20 14:40:12 +00002169 APInt::tcSetLeastSignificantBits(parts.data(), dstPartsCount, bits);
Neil Booth618d0fc2007-11-01 22:43:37 +00002170 if (sign && isSigned)
Simon Pilgrim00b34992017-03-20 14:40:12 +00002171 APInt::tcShiftLeft(parts.data(), dstPartsCount, width - 1);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002172 }
2173
Neil Booth618d0fc2007-11-01 22:43:37 +00002174 return fs;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002175}
2176
Neil Booth6c1c8582007-10-07 12:07:53 +00002177/* Convert an unsigned integer SRC to a floating point number,
2178 rounding according to ROUNDING_MODE. The sign of the floating
2179 point number is not modified. */
Tim Shen85de51d2016-10-25 19:55:59 +00002180IEEEFloat::opStatus IEEEFloat::convertFromUnsignedParts(
2181 const integerPart *src, unsigned int srcCount, roundingMode rounding_mode) {
Neil Booth49c6aab2007-10-08 14:39:42 +00002182 unsigned int omsb, precision, dstCount;
Neil Booth6c1c8582007-10-07 12:07:53 +00002183 integerPart *dst;
Neil Booth49c6aab2007-10-08 14:39:42 +00002184 lostFraction lost_fraction;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002185
2186 category = fcNormal;
Neil Booth49c6aab2007-10-08 14:39:42 +00002187 omsb = APInt::tcMSB(src, srcCount) + 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002188 dst = significandParts();
2189 dstCount = partCount();
Neil Booth49c6aab2007-10-08 14:39:42 +00002190 precision = semantics->precision;
Neil Booth6c1c8582007-10-07 12:07:53 +00002191
Nick Lewyckyf66daac2011-10-03 21:30:08 +00002192 /* We want the most significant PRECISION bits of SRC. There may not
Neil Booth49c6aab2007-10-08 14:39:42 +00002193 be that many; extract what we can. */
2194 if (precision <= omsb) {
2195 exponent = omsb - 1;
Neil Booth6c1c8582007-10-07 12:07:53 +00002196 lost_fraction = lostFractionThroughTruncation(src, srcCount,
Neil Booth49c6aab2007-10-08 14:39:42 +00002197 omsb - precision);
2198 APInt::tcExtract(dst, dstCount, src, precision, omsb - precision);
2199 } else {
2200 exponent = precision - 1;
2201 lost_fraction = lfExactlyZero;
2202 APInt::tcExtract(dst, dstCount, src, omsb, 0);
Neil Booth6c1c8582007-10-07 12:07:53 +00002203 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002204
2205 return normalize(rounding_mode, lost_fraction);
2206}
2207
Tim Shen85de51d2016-10-25 19:55:59 +00002208IEEEFloat::opStatus IEEEFloat::convertFromAPInt(const APInt &Val, bool isSigned,
2209 roundingMode rounding_mode) {
Dan Gohman35723eb2008-02-29 01:26:11 +00002210 unsigned int partCount = Val.getNumWords();
2211 APInt api = Val;
2212
2213 sign = false;
2214 if (isSigned && api.isNegative()) {
2215 sign = true;
2216 api = -api;
2217 }
2218
2219 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
2220}
2221
Neil Booth03f58ab2007-10-07 12:15:41 +00002222/* Convert a two's complement integer SRC to a floating point number,
2223 rounding according to ROUNDING_MODE. ISSIGNED is true if the
2224 integer is signed, in which case it must be sign-extended. */
Tim Shen85de51d2016-10-25 19:55:59 +00002225IEEEFloat::opStatus
2226IEEEFloat::convertFromSignExtendedInteger(const integerPart *src,
2227 unsigned int srcCount, bool isSigned,
2228 roundingMode rounding_mode) {
Neil Booth03f58ab2007-10-07 12:15:41 +00002229 opStatus status;
2230
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002231 if (isSigned &&
2232 APInt::tcExtractBit(src, srcCount * integerPartWidth - 1)) {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002233 integerPart *copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002234
2235 /* If we're signed and negative negate a copy. */
2236 sign = true;
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002237 copy = new integerPart[srcCount];
Neil Booth03f58ab2007-10-07 12:15:41 +00002238 APInt::tcAssign(copy, src, srcCount);
2239 APInt::tcNegate(copy, srcCount);
2240 status = convertFromUnsignedParts(copy, srcCount, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002241 delete [] copy;
Neil Booth03f58ab2007-10-07 12:15:41 +00002242 } else {
2243 sign = false;
2244 status = convertFromUnsignedParts(src, srcCount, rounding_mode);
2245 }
2246
2247 return status;
2248}
2249
Neil Booth5f009732007-10-07 11:45:55 +00002250/* FIXME: should this just take a const APInt reference? */
Tim Shen85de51d2016-10-25 19:55:59 +00002251IEEEFloat::opStatus
2252IEEEFloat::convertFromZeroExtendedInteger(const integerPart *parts,
2253 unsigned int width, bool isSigned,
2254 roundingMode rounding_mode) {
Dale Johannesen42305122007-09-21 22:09:37 +00002255 unsigned int partCount = partCountForBits(width);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002256 APInt api = APInt(width, makeArrayRef(parts, partCount));
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002257
2258 sign = false;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002259 if (isSigned && APInt::tcExtractBit(parts, width - 1)) {
Dale Johannesen28a2c4a2007-09-30 18:17:01 +00002260 sign = true;
2261 api = -api;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002262 }
2263
Neil Boothba205222007-10-07 12:10:57 +00002264 return convertFromUnsignedParts(api.getRawData(), partCount, rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002265}
2266
Tim Shen85de51d2016-10-25 19:55:59 +00002267IEEEFloat::opStatus
2268IEEEFloat::convertFromHexadecimalString(StringRef s,
2269 roundingMode rounding_mode) {
Erick Tryzelaara9680df2009-08-18 18:20:37 +00002270 lostFraction lost_fraction = lfExactlyZero;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002271
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002272 category = fcNormal;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002273 zeroSignificand();
2274 exponent = 0;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002275
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002276 integerPart *significand = significandParts();
2277 unsigned partsCount = partCount();
2278 unsigned bitPos = partsCount * integerPartWidth;
2279 bool computedTrailingFraction = false;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002280
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002281 // Skip leading zeroes and any (hexa)decimal point.
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002282 StringRef::iterator begin = s.begin();
2283 StringRef::iterator end = s.end();
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002284 StringRef::iterator dot;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002285 StringRef::iterator p = skipLeadingZeroesAndAnyDot(begin, end, &dot);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002286 StringRef::iterator firstSignificantDigit = p;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002287
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002288 while (p != end) {
Dale Johannesenfa483722008-05-14 22:53:25 +00002289 integerPart hex_value;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002290
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002291 if (*p == '.') {
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002292 assert(dot == end && "String contains multiple dots");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002293 dot = p++;
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002294 continue;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002295 }
2296
2297 hex_value = hexDigitValue(*p);
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002298 if (hex_value == -1U)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002299 break;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002300
2301 p++;
2302
Eli Friedmand2eb07a2013-07-17 22:17:29 +00002303 // Store the number while we have space.
2304 if (bitPos) {
2305 bitPos -= 4;
2306 hex_value <<= bitPos % integerPartWidth;
2307 significand[bitPos / integerPartWidth] |= hex_value;
2308 } else if (!computedTrailingFraction) {
2309 lost_fraction = trailingHexadecimalFraction(p, end, hex_value);
2310 computedTrailingFraction = true;
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002311 }
2312 }
2313
2314 /* Hex floats require an exponent but not a hexadecimal point. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002315 assert(p != end && "Hex strings require an exponent");
2316 assert((*p == 'p' || *p == 'P') && "Invalid character in significand");
2317 assert(p != begin && "Significand has no digits");
2318 assert((dot == end || p - begin != 1) && "Significand has no digits");
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002319
2320 /* Ignore the exponent if we are zero. */
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002321 if (p != firstSignificantDigit) {
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002322 int expAdjustment;
2323
2324 /* Implicit hexadecimal point? */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002325 if (dot == end)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002326 dot = p;
2327
2328 /* Calculate the exponent adjustment implicit in the number of
2329 significant digits. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002330 expAdjustment = static_cast<int>(dot - firstSignificantDigit);
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002331 if (expAdjustment < 0)
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002332 expAdjustment++;
2333 expAdjustment = expAdjustment * 4 - 1;
2334
2335 /* Adjust for writing the significand starting at the most
2336 significant nibble. */
2337 expAdjustment += semantics->precision;
2338 expAdjustment -= partsCount * integerPartWidth;
2339
2340 /* Adjust for the given exponent. */
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002341 exponent = totalExponent(p + 1, end, expAdjustment);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002342 }
2343
2344 return normalize(rounding_mode, lost_fraction);
2345}
2346
Tim Shen85de51d2016-10-25 19:55:59 +00002347IEEEFloat::opStatus
2348IEEEFloat::roundSignificandWithExponent(const integerPart *decSigParts,
2349 unsigned sigPartCount, int exp,
2350 roundingMode rounding_mode) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002351 unsigned int parts, pow5PartCount;
Tamas Berghammerb6b0ddf2015-07-09 10:13:39 +00002352 fltSemantics calcSemantics = { 32767, -32767, 0, 0 };
Neil Boothb93d90e2007-10-12 16:02:31 +00002353 integerPart pow5Parts[maxPowerOfFiveParts];
2354 bool isNearest;
2355
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002356 isNearest = (rounding_mode == rmNearestTiesToEven ||
2357 rounding_mode == rmNearestTiesToAway);
Neil Boothb93d90e2007-10-12 16:02:31 +00002358
2359 parts = partCountForBits(semantics->precision + 11);
2360
2361 /* Calculate pow(5, abs(exp)). */
2362 pow5PartCount = powerOf5(pow5Parts, exp >= 0 ? exp: -exp);
2363
2364 for (;; parts *= 2) {
2365 opStatus sigStatus, powStatus;
2366 unsigned int excessPrecision, truncatedBits;
2367
2368 calcSemantics.precision = parts * integerPartWidth - 1;
2369 excessPrecision = calcSemantics.precision - semantics->precision;
2370 truncatedBits = excessPrecision;
2371
Tim Shen139a58f2016-10-27 22:52:40 +00002372 IEEEFloat decSig(calcSemantics, uninitialized);
2373 decSig.makeZero(sign);
Tim Shen85de51d2016-10-25 19:55:59 +00002374 IEEEFloat pow5(calcSemantics);
Neil Boothb93d90e2007-10-12 16:02:31 +00002375
2376 sigStatus = decSig.convertFromUnsignedParts(decSigParts, sigPartCount,
2377 rmNearestTiesToEven);
2378 powStatus = pow5.convertFromUnsignedParts(pow5Parts, pow5PartCount,
2379 rmNearestTiesToEven);
2380 /* Add exp, as 10^n = 5^n * 2^n. */
2381 decSig.exponent += exp;
2382
2383 lostFraction calcLostFraction;
Evan Cheng82b9e962008-05-02 21:15:08 +00002384 integerPart HUerr, HUdistance;
2385 unsigned int powHUerr;
Neil Boothb93d90e2007-10-12 16:02:31 +00002386
2387 if (exp >= 0) {
2388 /* multiplySignificand leaves the precision-th bit set to 1. */
Craig Topperc10719f2014-04-07 04:17:22 +00002389 calcLostFraction = decSig.multiplySignificand(pow5, nullptr);
Neil Boothb93d90e2007-10-12 16:02:31 +00002390 powHUerr = powStatus != opOK;
2391 } else {
2392 calcLostFraction = decSig.divideSignificand(pow5);
2393 /* Denormal numbers have less precision. */
2394 if (decSig.exponent < semantics->minExponent) {
2395 excessPrecision += (semantics->minExponent - decSig.exponent);
2396 truncatedBits = excessPrecision;
2397 if (excessPrecision > calcSemantics.precision)
2398 excessPrecision = calcSemantics.precision;
2399 }
2400 /* Extra half-ulp lost in reciprocal of exponent. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002401 powHUerr = (powStatus == opOK && calcLostFraction == lfExactlyZero) ? 0:2;
Neil Boothb93d90e2007-10-12 16:02:31 +00002402 }
2403
2404 /* Both multiplySignificand and divideSignificand return the
2405 result with the integer bit set. */
Evan Cheng67c90212009-10-27 21:35:42 +00002406 assert(APInt::tcExtractBit
2407 (decSig.significandParts(), calcSemantics.precision - 1) == 1);
Neil Boothb93d90e2007-10-12 16:02:31 +00002408
2409 HUerr = HUerrBound(calcLostFraction != lfExactlyZero, sigStatus != opOK,
2410 powHUerr);
2411 HUdistance = 2 * ulpsFromBoundary(decSig.significandParts(),
2412 excessPrecision, isNearest);
2413
2414 /* Are we guaranteed to round correctly if we truncate? */
2415 if (HUdistance >= HUerr) {
2416 APInt::tcExtract(significandParts(), partCount(), decSig.significandParts(),
2417 calcSemantics.precision - excessPrecision,
2418 excessPrecision);
2419 /* Take the exponent of decSig. If we tcExtract-ed less bits
2420 above we must adjust our exponent to compensate for the
2421 implicit right shift. */
2422 exponent = (decSig.exponent + semantics->precision
2423 - (calcSemantics.precision - excessPrecision));
2424 calcLostFraction = lostFractionThroughTruncation(decSig.significandParts(),
2425 decSig.partCount(),
2426 truncatedBits);
2427 return normalize(rounding_mode, calcLostFraction);
2428 }
2429 }
2430}
2431
Tim Shen85de51d2016-10-25 19:55:59 +00002432IEEEFloat::opStatus
2433IEEEFloat::convertFromDecimalString(StringRef str, roundingMode rounding_mode) {
Neil Booth4ed401b2007-10-14 10:16:12 +00002434 decimalInfo D;
Neil Boothb93d90e2007-10-12 16:02:31 +00002435 opStatus fs;
2436
Neil Booth4ed401b2007-10-14 10:16:12 +00002437 /* Scan the text. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002438 StringRef::iterator p = str.begin();
2439 interpretDecimal(p, str.end(), &D);
Neil Boothb93d90e2007-10-12 16:02:31 +00002440
Neil Booth91305512007-10-15 15:00:55 +00002441 /* Handle the quick cases. First the case of no significant digits,
2442 i.e. zero, and then exponents that are obviously too large or too
2443 small. Writing L for log 10 / log 2, a number d.ddddd*10^exp
2444 definitely overflows if
2445
2446 (exp - 1) * L >= maxExponent
2447
2448 and definitely underflows to zero where
2449
2450 (exp + 1) * L <= minExponent - precision
2451
2452 With integer arithmetic the tightest bounds for L are
2453
2454 93/28 < L < 196/59 [ numerator <= 256 ]
2455 42039/12655 < L < 28738/8651 [ numerator <= 65536 ]
2456 */
2457
Michael Gottesman228156c2013-07-01 23:54:08 +00002458 // Test if we have a zero number allowing for strings with no null terminators
2459 // and zero decimals with non-zero exponents.
Simon Pilgrima2849592017-03-20 13:53:59 +00002460 //
Michael Gottesman228156c2013-07-01 23:54:08 +00002461 // We computed firstSigDigit by ignoring all zeros and dots. Thus if
2462 // D->firstSigDigit equals str.end(), every digit must be a zero and there can
2463 // be at most one dot. On the other hand, if we have a zero with a non-zero
2464 // exponent, then we know that D.firstSigDigit will be non-numeric.
Michael Gottesman94d61952013-07-02 15:50:05 +00002465 if (D.firstSigDigit == str.end() || decDigitValue(*D.firstSigDigit) >= 10U) {
Neil Boothb93d90e2007-10-12 16:02:31 +00002466 category = fcZero;
2467 fs = opOK;
John McCallb42cc682010-02-26 22:20:41 +00002468
2469 /* Check whether the normalized exponent is high enough to overflow
2470 max during the log-rebasing in the max-exponent check below. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002471 } else if (D.normalizedExponent - 1 > INT_MAX / 42039) {
John McCallb42cc682010-02-26 22:20:41 +00002472 fs = handleOverflow(rounding_mode);
2473
2474 /* If it wasn't, then it also wasn't high enough to overflow max
2475 during the log-rebasing in the min-exponent check. Check that it
2476 won't overflow min in either check, then perform the min-exponent
2477 check. */
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00002478 } else if (D.normalizedExponent - 1 < INT_MIN / 42039 ||
John McCallb42cc682010-02-26 22:20:41 +00002479 (D.normalizedExponent + 1) * 28738 <=
2480 8651 * (semantics->minExponent - (int) semantics->precision)) {
Neil Booth91305512007-10-15 15:00:55 +00002481 /* Underflow to zero and round. */
Michael Gottesman30a90eb2013-07-27 21:49:21 +00002482 category = fcNormal;
Neil Booth91305512007-10-15 15:00:55 +00002483 zeroSignificand();
2484 fs = normalize(rounding_mode, lfLessThanHalf);
John McCallb42cc682010-02-26 22:20:41 +00002485
2486 /* We can finally safely perform the max-exponent check. */
Neil Booth91305512007-10-15 15:00:55 +00002487 } else if ((D.normalizedExponent - 1) * 42039
2488 >= 12655 * semantics->maxExponent) {
2489 /* Overflow and round. */
2490 fs = handleOverflow(rounding_mode);
Neil Boothb93d90e2007-10-12 16:02:31 +00002491 } else {
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002492 integerPart *decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002493 unsigned int partCount;
Neil Boothb93d90e2007-10-12 16:02:31 +00002494
Neil Booth4ed401b2007-10-14 10:16:12 +00002495 /* A tight upper bound on number of bits required to hold an
Neil Booth91305512007-10-15 15:00:55 +00002496 N-digit decimal integer is N * 196 / 59. Allocate enough space
Neil Booth4ed401b2007-10-14 10:16:12 +00002497 to hold the full significand, and an extra part required by
2498 tcMultiplyPart. */
Evan Cheng82b9e962008-05-02 21:15:08 +00002499 partCount = static_cast<unsigned int>(D.lastSigDigit - D.firstSigDigit) + 1;
Neil Booth91305512007-10-15 15:00:55 +00002500 partCount = partCountForBits(1 + 196 * partCount / 59);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002501 decSignificand = new integerPart[partCount + 1];
Neil Booth4ed401b2007-10-14 10:16:12 +00002502 partCount = 0;
Neil Boothb93d90e2007-10-12 16:02:31 +00002503
Neil Booth4ed401b2007-10-14 10:16:12 +00002504 /* Convert to binary efficiently - we do almost all multiplication
2505 in an integerPart. When this would overflow do we do a single
2506 bignum multiplication, and then revert again to multiplication
2507 in an integerPart. */
2508 do {
2509 integerPart decValue, val, multiplier;
2510
2511 val = 0;
2512 multiplier = 1;
2513
2514 do {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002515 if (*p == '.') {
Neil Booth4ed401b2007-10-14 10:16:12 +00002516 p++;
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002517 if (p == str.end()) {
2518 break;
2519 }
2520 }
Neil Booth4ed401b2007-10-14 10:16:12 +00002521 decValue = decDigitValue(*p++);
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002522 assert(decValue < 10U && "Invalid character in significand");
Neil Booth4ed401b2007-10-14 10:16:12 +00002523 multiplier *= 10;
2524 val = val * 10 + decValue;
2525 /* The maximum number that can be multiplied by ten with any
2526 digit added without overflowing an integerPart. */
2527 } while (p <= D.lastSigDigit && multiplier <= (~ (integerPart) 0 - 9) / 10);
2528
2529 /* Multiply out the current part. */
2530 APInt::tcMultiplyPart(decSignificand, decSignificand, multiplier, val,
2531 partCount, partCount + 1, false);
2532
2533 /* If we used another part (likely but not guaranteed), increase
2534 the count. */
2535 if (decSignificand[partCount])
2536 partCount++;
2537 } while (p <= D.lastSigDigit);
Neil Boothb93d90e2007-10-12 16:02:31 +00002538
Neil Boothae077d22007-11-01 22:51:07 +00002539 category = fcNormal;
Neil Boothb93d90e2007-10-12 16:02:31 +00002540 fs = roundSignificandWithExponent(decSignificand, partCount,
Neil Booth4ed401b2007-10-14 10:16:12 +00002541 D.exponent, rounding_mode);
Dylan Noblesmith4e69e292014-08-26 02:03:33 +00002542
2543 delete [] decSignificand;
Neil Booth4ed401b2007-10-14 10:16:12 +00002544 }
Neil Boothb93d90e2007-10-12 16:02:31 +00002545
2546 return fs;
2547}
2548
Tim Shen85de51d2016-10-25 19:55:59 +00002549bool IEEEFloat::convertFromStringSpecials(StringRef str) {
Serguei Katkov768d6dd2017-12-19 04:27:39 +00002550 if (str.equals("inf") || str.equals("INFINITY") || str.equals("+Inf")) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002551 makeInf(false);
2552 return true;
2553 }
2554
Serguei Katkov768d6dd2017-12-19 04:27:39 +00002555 if (str.equals("-inf") || str.equals("-INFINITY") || str.equals("-Inf")) {
Michael Gottesman40e8a182013-06-24 09:58:05 +00002556 makeInf(true);
2557 return true;
2558 }
2559
2560 if (str.equals("nan") || str.equals("NaN")) {
2561 makeNaN(false, false);
2562 return true;
2563 }
2564
2565 if (str.equals("-nan") || str.equals("-NaN")) {
2566 makeNaN(false, true);
2567 return true;
2568 }
2569
2570 return false;
2571}
2572
Tim Shen85de51d2016-10-25 19:55:59 +00002573IEEEFloat::opStatus IEEEFloat::convertFromString(StringRef str,
2574 roundingMode rounding_mode) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002575 assert(!str.empty() && "Invalid string length");
Neil Booth06077e72007-10-14 10:29:28 +00002576
Michael Gottesman40e8a182013-06-24 09:58:05 +00002577 // Handle special cases.
2578 if (convertFromStringSpecials(str))
2579 return opOK;
2580
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002581 /* Handle a leading minus sign. */
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002582 StringRef::iterator p = str.begin();
2583 size_t slen = str.size();
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002584 sign = *p == '-' ? 1 : 0;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002585 if (*p == '-' || *p == '+') {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002586 p++;
2587 slen--;
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002588 assert(slen && "String has no digits");
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002589 }
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002590
Dan Gohmanb452d4e2010-03-24 19:38:02 +00002591 if (slen >= 2 && p[0] == '0' && (p[1] == 'x' || p[1] == 'X')) {
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002592 assert(slen - 2 && "Invalid string");
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002593 return convertFromHexadecimalString(StringRef(p + 2, slen - 2),
Erick Tryzelaar19f63b22009-08-16 23:36:19 +00002594 rounding_mode);
2595 }
Bill Wendlingc6075402008-11-27 08:00:12 +00002596
Erick Tryzelaarda666c82009-08-20 23:30:43 +00002597 return convertFromDecimalString(StringRef(p, slen), rounding_mode);
Chris Lattnerfe02c1f2007-08-20 22:49:32 +00002598}
Dale Johannesena719a602007-08-24 00:56:33 +00002599
Neil Booth8f1946f2007-10-03 22:26:02 +00002600/* Write out a hexadecimal representation of the floating point value
2601 to DST, which must be of sufficient size, in the C99 form
2602 [-]0xh.hhhhp[+-]d. Return the number of characters written,
2603 excluding the terminating NUL.
2604
2605 If UPPERCASE, the output is in upper case, otherwise in lower case.
2606
2607 HEXDIGITS digits appear altogether, rounding the value if
2608 necessary. If HEXDIGITS is 0, the minimal precision to display the
2609 number precisely is used instead. If nothing would appear after
2610 the decimal point it is suppressed.
2611
2612 The decimal exponent is always printed and has at least one digit.
2613 Zero values display an exponent of zero. Infinities and NaNs
2614 appear as "infinity" or "nan" respectively.
2615
2616 The above rules are as specified by C99. There is ambiguity about
2617 what the leading hexadecimal digit should be. This implementation
2618 uses whatever is necessary so that the exponent is displayed as
2619 stored. This implies the exponent will fall within the IEEE format
2620 range, and the leading hexadecimal digit will be 0 (for denormals),
2621 1 (normal numbers) or 2 (normal numbers rounded-away-from-zero with
2622 any other digits zero).
2623*/
Tim Shen85de51d2016-10-25 19:55:59 +00002624unsigned int IEEEFloat::convertToHexString(char *dst, unsigned int hexDigits,
2625 bool upperCase,
2626 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002627 char *p;
2628
2629 p = dst;
2630 if (sign)
2631 *dst++ = '-';
2632
2633 switch (category) {
2634 case fcInfinity:
2635 memcpy (dst, upperCase ? infinityU: infinityL, sizeof infinityU - 1);
2636 dst += sizeof infinityL - 1;
2637 break;
2638
2639 case fcNaN:
2640 memcpy (dst, upperCase ? NaNU: NaNL, sizeof NaNU - 1);
2641 dst += sizeof NaNU - 1;
2642 break;
2643
2644 case fcZero:
2645 *dst++ = '0';
2646 *dst++ = upperCase ? 'X': 'x';
2647 *dst++ = '0';
2648 if (hexDigits > 1) {
2649 *dst++ = '.';
2650 memset (dst, '0', hexDigits - 1);
2651 dst += hexDigits - 1;
2652 }
2653 *dst++ = upperCase ? 'P': 'p';
2654 *dst++ = '0';
2655 break;
2656
2657 case fcNormal:
2658 dst = convertNormalToHexString (dst, hexDigits, upperCase, rounding_mode);
2659 break;
2660 }
2661
2662 *dst = 0;
2663
Evan Cheng82b9e962008-05-02 21:15:08 +00002664 return static_cast<unsigned int>(dst - p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002665}
2666
2667/* Does the hard work of outputting the correctly rounded hexadecimal
2668 form of a normal floating point number with the specified number of
2669 hexadecimal digits. If HEXDIGITS is zero the minimum number of
2670 digits necessary to print the value precisely is output. */
Tim Shen85de51d2016-10-25 19:55:59 +00002671char *IEEEFloat::convertNormalToHexString(char *dst, unsigned int hexDigits,
2672 bool upperCase,
2673 roundingMode rounding_mode) const {
Neil Booth8f1946f2007-10-03 22:26:02 +00002674 unsigned int count, valueBits, shift, partsCount, outputDigits;
2675 const char *hexDigitChars;
2676 const integerPart *significand;
2677 char *p;
2678 bool roundUp;
2679
2680 *dst++ = '0';
2681 *dst++ = upperCase ? 'X': 'x';
2682
2683 roundUp = false;
2684 hexDigitChars = upperCase ? hexDigitsUpper: hexDigitsLower;
2685
2686 significand = significandParts();
2687 partsCount = partCount();
2688
2689 /* +3 because the first digit only uses the single integer bit, so
2690 we have 3 virtual zero most-significant-bits. */
2691 valueBits = semantics->precision + 3;
2692 shift = integerPartWidth - valueBits % integerPartWidth;
2693
2694 /* The natural number of digits required ignoring trailing
2695 insignificant zeroes. */
2696 outputDigits = (valueBits - significandLSB () + 3) / 4;
2697
2698 /* hexDigits of zero means use the required number for the
2699 precision. Otherwise, see if we are truncating. If we are,
Neil Booth0ea72a92007-10-06 00:24:48 +00002700 find out if we need to round away from zero. */
Neil Booth8f1946f2007-10-03 22:26:02 +00002701 if (hexDigits) {
2702 if (hexDigits < outputDigits) {
2703 /* We are dropping non-zero bits, so need to check how to round.
2704 "bits" is the number of dropped bits. */
2705 unsigned int bits;
2706 lostFraction fraction;
2707
2708 bits = valueBits - hexDigits * 4;
2709 fraction = lostFractionThroughTruncation (significand, partsCount, bits);
2710 roundUp = roundAwayFromZero(rounding_mode, fraction, bits);
2711 }
2712 outputDigits = hexDigits;
2713 }
2714
2715 /* Write the digits consecutively, and start writing in the location
2716 of the hexadecimal point. We move the most significant digit
2717 left and add the hexadecimal point later. */
2718 p = ++dst;
2719
2720 count = (valueBits + integerPartWidth - 1) / integerPartWidth;
2721
2722 while (outputDigits && count) {
2723 integerPart part;
2724
2725 /* Put the most significant integerPartWidth bits in "part". */
2726 if (--count == partsCount)
2727 part = 0; /* An imaginary higher zero part. */
2728 else
2729 part = significand[count] << shift;
2730
2731 if (count && shift)
2732 part |= significand[count - 1] >> (integerPartWidth - shift);
2733
2734 /* Convert as much of "part" to hexdigits as we can. */
2735 unsigned int curDigits = integerPartWidth / 4;
2736
2737 if (curDigits > outputDigits)
2738 curDigits = outputDigits;
2739 dst += partAsHex (dst, part, curDigits, hexDigitChars);
2740 outputDigits -= curDigits;
2741 }
2742
2743 if (roundUp) {
2744 char *q = dst;
2745
2746 /* Note that hexDigitChars has a trailing '0'. */
2747 do {
2748 q--;
2749 *q = hexDigitChars[hexDigitValue (*q) + 1];
Neil Booth0ea72a92007-10-06 00:24:48 +00002750 } while (*q == '0');
Evan Cheng67c90212009-10-27 21:35:42 +00002751 assert(q >= p);
Neil Booth8f1946f2007-10-03 22:26:02 +00002752 } else {
2753 /* Add trailing zeroes. */
2754 memset (dst, '0', outputDigits);
2755 dst += outputDigits;
2756 }
2757
2758 /* Move the most significant digit to before the point, and if there
2759 is something after the decimal point add it. This must come
2760 after rounding above. */
2761 p[-1] = p[0];
2762 if (dst -1 == p)
2763 dst--;
2764 else
2765 p[0] = '.';
2766
2767 /* Finally output the exponent. */
2768 *dst++ = upperCase ? 'P': 'p';
2769
Neil Booth32897f52007-10-06 07:29:25 +00002770 return writeSignedDecimal (dst, exponent);
Neil Booth8f1946f2007-10-03 22:26:02 +00002771}
2772
Tim Shen85de51d2016-10-25 19:55:59 +00002773hash_code hash_value(const IEEEFloat &Arg) {
Michael Gottesman8136c382013-06-26 23:17:28 +00002774 if (!Arg.isFiniteNonZero())
Chandler Carruth71bd7d12012-03-04 12:02:57 +00002775 return hash_combine((uint8_t)Arg.category,
2776 // NaN has no sign, fix it at zero.
2777 Arg.isNaN() ? (uint8_t)0 : (uint8_t)Arg.sign,
2778 Arg.semantics->precision);
2779
2780 // Normal floats need their exponent and significand hashed.
2781 return hash_combine((uint8_t)Arg.category, (uint8_t)Arg.sign,
2782 Arg.semantics->precision, Arg.exponent,
2783 hash_combine_range(
2784 Arg.significandParts(),
2785 Arg.significandParts() + Arg.partCount()));
Dale Johannesena719a602007-08-24 00:56:33 +00002786}
2787
2788// Conversion from APFloat to/from host float/double. It may eventually be
2789// possible to eliminate these and have everybody deal with APFloats, but that
2790// will take a while. This approach will not easily extend to long double.
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002791// Current implementation requires integerPartWidth==64, which is correct at
2792// the moment but could be made more general.
Dale Johannesena719a602007-08-24 00:56:33 +00002793
Dale Johannesen728687c2007-09-05 20:39:49 +00002794// Denormals have exponent minExponent in APFloat, but minExponent-1 in
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002795// the actual IEEE respresentations. We compensate for that here.
Dale Johannesen728687c2007-09-05 20:39:49 +00002796
Tim Shen85de51d2016-10-25 19:55:59 +00002797APInt IEEEFloat::convertF80LongDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002798 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended);
Evan Cheng67c90212009-10-27 21:35:42 +00002799 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002800
2801 uint64_t myexponent, mysignificand;
2802
Michael Gottesman8136c382013-06-26 23:17:28 +00002803 if (isFiniteNonZero()) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00002804 myexponent = exponent+16383; //bias
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002805 mysignificand = significandParts()[0];
Dale Johannesen245dceb2007-09-11 18:32:33 +00002806 if (myexponent==1 && !(mysignificand & 0x8000000000000000ULL))
2807 myexponent = 0; // denormal
2808 } else if (category==fcZero) {
2809 myexponent = 0;
2810 mysignificand = 0;
2811 } else if (category==fcInfinity) {
2812 myexponent = 0x7fff;
2813 mysignificand = 0x8000000000000000ULL;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002814 } else {
2815 assert(category == fcNaN && "Unknown category");
Dale Johannesen245dceb2007-09-11 18:32:33 +00002816 myexponent = 0x7fff;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00002817 mysignificand = significandParts()[0];
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002818 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00002819
2820 uint64_t words[2];
Dale Johannesen93eefa02009-03-23 21:16:53 +00002821 words[0] = mysignificand;
2822 words[1] = ((uint64_t)(sign & 1) << 15) |
2823 (myexponent & 0x7fffLL);
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002824 return APInt(80, words);
Dale Johannesen245dceb2007-09-11 18:32:33 +00002825}
2826
Tim Shen85de51d2016-10-25 19:55:59 +00002827APInt IEEEFloat::convertPPCDoubleDoubleAPFloatToAPInt() const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00002828 assert(semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy);
Evan Cheng67c90212009-10-27 21:35:42 +00002829 assert(partCount()==2);
Dale Johannesen007aa372007-10-11 18:07:22 +00002830
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002831 uint64_t words[2];
2832 opStatus fs;
2833 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00002834
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002835 // Convert number to double. To avoid spurious underflows, we re-
2836 // normalize against the "double" minExponent first, and only *then*
2837 // truncate the mantissa. The result of that second conversion
2838 // may be inexact, but should never underflow.
Alexey Samsonov2b431d92012-11-30 22:27:54 +00002839 // Declare fltSemantics before APFloat that uses it (and
2840 // saves pointer to it) to ensure correct destruction order.
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002841 fltSemantics extendedSemantics = *semantics;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002842 extendedSemantics.minExponent = semIEEEdouble.minExponent;
Tim Shen85de51d2016-10-25 19:55:59 +00002843 IEEEFloat extended(*this);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002844 fs = extended.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2845 assert(fs == opOK && !losesInfo);
2846 (void)fs;
2847
Tim Shen85de51d2016-10-25 19:55:59 +00002848 IEEEFloat u(extended);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002849 fs = u.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002850 assert(fs == opOK || fs == opInexact);
2851 (void)fs;
2852 words[0] = *u.convertDoubleAPFloatToAPInt().getRawData();
2853
2854 // If conversion was exact or resulted in a special case, we're done;
2855 // just set the second double to zero. Otherwise, re-convert back to
2856 // the extended format and compute the difference. This now should
2857 // convert exactly to double.
Michael Gottesman8136c382013-06-26 23:17:28 +00002858 if (u.isFiniteNonZero() && losesInfo) {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002859 fs = u.convert(extendedSemantics, rmNearestTiesToEven, &losesInfo);
2860 assert(fs == opOK && !losesInfo);
2861 (void)fs;
2862
Tim Shen85de51d2016-10-25 19:55:59 +00002863 IEEEFloat v(extended);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002864 v.subtract(u, rmNearestTiesToEven);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002865 fs = v.convert(semIEEEdouble, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002866 assert(fs == opOK && !losesInfo);
2867 (void)fs;
2868 words[1] = *v.convertDoubleAPFloatToAPInt().getRawData();
Dale Johannesen007aa372007-10-11 18:07:22 +00002869 } else {
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00002870 words[1] = 0;
Dale Johannesen007aa372007-10-11 18:07:22 +00002871 }
2872
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002873 return APInt(128, words);
Dale Johannesen007aa372007-10-11 18:07:22 +00002874}
2875
Tim Shen85de51d2016-10-25 19:55:59 +00002876APInt IEEEFloat::convertQuadrupleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002877 assert(semantics == (const llvm::fltSemantics*)&semIEEEquad);
Evan Cheng67c90212009-10-27 21:35:42 +00002878 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002879
2880 uint64_t myexponent, mysignificand, mysignificand2;
2881
Michael Gottesman8136c382013-06-26 23:17:28 +00002882 if (isFiniteNonZero()) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002883 myexponent = exponent+16383; //bias
2884 mysignificand = significandParts()[0];
2885 mysignificand2 = significandParts()[1];
2886 if (myexponent==1 && !(mysignificand2 & 0x1000000000000LL))
2887 myexponent = 0; // denormal
2888 } else if (category==fcZero) {
2889 myexponent = 0;
2890 mysignificand = mysignificand2 = 0;
2891 } else if (category==fcInfinity) {
2892 myexponent = 0x7fff;
2893 mysignificand = mysignificand2 = 0;
2894 } else {
2895 assert(category == fcNaN && "Unknown category!");
2896 myexponent = 0x7fff;
2897 mysignificand = significandParts()[0];
2898 mysignificand2 = significandParts()[1];
2899 }
2900
2901 uint64_t words[2];
2902 words[0] = mysignificand;
2903 words[1] = ((uint64_t)(sign & 1) << 63) |
2904 ((myexponent & 0x7fff) << 48) |
Anton Korobeynikov876955c2009-08-21 23:09:47 +00002905 (mysignificand2 & 0xffffffffffffLL);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002906
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00002907 return APInt(128, words);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00002908}
2909
Tim Shen85de51d2016-10-25 19:55:59 +00002910APInt IEEEFloat::convertDoubleAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002911 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble);
Evan Cheng67c90212009-10-27 21:35:42 +00002912 assert(partCount()==1);
Dale Johannesena719a602007-08-24 00:56:33 +00002913
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002914 uint64_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002915
Michael Gottesman8136c382013-06-26 23:17:28 +00002916 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002917 myexponent = exponent+1023; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00002918 mysignificand = *significandParts();
2919 if (myexponent==1 && !(mysignificand & 0x10000000000000LL))
2920 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002921 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002922 myexponent = 0;
2923 mysignificand = 0;
2924 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002925 myexponent = 0x7ff;
2926 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002927 } else {
2928 assert(category == fcNaN && "Unknown category!");
Dale Johannesena719a602007-08-24 00:56:33 +00002929 myexponent = 0x7ff;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002930 mysignificand = *significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002931 }
Dale Johannesena719a602007-08-24 00:56:33 +00002932
Evan Cheng82b9e962008-05-02 21:15:08 +00002933 return APInt(64, ((((uint64_t)(sign & 1) << 63) |
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002934 ((myexponent & 0x7ff) << 52) |
2935 (mysignificand & 0xfffffffffffffLL))));
Dale Johannesena719a602007-08-24 00:56:33 +00002936}
2937
Tim Shen85de51d2016-10-25 19:55:59 +00002938APInt IEEEFloat::convertFloatAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002939 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle);
Evan Cheng67c90212009-10-27 21:35:42 +00002940 assert(partCount()==1);
Neil Booth9acbf5a2007-09-26 21:33:42 +00002941
Dale Johannesen3cf889f2007-08-31 04:03:46 +00002942 uint32_t myexponent, mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00002943
Michael Gottesman8136c382013-06-26 23:17:28 +00002944 if (isFiniteNonZero()) {
Dale Johannesena719a602007-08-24 00:56:33 +00002945 myexponent = exponent+127; //bias
Evan Cheng82b9e962008-05-02 21:15:08 +00002946 mysignificand = (uint32_t)*significandParts();
Dale Johannesen06a10df2007-11-17 01:02:27 +00002947 if (myexponent == 1 && !(mysignificand & 0x800000))
Dale Johannesen728687c2007-09-05 20:39:49 +00002948 myexponent = 0; // denormal
Dale Johannesena719a602007-08-24 00:56:33 +00002949 } else if (category==fcZero) {
Dale Johannesena719a602007-08-24 00:56:33 +00002950 myexponent = 0;
2951 mysignificand = 0;
2952 } else if (category==fcInfinity) {
Dale Johannesena719a602007-08-24 00:56:33 +00002953 myexponent = 0xff;
2954 mysignificand = 0;
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002955 } else {
2956 assert(category == fcNaN && "Unknown category!");
Dale Johannesen728687c2007-09-05 20:39:49 +00002957 myexponent = 0xff;
Evan Cheng82b9e962008-05-02 21:15:08 +00002958 mysignificand = (uint32_t)*significandParts();
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002959 }
Dale Johannesena719a602007-08-24 00:56:33 +00002960
Chris Lattner2a9bcb92007-10-06 06:13:42 +00002961 return APInt(32, (((sign&1) << 31) | ((myexponent&0xff) << 23) |
2962 (mysignificand & 0x7fffff)));
Dale Johannesena719a602007-08-24 00:56:33 +00002963}
2964
Tim Shen85de51d2016-10-25 19:55:59 +00002965APInt IEEEFloat::convertHalfAPFloatToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002966 assert(semantics == (const llvm::fltSemantics*)&semIEEEhalf);
Evan Cheng67c90212009-10-27 21:35:42 +00002967 assert(partCount()==1);
Chris Lattner4794b2b2009-10-16 02:13:51 +00002968
2969 uint32_t myexponent, mysignificand;
2970
Michael Gottesman8136c382013-06-26 23:17:28 +00002971 if (isFiniteNonZero()) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00002972 myexponent = exponent+15; //bias
2973 mysignificand = (uint32_t)*significandParts();
2974 if (myexponent == 1 && !(mysignificand & 0x400))
2975 myexponent = 0; // denormal
2976 } else if (category==fcZero) {
2977 myexponent = 0;
2978 mysignificand = 0;
2979 } else if (category==fcInfinity) {
Dale Johannesen0d670b52009-10-23 04:02:51 +00002980 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002981 mysignificand = 0;
2982 } else {
2983 assert(category == fcNaN && "Unknown category!");
Dale Johannesen0d670b52009-10-23 04:02:51 +00002984 myexponent = 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00002985 mysignificand = (uint32_t)*significandParts();
2986 }
2987
2988 return APInt(16, (((sign&1) << 15) | ((myexponent&0x1f) << 10) |
2989 (mysignificand & 0x3ff)));
2990}
2991
Dale Johannesen007aa372007-10-11 18:07:22 +00002992// This function creates an APInt that is just a bit map of the floating
2993// point constant as it would appear in memory. It is not a conversion,
2994// and treating the result as a normal integer is unlikely to be useful.
2995
Tim Shen85de51d2016-10-25 19:55:59 +00002996APInt IEEEFloat::bitcastToAPInt() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002997 if (semantics == (const llvm::fltSemantics*)&semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00002998 return convertHalfAPFloatToAPInt();
2999
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003000 if (semantics == (const llvm::fltSemantics*)&semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003001 return convertFloatAPFloatToAPInt();
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003002
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003003 if (semantics == (const llvm::fltSemantics*)&semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003004 return convertDoubleAPFloatToAPInt();
Neil Booth9acbf5a2007-09-26 21:33:42 +00003005
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003006 if (semantics == (const llvm::fltSemantics*)&semIEEEquad)
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003007 return convertQuadrupleAPFloatToAPInt();
3008
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003009 if (semantics == (const llvm::fltSemantics *)&semPPCDoubleDoubleLegacy)
Dale Johannesen007aa372007-10-11 18:07:22 +00003010 return convertPPCDoubleDoubleAPFloatToAPInt();
3011
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003012 assert(semantics == (const llvm::fltSemantics*)&semX87DoubleExtended &&
Chris Lattner2a9bcb92007-10-06 06:13:42 +00003013 "unknown format!");
3014 return convertF80LongDoubleAPFloatToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003015}
3016
Tim Shen85de51d2016-10-25 19:55:59 +00003017float IEEEFloat::convertToFloat() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003018 assert(semantics == (const llvm::fltSemantics*)&semIEEEsingle &&
Chris Lattner688f9912009-09-24 21:44:20 +00003019 "Float semantics are not IEEEsingle");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003020 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003021 return api.bitsToFloat();
3022}
3023
Tim Shen85de51d2016-10-25 19:55:59 +00003024double IEEEFloat::convertToDouble() const {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003025 assert(semantics == (const llvm::fltSemantics*)&semIEEEdouble &&
Chris Lattner688f9912009-09-24 21:44:20 +00003026 "Float semantics are not IEEEdouble");
Dale Johannesen54306fe2008-10-09 18:53:47 +00003027 APInt api = bitcastToAPInt();
Dale Johannesen245dceb2007-09-11 18:32:33 +00003028 return api.bitsToDouble();
3029}
3030
Dale Johannesenfff29952008-10-06 18:22:29 +00003031/// Integer bit is explicit in this format. Intel hardware (387 and later)
3032/// does not support these bit patterns:
3033/// exponent = all 1's, integer bit 0, significand 0 ("pseudoinfinity")
3034/// exponent = all 1's, integer bit 0, significand nonzero ("pseudoNaN")
Dale Johannesenfff29952008-10-06 18:22:29 +00003035/// exponent!=0 nor all 1's, integer bit 0 ("unnormal")
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003036/// exponent = 0, integer bit 1 ("pseudodenormal")
3037/// At the moment, the first three are treated as NaNs, the last one as Normal.
Tim Shen85de51d2016-10-25 19:55:59 +00003038void IEEEFloat::initFromF80LongDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003039 assert(api.getBitWidth()==80);
3040 uint64_t i1 = api.getRawData()[0];
3041 uint64_t i2 = api.getRawData()[1];
Dale Johannesen93eefa02009-03-23 21:16:53 +00003042 uint64_t myexponent = (i2 & 0x7fff);
3043 uint64_t mysignificand = i1;
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003044 uint8_t myintegerbit = mysignificand >> 63;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003045
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003046 initialize(&semX87DoubleExtended);
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003047 assert(partCount()==2);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003048
Dale Johannesen93eefa02009-03-23 21:16:53 +00003049 sign = static_cast<unsigned int>(i2>>15);
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003050 if (myexponent == 0 && mysignificand == 0) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003051 // exponent, significand meaningless
3052 category = fcZero;
3053 } else if (myexponent==0x7fff && mysignificand==0x8000000000000000ULL) {
3054 // exponent, significand meaningless
3055 category = fcInfinity;
Pavel Labathb1bcafd2018-05-09 15:13:45 +00003056 } else if ((myexponent == 0x7fff && mysignificand != 0x8000000000000000ULL) ||
3057 (myexponent != 0x7fff && myexponent != 0 && myintegerbit == 0)) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003058 // exponent meaningless
3059 category = fcNaN;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003060 significandParts()[0] = mysignificand;
3061 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003062 } else {
3063 category = fcNormal;
3064 exponent = myexponent - 16383;
Dale Johannesen146a0ea2007-09-20 23:47:58 +00003065 significandParts()[0] = mysignificand;
3066 significandParts()[1] = 0;
Dale Johannesen245dceb2007-09-11 18:32:33 +00003067 if (myexponent==0) // denormal
3068 exponent = -16382;
Neil Booth9acbf5a2007-09-26 21:33:42 +00003069 }
Dale Johannesen245dceb2007-09-11 18:32:33 +00003070}
3071
Tim Shen85de51d2016-10-25 19:55:59 +00003072void IEEEFloat::initFromPPCDoubleDoubleAPInt(const APInt &api) {
Dale Johannesen007aa372007-10-11 18:07:22 +00003073 assert(api.getBitWidth()==128);
3074 uint64_t i1 = api.getRawData()[0];
3075 uint64_t i2 = api.getRawData()[1];
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003076 opStatus fs;
3077 bool losesInfo;
Dale Johannesen007aa372007-10-11 18:07:22 +00003078
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003079 // Get the first double and convert to our format.
3080 initFromDoubleAPInt(APInt(64, i1));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003081 fs = convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003082 assert(fs == opOK && !losesInfo);
3083 (void)fs;
Dale Johannesen007aa372007-10-11 18:07:22 +00003084
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003085 // Unless we have a special case, add in second double.
Michael Gottesman8136c382013-06-26 23:17:28 +00003086 if (isFiniteNonZero()) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003087 IEEEFloat v(semIEEEdouble, APInt(64, i2));
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003088 fs = v.convert(semPPCDoubleDoubleLegacy, rmNearestTiesToEven, &losesInfo);
Ulrich Weigandd9f7e252012-10-29 18:09:01 +00003089 assert(fs == opOK && !losesInfo);
3090 (void)fs;
3091
3092 add(v, rmNearestTiesToEven);
Dale Johannesen007aa372007-10-11 18:07:22 +00003093 }
3094}
3095
Tim Shen85de51d2016-10-25 19:55:59 +00003096void IEEEFloat::initFromQuadrupleAPInt(const APInt &api) {
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003097 assert(api.getBitWidth()==128);
3098 uint64_t i1 = api.getRawData()[0];
3099 uint64_t i2 = api.getRawData()[1];
3100 uint64_t myexponent = (i2 >> 48) & 0x7fff;
3101 uint64_t mysignificand = i1;
3102 uint64_t mysignificand2 = i2 & 0xffffffffffffLL;
3103
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003104 initialize(&semIEEEquad);
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003105 assert(partCount()==2);
Anton Korobeynikov13e8c7e2009-08-21 22:10:30 +00003106
3107 sign = static_cast<unsigned int>(i2>>63);
3108 if (myexponent==0 &&
3109 (mysignificand==0 && mysignificand2==0)) {
3110 // exponent, significand meaningless
3111 category = fcZero;
3112 } else if (myexponent==0x7fff &&
3113 (mysignificand==0 && mysignificand2==0)) {
3114 // exponent, significand meaningless
3115 category = fcInfinity;
3116 } else if (myexponent==0x7fff &&
3117 (mysignificand!=0 || mysignificand2 !=0)) {
3118 // exponent meaningless
3119 category = fcNaN;
3120 significandParts()[0] = mysignificand;
3121 significandParts()[1] = mysignificand2;
3122 } else {
3123 category = fcNormal;
3124 exponent = myexponent - 16383;
3125 significandParts()[0] = mysignificand;
3126 significandParts()[1] = mysignificand2;
3127 if (myexponent==0) // denormal
3128 exponent = -16382;
3129 else
3130 significandParts()[1] |= 0x1000000000000LL; // integer bit
3131 }
3132}
3133
Tim Shen85de51d2016-10-25 19:55:59 +00003134void IEEEFloat::initFromDoubleAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003135 assert(api.getBitWidth()==64);
3136 uint64_t i = *api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003137 uint64_t myexponent = (i >> 52) & 0x7ff;
3138 uint64_t mysignificand = i & 0xfffffffffffffLL;
3139
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003140 initialize(&semIEEEdouble);
Dale Johannesena719a602007-08-24 00:56:33 +00003141 assert(partCount()==1);
3142
Evan Cheng82b9e962008-05-02 21:15:08 +00003143 sign = static_cast<unsigned int>(i>>63);
Dale Johannesena719a602007-08-24 00:56:33 +00003144 if (myexponent==0 && mysignificand==0) {
3145 // exponent, significand meaningless
3146 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003147 } else if (myexponent==0x7ff && mysignificand==0) {
3148 // exponent, significand meaningless
3149 category = fcInfinity;
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003150 } else if (myexponent==0x7ff && mysignificand!=0) {
3151 // exponent meaningless
3152 category = fcNaN;
3153 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003154 } else {
Dale Johannesena719a602007-08-24 00:56:33 +00003155 category = fcNormal;
3156 exponent = myexponent - 1023;
Dale Johannesen728687c2007-09-05 20:39:49 +00003157 *significandParts() = mysignificand;
3158 if (myexponent==0) // denormal
3159 exponent = -1022;
3160 else
3161 *significandParts() |= 0x10000000000000LL; // integer bit
Neil Booth9acbf5a2007-09-26 21:33:42 +00003162 }
Dale Johannesena719a602007-08-24 00:56:33 +00003163}
3164
Tim Shen85de51d2016-10-25 19:55:59 +00003165void IEEEFloat::initFromFloatAPInt(const APInt &api) {
Dale Johannesen245dceb2007-09-11 18:32:33 +00003166 assert(api.getBitWidth()==32);
3167 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen918c33c2007-08-24 05:08:11 +00003168 uint32_t myexponent = (i >> 23) & 0xff;
3169 uint32_t mysignificand = i & 0x7fffff;
3170
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003171 initialize(&semIEEEsingle);
Dale Johannesena719a602007-08-24 00:56:33 +00003172 assert(partCount()==1);
3173
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003174 sign = i >> 31;
Dale Johannesena719a602007-08-24 00:56:33 +00003175 if (myexponent==0 && mysignificand==0) {
3176 // exponent, significand meaningless
3177 category = fcZero;
Dale Johannesena719a602007-08-24 00:56:33 +00003178 } else if (myexponent==0xff && mysignificand==0) {
3179 // exponent, significand meaningless
3180 category = fcInfinity;
Dale Johannesen4f55d9f2007-09-25 17:25:00 +00003181 } else if (myexponent==0xff && mysignificand!=0) {
Dale Johannesena719a602007-08-24 00:56:33 +00003182 // sign, exponent, significand meaningless
Dale Johannesen3cf889f2007-08-31 04:03:46 +00003183 category = fcNaN;
3184 *significandParts() = mysignificand;
Dale Johannesena719a602007-08-24 00:56:33 +00003185 } else {
3186 category = fcNormal;
Dale Johannesena719a602007-08-24 00:56:33 +00003187 exponent = myexponent - 127; //bias
Dale Johannesen728687c2007-09-05 20:39:49 +00003188 *significandParts() = mysignificand;
3189 if (myexponent==0) // denormal
3190 exponent = -126;
3191 else
3192 *significandParts() |= 0x800000; // integer bit
Dale Johannesena719a602007-08-24 00:56:33 +00003193 }
3194}
Dale Johannesen245dceb2007-09-11 18:32:33 +00003195
Tim Shen85de51d2016-10-25 19:55:59 +00003196void IEEEFloat::initFromHalfAPInt(const APInt &api) {
Chris Lattner4794b2b2009-10-16 02:13:51 +00003197 assert(api.getBitWidth()==16);
3198 uint32_t i = (uint32_t)*api.getRawData();
Dale Johannesen0d670b52009-10-23 04:02:51 +00003199 uint32_t myexponent = (i >> 10) & 0x1f;
Chris Lattner4794b2b2009-10-16 02:13:51 +00003200 uint32_t mysignificand = i & 0x3ff;
3201
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003202 initialize(&semIEEEhalf);
Chris Lattner4794b2b2009-10-16 02:13:51 +00003203 assert(partCount()==1);
3204
3205 sign = i >> 15;
3206 if (myexponent==0 && mysignificand==0) {
3207 // exponent, significand meaningless
3208 category = fcZero;
3209 } else if (myexponent==0x1f && mysignificand==0) {
3210 // exponent, significand meaningless
3211 category = fcInfinity;
3212 } else if (myexponent==0x1f && mysignificand!=0) {
3213 // sign, exponent, significand meaningless
3214 category = fcNaN;
3215 *significandParts() = mysignificand;
3216 } else {
3217 category = fcNormal;
3218 exponent = myexponent - 15; //bias
3219 *significandParts() = mysignificand;
3220 if (myexponent==0) // denormal
3221 exponent = -14;
3222 else
3223 *significandParts() |= 0x400; // integer bit
3224 }
3225}
3226
Dale Johannesen245dceb2007-09-11 18:32:33 +00003227/// Treat api as containing the bits of a floating point number. Currently
Dale Johannesen007aa372007-10-11 18:07:22 +00003228/// we infer the floating point type from the size of the APInt. The
3229/// isIEEE argument distinguishes between PPC128 and IEEE128 (not meaningful
3230/// when the size is anything else).
Tim Shen85de51d2016-10-25 19:55:59 +00003231void IEEEFloat::initFromAPInt(const fltSemantics *Sem, const APInt &api) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003232 if (Sem == &semIEEEhalf)
Chris Lattner4794b2b2009-10-16 02:13:51 +00003233 return initFromHalfAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003234 if (Sem == &semIEEEsingle)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003235 return initFromFloatAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003236 if (Sem == &semIEEEdouble)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003237 return initFromDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003238 if (Sem == &semX87DoubleExtended)
Dale Johannesen245dceb2007-09-11 18:32:33 +00003239 return initFromF80LongDoubleAPInt(api);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003240 if (Sem == &semIEEEquad)
Tim Northover29178a32013-01-22 09:46:31 +00003241 return initFromQuadrupleAPInt(api);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003242 if (Sem == &semPPCDoubleDoubleLegacy)
Tim Northover29178a32013-01-22 09:46:31 +00003243 return initFromPPCDoubleDoubleAPInt(api);
3244
Craig Topper2617dcc2014-04-15 06:32:26 +00003245 llvm_unreachable(nullptr);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003246}
3247
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003248/// Make this number the largest magnitude normal number in the given
3249/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003250void IEEEFloat::makeLargest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003251 // We want (in interchange format):
3252 // sign = {Negative}
3253 // exponent = 1..10
3254 // significand = 1..1
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003255 category = fcNormal;
3256 sign = Negative;
3257 exponent = semantics->maxExponent;
John McCall29b5c282009-12-24 08:56:26 +00003258
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003259 // Use memset to set all but the highest integerPart to all ones.
3260 integerPart *significand = significandParts();
3261 unsigned PartCount = partCount();
3262 memset(significand, 0xFF, sizeof(integerPart)*(PartCount - 1));
John McCall29b5c282009-12-24 08:56:26 +00003263
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003264 // Set the high integerPart especially setting all unused top bits for
3265 // internal consistency.
3266 const unsigned NumUnusedHighBits =
3267 PartCount*integerPartWidth - semantics->precision;
Alexey Samsonovba1ecbc2014-09-06 00:41:19 +00003268 significand[PartCount - 1] = (NumUnusedHighBits < integerPartWidth)
3269 ? (~integerPart(0) >> NumUnusedHighBits)
3270 : 0;
John McCall29b5c282009-12-24 08:56:26 +00003271}
3272
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003273/// Make this number the smallest magnitude denormal number in the given
3274/// semantics.
Tim Shen85de51d2016-10-25 19:55:59 +00003275void IEEEFloat::makeSmallest(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003276 // We want (in interchange format):
3277 // sign = {Negative}
3278 // exponent = 0..0
3279 // significand = 0..01
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003280 category = fcNormal;
3281 sign = Negative;
3282 exponent = semantics->minExponent;
3283 APInt::tcSet(significandParts(), 1, partCount());
3284}
John McCall29b5c282009-12-24 08:56:26 +00003285
Tim Shen139a58f2016-10-27 22:52:40 +00003286void IEEEFloat::makeSmallestNormalized(bool Negative) {
John McCall29b5c282009-12-24 08:56:26 +00003287 // We want (in interchange format):
3288 // sign = {Negative}
3289 // exponent = 0..0
3290 // significand = 10..0
3291
Tim Shen139a58f2016-10-27 22:52:40 +00003292 category = fcNormal;
3293 zeroSignificand();
3294 sign = Negative;
3295 exponent = semantics->minExponent;
3296 significandParts()[partCountForBits(semantics->precision) - 1] |=
3297 (((integerPart)1) << ((semantics->precision - 1) % integerPartWidth));
John McCall29b5c282009-12-24 08:56:26 +00003298}
3299
Tim Shen85de51d2016-10-25 19:55:59 +00003300IEEEFloat::IEEEFloat(const fltSemantics &Sem, const APInt &API) {
Tim Northover29178a32013-01-22 09:46:31 +00003301 initFromAPInt(&Sem, API);
Dale Johannesen245dceb2007-09-11 18:32:33 +00003302}
3303
Tim Shen85de51d2016-10-25 19:55:59 +00003304IEEEFloat::IEEEFloat(float f) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003305 initFromAPInt(&semIEEEsingle, APInt::floatToBits(f));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003306}
3307
Tim Shen85de51d2016-10-25 19:55:59 +00003308IEEEFloat::IEEEFloat(double d) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003309 initFromAPInt(&semIEEEdouble, APInt::doubleToBits(d));
Dale Johannesen245dceb2007-09-11 18:32:33 +00003310}
John McCall29b5c282009-12-24 08:56:26 +00003311
3312namespace {
David Blaikie70fdf722012-07-25 18:04:24 +00003313 void append(SmallVectorImpl<char> &Buffer, StringRef Str) {
3314 Buffer.append(Str.begin(), Str.end());
John McCall29b5c282009-12-24 08:56:26 +00003315 }
3316
John McCalle6212ace2009-12-24 12:16:56 +00003317 /// Removes data from the given significand until it is no more
3318 /// precise than is required for the desired precision.
3319 void AdjustToPrecision(APInt &significand,
3320 int &exp, unsigned FormatPrecision) {
3321 unsigned bits = significand.getActiveBits();
3322
3323 // 196/59 is a very slight overestimate of lg_2(10).
3324 unsigned bitsRequired = (FormatPrecision * 196 + 58) / 59;
3325
3326 if (bits <= bitsRequired) return;
3327
3328 unsigned tensRemovable = (bits - bitsRequired) * 59 / 196;
3329 if (!tensRemovable) return;
3330
3331 exp += tensRemovable;
3332
3333 APInt divisor(significand.getBitWidth(), 1);
3334 APInt powten(significand.getBitWidth(), 10);
3335 while (true) {
3336 if (tensRemovable & 1)
3337 divisor *= powten;
3338 tensRemovable >>= 1;
3339 if (!tensRemovable) break;
3340 powten *= powten;
3341 }
3342
3343 significand = significand.udiv(divisor);
3344
Hao Liube99cc32013-03-20 01:46:36 +00003345 // Truncate the significand down to its active bit count.
3346 significand = significand.trunc(significand.getActiveBits());
John McCalle6212ace2009-12-24 12:16:56 +00003347 }
3348
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003349
John McCall29b5c282009-12-24 08:56:26 +00003350 void AdjustToPrecision(SmallVectorImpl<char> &buffer,
3351 int &exp, unsigned FormatPrecision) {
3352 unsigned N = buffer.size();
3353 if (N <= FormatPrecision) return;
3354
3355 // The most significant figures are the last ones in the buffer.
3356 unsigned FirstSignificant = N - FormatPrecision;
3357
3358 // Round.
3359 // FIXME: this probably shouldn't use 'round half up'.
3360
3361 // Rounding down is just a truncation, except we also want to drop
3362 // trailing zeros from the new result.
3363 if (buffer[FirstSignificant - 1] < '5') {
NAKAMURA Takumi5adeb932012-02-19 03:18:29 +00003364 while (FirstSignificant < N && buffer[FirstSignificant] == '0')
John McCall29b5c282009-12-24 08:56:26 +00003365 FirstSignificant++;
3366
3367 exp += FirstSignificant;
3368 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3369 return;
3370 }
3371
3372 // Rounding up requires a decimal add-with-carry. If we continue
3373 // the carry, the newly-introduced zeros will just be truncated.
3374 for (unsigned I = FirstSignificant; I != N; ++I) {
3375 if (buffer[I] == '9') {
3376 FirstSignificant++;
3377 } else {
3378 buffer[I]++;
3379 break;
3380 }
3381 }
3382
3383 // If we carried through, we have exactly one digit of precision.
3384 if (FirstSignificant == N) {
3385 exp += FirstSignificant;
3386 buffer.clear();
3387 buffer.push_back('1');
3388 return;
3389 }
3390
3391 exp += FirstSignificant;
3392 buffer.erase(&buffer[0], &buffer[FirstSignificant]);
3393 }
Duncan P. N. Exon Smith91d3cfe2016-04-05 20:45:04 +00003394}
John McCall29b5c282009-12-24 08:56:26 +00003395
Tim Shen85de51d2016-10-25 19:55:59 +00003396void IEEEFloat::toString(SmallVectorImpl<char> &Str, unsigned FormatPrecision,
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003397 unsigned FormatMaxPadding, bool TruncateZero) const {
John McCall29b5c282009-12-24 08:56:26 +00003398 switch (category) {
3399 case fcInfinity:
3400 if (isNegative())
3401 return append(Str, "-Inf");
3402 else
3403 return append(Str, "+Inf");
3404
3405 case fcNaN: return append(Str, "NaN");
3406
3407 case fcZero:
3408 if (isNegative())
3409 Str.push_back('-');
3410
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003411 if (!FormatMaxPadding) {
3412 if (TruncateZero)
3413 append(Str, "0.0E+0");
3414 else {
3415 append(Str, "0.0");
3416 if (FormatPrecision > 1)
3417 Str.append(FormatPrecision - 1, '0');
3418 append(Str, "e+00");
3419 }
3420 } else
John McCall29b5c282009-12-24 08:56:26 +00003421 Str.push_back('0');
3422 return;
3423
3424 case fcNormal:
3425 break;
3426 }
3427
3428 if (isNegative())
3429 Str.push_back('-');
3430
3431 // Decompose the number into an APInt and an exponent.
3432 int exp = exponent - ((int) semantics->precision - 1);
3433 APInt significand(semantics->precision,
Jeffrey Yasskin7a162882011-07-18 21:45:40 +00003434 makeArrayRef(significandParts(),
3435 partCountForBits(semantics->precision)));
John McCall29b5c282009-12-24 08:56:26 +00003436
John McCalldd5044a2009-12-24 23:18:09 +00003437 // Set FormatPrecision if zero. We want to do this before we
3438 // truncate trailing zeros, as those are part of the precision.
3439 if (!FormatPrecision) {
Eli Friedmane72f1322013-08-29 23:44:34 +00003440 // We use enough digits so the number can be round-tripped back to an
3441 // APFloat. The formula comes from "How to Print Floating-Point Numbers
3442 // Accurately" by Steele and White.
3443 // FIXME: Using a formula based purely on the precision is conservative;
3444 // we can print fewer digits depending on the actual value being printed.
John McCalldd5044a2009-12-24 23:18:09 +00003445
Eli Friedmane72f1322013-08-29 23:44:34 +00003446 // FormatPrecision = 2 + floor(significandBits / lg_2(10))
3447 FormatPrecision = 2 + semantics->precision * 59 / 196;
John McCalldd5044a2009-12-24 23:18:09 +00003448 }
3449
John McCall29b5c282009-12-24 08:56:26 +00003450 // Ignore trailing binary zeros.
3451 int trailingZeros = significand.countTrailingZeros();
3452 exp += trailingZeros;
Craig Topperfc947bc2017-04-18 17:14:21 +00003453 significand.lshrInPlace(trailingZeros);
John McCall29b5c282009-12-24 08:56:26 +00003454
3455 // Change the exponent from 2^e to 10^e.
3456 if (exp == 0) {
3457 // Nothing to do.
3458 } else if (exp > 0) {
3459 // Just shift left.
Jay Foad583abbc2010-12-07 08:25:19 +00003460 significand = significand.zext(semantics->precision + exp);
John McCall29b5c282009-12-24 08:56:26 +00003461 significand <<= exp;
3462 exp = 0;
3463 } else { /* exp < 0 */
3464 int texp = -exp;
3465
3466 // We transform this using the identity:
3467 // (N)(2^-e) == (N)(5^e)(10^-e)
3468 // This means we have to multiply N (the significand) by 5^e.
3469 // To avoid overflow, we have to operate on numbers large
3470 // enough to store N * 5^e:
3471 // log2(N * 5^e) == log2(N) + e * log2(5)
John McCalldd5044a2009-12-24 23:18:09 +00003472 // <= semantics->precision + e * 137 / 59
3473 // (log_2(5) ~ 2.321928 < 2.322034 ~ 137/59)
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003474
Eli Friedman19546412011-10-07 23:40:49 +00003475 unsigned precision = semantics->precision + (137 * texp + 136) / 59;
John McCall29b5c282009-12-24 08:56:26 +00003476
3477 // Multiply significand by 5^e.
3478 // N * 5^0101 == N * 5^(1*1) * 5^(0*2) * 5^(1*4) * 5^(0*8)
Jay Foad583abbc2010-12-07 08:25:19 +00003479 significand = significand.zext(precision);
John McCall29b5c282009-12-24 08:56:26 +00003480 APInt five_to_the_i(precision, 5);
3481 while (true) {
3482 if (texp & 1) significand *= five_to_the_i;
Dan Gohmanb452d4e2010-03-24 19:38:02 +00003483
John McCall29b5c282009-12-24 08:56:26 +00003484 texp >>= 1;
3485 if (!texp) break;
3486 five_to_the_i *= five_to_the_i;
3487 }
3488 }
3489
John McCalle6212ace2009-12-24 12:16:56 +00003490 AdjustToPrecision(significand, exp, FormatPrecision);
3491
Dmitri Gribenko226fea52013-01-13 16:01:15 +00003492 SmallVector<char, 256> buffer;
John McCall29b5c282009-12-24 08:56:26 +00003493
3494 // Fill the buffer.
3495 unsigned precision = significand.getBitWidth();
3496 APInt ten(precision, 10);
3497 APInt digit(precision, 0);
3498
3499 bool inTrail = true;
3500 while (significand != 0) {
3501 // digit <- significand % 10
3502 // significand <- significand / 10
3503 APInt::udivrem(significand, ten, significand, digit);
3504
3505 unsigned d = digit.getZExtValue();
3506
3507 // Drop trailing zeros.
3508 if (inTrail && !d) exp++;
3509 else {
3510 buffer.push_back((char) ('0' + d));
3511 inTrail = false;
3512 }
3513 }
3514
3515 assert(!buffer.empty() && "no characters in buffer!");
3516
3517 // Drop down to FormatPrecision.
3518 // TODO: don't do more precise calculations above than are required.
3519 AdjustToPrecision(buffer, exp, FormatPrecision);
3520
3521 unsigned NDigits = buffer.size();
3522
John McCalldd5044a2009-12-24 23:18:09 +00003523 // Check whether we should use scientific notation.
John McCall29b5c282009-12-24 08:56:26 +00003524 bool FormatScientific;
3525 if (!FormatMaxPadding)
3526 FormatScientific = true;
3527 else {
John McCall29b5c282009-12-24 08:56:26 +00003528 if (exp >= 0) {
John McCalldd5044a2009-12-24 23:18:09 +00003529 // 765e3 --> 765000
3530 // ^^^
3531 // But we shouldn't make the number look more precise than it is.
3532 FormatScientific = ((unsigned) exp > FormatMaxPadding ||
3533 NDigits + (unsigned) exp > FormatPrecision);
John McCall29b5c282009-12-24 08:56:26 +00003534 } else {
John McCalldd5044a2009-12-24 23:18:09 +00003535 // Power of the most significant digit.
3536 int MSD = exp + (int) (NDigits - 1);
3537 if (MSD >= 0) {
John McCall29b5c282009-12-24 08:56:26 +00003538 // 765e-2 == 7.65
John McCalldd5044a2009-12-24 23:18:09 +00003539 FormatScientific = false;
John McCall29b5c282009-12-24 08:56:26 +00003540 } else {
3541 // 765e-5 == 0.00765
3542 // ^ ^^
John McCalldd5044a2009-12-24 23:18:09 +00003543 FormatScientific = ((unsigned) -MSD) > FormatMaxPadding;
John McCall29b5c282009-12-24 08:56:26 +00003544 }
3545 }
John McCall29b5c282009-12-24 08:56:26 +00003546 }
3547
3548 // Scientific formatting is pretty straightforward.
3549 if (FormatScientific) {
3550 exp += (NDigits - 1);
3551
3552 Str.push_back(buffer[NDigits-1]);
3553 Str.push_back('.');
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003554 if (NDigits == 1 && TruncateZero)
John McCall29b5c282009-12-24 08:56:26 +00003555 Str.push_back('0');
3556 else
3557 for (unsigned I = 1; I != NDigits; ++I)
3558 Str.push_back(buffer[NDigits-1-I]);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003559 // Fill with zeros up to FormatPrecision.
3560 if (!TruncateZero && FormatPrecision > NDigits - 1)
3561 Str.append(FormatPrecision - NDigits + 1, '0');
3562 // For !TruncateZero we use lower 'e'.
3563 Str.push_back(TruncateZero ? 'E' : 'e');
John McCall29b5c282009-12-24 08:56:26 +00003564
3565 Str.push_back(exp >= 0 ? '+' : '-');
3566 if (exp < 0) exp = -exp;
3567 SmallVector<char, 6> expbuf;
3568 do {
3569 expbuf.push_back((char) ('0' + (exp % 10)));
3570 exp /= 10;
3571 } while (exp);
Serguei Katkov3a46eb42017-04-21 02:52:17 +00003572 // Exponent always at least two digits if we do not truncate zeros.
3573 if (!TruncateZero && expbuf.size() < 2)
3574 expbuf.push_back('0');
John McCall29b5c282009-12-24 08:56:26 +00003575 for (unsigned I = 0, E = expbuf.size(); I != E; ++I)
3576 Str.push_back(expbuf[E-1-I]);
3577 return;
3578 }
3579
3580 // Non-scientific, positive exponents.
3581 if (exp >= 0) {
3582 for (unsigned I = 0; I != NDigits; ++I)
3583 Str.push_back(buffer[NDigits-1-I]);
3584 for (unsigned I = 0; I != (unsigned) exp; ++I)
3585 Str.push_back('0');
3586 return;
3587 }
3588
3589 // Non-scientific, negative exponents.
3590
3591 // The number of digits to the left of the decimal point.
3592 int NWholeDigits = exp + (int) NDigits;
3593
3594 unsigned I = 0;
3595 if (NWholeDigits > 0) {
3596 for (; I != (unsigned) NWholeDigits; ++I)
3597 Str.push_back(buffer[NDigits-I-1]);
3598 Str.push_back('.');
3599 } else {
3600 unsigned NZeros = 1 + (unsigned) -NWholeDigits;
3601
3602 Str.push_back('0');
3603 Str.push_back('.');
3604 for (unsigned Z = 1; Z != NZeros; ++Z)
3605 Str.push_back('0');
3606 }
3607
3608 for (; I != NDigits; ++I)
3609 Str.push_back(buffer[NDigits-I-1]);
3610}
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003611
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003612bool IEEEFloat::getExactInverse(APFloat *inv) const {
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003613 // Special floats and denormals have no exact inverse.
Michael Gottesman8136c382013-06-26 23:17:28 +00003614 if (!isFiniteNonZero())
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003615 return false;
3616
3617 // Check that the number is a power of two by making sure that only the
3618 // integer bit is set in the significand.
3619 if (significandLSB() != semantics->precision - 1)
3620 return false;
3621
3622 // Get the inverse.
Tim Shen85de51d2016-10-25 19:55:59 +00003623 IEEEFloat reciprocal(*semantics, 1ULL);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003624 if (reciprocal.divide(*this, rmNearestTiesToEven) != opOK)
3625 return false;
3626
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003627 // Avoid multiplication with a denormal, it is not safe on all platforms and
3628 // may be slower than a normal division.
Benjamin Kramer6bef24f2013-06-01 11:26:33 +00003629 if (reciprocal.isDenormal())
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003630 return false;
3631
Michael Gottesman8136c382013-06-26 23:17:28 +00003632 assert(reciprocal.isFiniteNonZero() &&
Benjamin Krameraf0ed952011-03-30 17:02:54 +00003633 reciprocal.significandLSB() == reciprocal.semantics->precision - 1);
3634
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003635 if (inv)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003636 *inv = APFloat(reciprocal, *semantics);
Benjamin Kramer03fd6722011-03-30 15:42:27 +00003637
3638 return true;
3639}
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003640
Tim Shen85de51d2016-10-25 19:55:59 +00003641bool IEEEFloat::isSignaling() const {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003642 if (!isNaN())
3643 return false;
3644
3645 // IEEE-754R 2008 6.2.1: A signaling NaN bit string should be encoded with the
3646 // first bit of the trailing significand being 0.
3647 return !APInt::tcExtractBit(significandParts(), semantics->precision - 2);
3648}
3649
3650/// IEEE-754R 2008 5.3.1: nextUp/nextDown.
3651///
3652/// *NOTE* since nextDown(x) = -nextUp(-x), we only implement nextUp with
3653/// appropriate sign switching before/after the computation.
Tim Shen85de51d2016-10-25 19:55:59 +00003654IEEEFloat::opStatus IEEEFloat::next(bool nextDown) {
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003655 // If we are performing nextDown, swap sign so we have -x.
3656 if (nextDown)
3657 changeSign();
3658
3659 // Compute nextUp(x)
3660 opStatus result = opOK;
3661
3662 // Handle each float category separately.
3663 switch (category) {
3664 case fcInfinity:
3665 // nextUp(+inf) = +inf
3666 if (!isNegative())
3667 break;
3668 // nextUp(-inf) = -getLargest()
3669 makeLargest(true);
3670 break;
3671 case fcNaN:
3672 // IEEE-754R 2008 6.2 Par 2: nextUp(sNaN) = qNaN. Set Invalid flag.
3673 // IEEE-754R 2008 6.2: nextUp(qNaN) = qNaN. Must be identity so we do not
3674 // change the payload.
3675 if (isSignaling()) {
3676 result = opInvalidOp;
Alp Tokercb402912014-01-24 17:20:08 +00003677 // For consistency, propagate the sign of the sNaN to the qNaN.
Craig Topperc10719f2014-04-07 04:17:22 +00003678 makeNaN(false, isNegative(), nullptr);
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003679 }
3680 break;
3681 case fcZero:
3682 // nextUp(pm 0) = +getSmallest()
3683 makeSmallest(false);
3684 break;
3685 case fcNormal:
3686 // nextUp(-getSmallest()) = -0
3687 if (isSmallest() && isNegative()) {
3688 APInt::tcSet(significandParts(), 0, partCount());
3689 category = fcZero;
3690 exponent = 0;
3691 break;
3692 }
3693
3694 // nextUp(getLargest()) == INFINITY
3695 if (isLargest() && !isNegative()) {
3696 APInt::tcSet(significandParts(), 0, partCount());
3697 category = fcInfinity;
3698 exponent = semantics->maxExponent + 1;
3699 break;
3700 }
3701
3702 // nextUp(normal) == normal + inc.
3703 if (isNegative()) {
3704 // If we are negative, we need to decrement the significand.
3705
3706 // We only cross a binade boundary that requires adjusting the exponent
3707 // if:
3708 // 1. exponent != semantics->minExponent. This implies we are not in the
3709 // smallest binade or are dealing with denormals.
3710 // 2. Our significand excluding the integral bit is all zeros.
3711 bool WillCrossBinadeBoundary =
3712 exponent != semantics->minExponent && isSignificandAllZeros();
3713
3714 // Decrement the significand.
3715 //
3716 // We always do this since:
Alp Tokerf907b892013-12-05 05:44:44 +00003717 // 1. If we are dealing with a non-binade decrement, by definition we
Michael Gottesman0c622ea2013-05-30 18:07:13 +00003718 // just decrement the significand.
3719 // 2. If we are dealing with a normal -> normal binade decrement, since
3720 // we have an explicit integral bit the fact that all bits but the
3721 // integral bit are zero implies that subtracting one will yield a
3722 // significand with 0 integral bit and 1 in all other spots. Thus we
3723 // must just adjust the exponent and set the integral bit to 1.
3724 // 3. If we are dealing with a normal -> denormal binade decrement,
3725 // since we set the integral bit to 0 when we represent denormals, we
3726 // just decrement the significand.
3727 integerPart *Parts = significandParts();
3728 APInt::tcDecrement(Parts, partCount());
3729
3730 if (WillCrossBinadeBoundary) {
3731 // Our result is a normal number. Do the following:
3732 // 1. Set the integral bit to 1.
3733 // 2. Decrement the exponent.
3734 APInt::tcSetBit(Parts, semantics->precision - 1);
3735 exponent--;
3736 }
3737 } else {
3738 // If we are positive, we need to increment the significand.
3739
3740 // We only cross a binade boundary that requires adjusting the exponent if
3741 // the input is not a denormal and all of said input's significand bits
3742 // are set. If all of said conditions are true: clear the significand, set
3743 // the integral bit to 1, and increment the exponent. If we have a
3744 // denormal always increment since moving denormals and the numbers in the
3745 // smallest normal binade have the same exponent in our representation.
3746 bool WillCrossBinadeBoundary = !isDenormal() && isSignificandAllOnes();
3747
3748 if (WillCrossBinadeBoundary) {
3749 integerPart *Parts = significandParts();
3750 APInt::tcSet(Parts, 0, partCount());
3751 APInt::tcSetBit(Parts, semantics->precision - 1);
3752 assert(exponent != semantics->maxExponent &&
3753 "We can not increment an exponent beyond the maxExponent allowed"
3754 " by the given floating point semantics.");
3755 exponent++;
3756 } else {
3757 incrementSignificand();
3758 }
3759 }
3760 break;
3761 }
3762
3763 // If we are performing nextDown, swap sign so we have -nextUp(-x)
3764 if (nextDown)
3765 changeSign();
3766
3767 return result;
3768}
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003769
Tim Shen85de51d2016-10-25 19:55:59 +00003770void IEEEFloat::makeInf(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003771 category = fcInfinity;
3772 sign = Negative;
3773 exponent = semantics->maxExponent + 1;
3774 APInt::tcSet(significandParts(), 0, partCount());
3775}
3776
Tim Shen85de51d2016-10-25 19:55:59 +00003777void IEEEFloat::makeZero(bool Negative) {
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003778 category = fcZero;
3779 sign = Negative;
3780 exponent = semantics->minExponent-1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003781 APInt::tcSet(significandParts(), 0, partCount());
3782}
3783
Tim Shen85de51d2016-10-25 19:55:59 +00003784void IEEEFloat::makeQuiet() {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003785 assert(isNaN());
3786 APInt::tcSetBit(significandParts(), semantics->precision - 2);
Michael Gottesmanc4facdf2013-06-24 09:58:02 +00003787}
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003788
Tim Shen85de51d2016-10-25 19:55:59 +00003789int ilogb(const IEEEFloat &Arg) {
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003790 if (Arg.isNaN())
Tim Shen85de51d2016-10-25 19:55:59 +00003791 return IEEEFloat::IEK_NaN;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003792 if (Arg.isZero())
Tim Shen85de51d2016-10-25 19:55:59 +00003793 return IEEEFloat::IEK_Zero;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003794 if (Arg.isInfinity())
Tim Shen85de51d2016-10-25 19:55:59 +00003795 return IEEEFloat::IEK_Inf;
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003796 if (!Arg.isDenormal())
3797 return Arg.exponent;
3798
Tim Shen85de51d2016-10-25 19:55:59 +00003799 IEEEFloat Normalized(Arg);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003800 int SignificandBits = Arg.getSemantics().precision - 1;
3801
3802 Normalized.exponent += SignificandBits;
Tim Shen85de51d2016-10-25 19:55:59 +00003803 Normalized.normalize(IEEEFloat::rmNearestTiesToEven, lfExactlyZero);
Matt Arsenault69fdf9b2016-03-13 05:12:32 +00003804 return Normalized.exponent - SignificandBits;
3805}
3806
Tim Shen85de51d2016-10-25 19:55:59 +00003807IEEEFloat scalbn(IEEEFloat X, int Exp, IEEEFloat::roundingMode RoundingMode) {
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003808 auto MaxExp = X.getSemantics().maxExponent;
3809 auto MinExp = X.getSemantics().minExponent;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003810
Matt Arsenaultafa31cf2016-03-13 05:11:51 +00003811 // If Exp is wildly out-of-scale, simply adding it to X.exponent will
3812 // overflow; clamp it to a safe range before adding, but ensure that the range
3813 // is large enough that the clamp does not change the result. The range we
3814 // need to support is the difference between the largest possible exponent and
3815 // the normalized exponent of half the smallest denormal.
3816
3817 int SignificandBits = X.getSemantics().precision - 1;
3818 int MaxIncrement = MaxExp - (MinExp - SignificandBits) + 1;
3819
3820 // Clamp to one past the range ends to let normalize handle overlflow.
3821 X.exponent += std::min(std::max(Exp, -MaxIncrement - 1), MaxIncrement);
3822 X.normalize(RoundingMode, lfExactlyZero);
Matt Arsenaultea00b492016-03-23 23:51:45 +00003823 if (X.isNaN())
3824 X.makeQuiet();
Richard Trieu6ae37962015-04-30 23:07:00 +00003825 return X;
Chandler Carruthd9edd1e2014-10-10 04:54:30 +00003826}
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003827
Tim Shen85de51d2016-10-25 19:55:59 +00003828IEEEFloat frexp(const IEEEFloat &Val, int &Exp, IEEEFloat::roundingMode RM) {
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003829 Exp = ilogb(Val);
3830
3831 // Quiet signalling nans.
Tim Shen85de51d2016-10-25 19:55:59 +00003832 if (Exp == IEEEFloat::IEK_NaN) {
3833 IEEEFloat Quiet(Val);
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003834 Quiet.makeQuiet();
3835 return Quiet;
3836 }
3837
Tim Shen85de51d2016-10-25 19:55:59 +00003838 if (Exp == IEEEFloat::IEK_Inf)
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003839 return Val;
3840
3841 // 1 is added because frexp is defined to return a normalized fraction in
3842 // +/-[0.5, 1.0), rather than the usual +/-[1.0, 2.0).
Tim Shen85de51d2016-10-25 19:55:59 +00003843 Exp = Exp == IEEEFloat::IEK_Zero ? 0 : Exp + 1;
Matt Arsenaultc25a7112016-03-21 16:49:16 +00003844 return scalbn(Val, -Exp, RM);
3845}
Tim Shen85de51d2016-10-25 19:55:59 +00003846
Tim Shen139a58f2016-10-27 22:52:40 +00003847DoubleAPFloat::DoubleAPFloat(const fltSemantics &S)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003848 : Semantics(&S),
3849 Floats(new APFloat[2]{APFloat(semIEEEdouble), APFloat(semIEEEdouble)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003850 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003851}
3852
3853DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, uninitializedTag)
3854 : Semantics(&S),
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003855 Floats(new APFloat[2]{APFloat(semIEEEdouble, uninitialized),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003856 APFloat(semIEEEdouble, uninitialized)}) {
3857 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003858}
3859
3860DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, integerPart I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003861 : Semantics(&S), Floats(new APFloat[2]{APFloat(semIEEEdouble, I),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003862 APFloat(semIEEEdouble)}) {
3863 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003864}
3865
3866DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, const APInt &I)
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003867 : Semantics(&S),
3868 Floats(new APFloat[2]{
3869 APFloat(semIEEEdouble, APInt(64, I.getRawData()[0])),
3870 APFloat(semIEEEdouble, APInt(64, I.getRawData()[1]))}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003871 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003872}
3873
3874DoubleAPFloat::DoubleAPFloat(const fltSemantics &S, APFloat &&First,
3875 APFloat &&Second)
3876 : Semantics(&S),
3877 Floats(new APFloat[2]{std::move(First), std::move(Second)}) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003878 assert(Semantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00003879 assert(&Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003880 assert(&Floats[1].getSemantics() == &semIEEEdouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003881}
3882
3883DoubleAPFloat::DoubleAPFloat(const DoubleAPFloat &RHS)
3884 : Semantics(RHS.Semantics),
Tim Shenb49915482016-10-28 22:45:33 +00003885 Floats(RHS.Floats ? new APFloat[2]{APFloat(RHS.Floats[0]),
3886 APFloat(RHS.Floats[1])}
3887 : nullptr) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003888 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003889}
3890
3891DoubleAPFloat::DoubleAPFloat(DoubleAPFloat &&RHS)
3892 : Semantics(RHS.Semantics), Floats(std::move(RHS.Floats)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00003893 RHS.Semantics = &semBogus;
3894 assert(Semantics == &semPPCDoubleDouble);
Tim Shen139a58f2016-10-27 22:52:40 +00003895}
3896
3897DoubleAPFloat &DoubleAPFloat::operator=(const DoubleAPFloat &RHS) {
Tim Shenb49915482016-10-28 22:45:33 +00003898 if (Semantics == RHS.Semantics && RHS.Floats) {
Tim Shen139a58f2016-10-27 22:52:40 +00003899 Floats[0] = RHS.Floats[0];
3900 Floats[1] = RHS.Floats[1];
3901 } else if (this != &RHS) {
3902 this->~DoubleAPFloat();
3903 new (this) DoubleAPFloat(RHS);
3904 }
3905 return *this;
3906}
3907
Tim Shen7f127622017-01-24 00:19:45 +00003908// Implement addition, subtraction, multiplication and division based on:
Tim Shen44bde892016-12-12 21:59:30 +00003909// "Software for Doubled-Precision Floating-Point Computations",
3910// by Seppo Linnainmaa, ACM TOMS vol 7 no 3, September 1981, pages 272-283.
3911APFloat::opStatus DoubleAPFloat::addImpl(const APFloat &a, const APFloat &aa,
3912 const APFloat &c, const APFloat &cc,
3913 roundingMode RM) {
3914 int Status = opOK;
3915 APFloat z = a;
3916 Status |= z.add(c, RM);
3917 if (!z.isFinite()) {
3918 if (!z.isInfinity()) {
3919 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003920 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003921 return (opStatus)Status;
3922 }
3923 Status = opOK;
3924 auto AComparedToC = a.compareAbsoluteValue(c);
3925 z = cc;
3926 Status |= z.add(aa, RM);
3927 if (AComparedToC == APFloat::cmpGreaterThan) {
3928 // z = cc + aa + c + a;
3929 Status |= z.add(c, RM);
3930 Status |= z.add(a, RM);
3931 } else {
3932 // z = cc + aa + a + c;
3933 Status |= z.add(a, RM);
3934 Status |= z.add(c, RM);
3935 }
3936 if (!z.isFinite()) {
3937 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003938 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003939 return (opStatus)Status;
3940 }
3941 Floats[0] = z;
3942 APFloat zz = aa;
3943 Status |= zz.add(cc, RM);
3944 if (AComparedToC == APFloat::cmpGreaterThan) {
3945 // Floats[1] = a - z + c + zz;
3946 Floats[1] = a;
3947 Status |= Floats[1].subtract(z, RM);
3948 Status |= Floats[1].add(c, RM);
3949 Status |= Floats[1].add(zz, RM);
3950 } else {
3951 // Floats[1] = c - z + a + zz;
3952 Floats[1] = c;
3953 Status |= Floats[1].subtract(z, RM);
3954 Status |= Floats[1].add(a, RM);
3955 Status |= Floats[1].add(zz, RM);
3956 }
3957 } else {
3958 // q = a - z;
3959 APFloat q = a;
3960 Status |= q.subtract(z, RM);
3961
3962 // zz = q + c + (a - (q + z)) + aa + cc;
3963 // Compute a - (q + z) as -((q + z) - a) to avoid temporary copies.
3964 auto zz = q;
3965 Status |= zz.add(c, RM);
3966 Status |= q.add(z, RM);
3967 Status |= q.subtract(a, RM);
3968 q.changeSign();
3969 Status |= zz.add(q, RM);
3970 Status |= zz.add(aa, RM);
3971 Status |= zz.add(cc, RM);
3972 if (zz.isZero() && !zz.isNegative()) {
3973 Floats[0] = std::move(z);
Tim Shen7117e692017-01-26 00:11:07 +00003974 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003975 return opOK;
3976 }
3977 Floats[0] = z;
3978 Status |= Floats[0].add(zz, RM);
3979 if (!Floats[0].isFinite()) {
Tim Shen7117e692017-01-26 00:11:07 +00003980 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00003981 return (opStatus)Status;
3982 }
3983 Floats[1] = std::move(z);
3984 Status |= Floats[1].subtract(Floats[0], RM);
3985 Status |= Floats[1].add(zz, RM);
3986 }
3987 return (opStatus)Status;
3988}
3989
3990APFloat::opStatus DoubleAPFloat::addWithSpecial(const DoubleAPFloat &LHS,
3991 const DoubleAPFloat &RHS,
3992 DoubleAPFloat &Out,
3993 roundingMode RM) {
3994 if (LHS.getCategory() == fcNaN) {
3995 Out = LHS;
3996 return opOK;
3997 }
3998 if (RHS.getCategory() == fcNaN) {
3999 Out = RHS;
4000 return opOK;
4001 }
4002 if (LHS.getCategory() == fcZero) {
4003 Out = RHS;
4004 return opOK;
4005 }
4006 if (RHS.getCategory() == fcZero) {
4007 Out = LHS;
4008 return opOK;
4009 }
4010 if (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcInfinity &&
4011 LHS.isNegative() != RHS.isNegative()) {
4012 Out.makeNaN(false, Out.isNegative(), nullptr);
4013 return opInvalidOp;
4014 }
4015 if (LHS.getCategory() == fcInfinity) {
4016 Out = LHS;
4017 return opOK;
4018 }
4019 if (RHS.getCategory() == fcInfinity) {
4020 Out = RHS;
4021 return opOK;
4022 }
4023 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal);
4024
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004025 APFloat A(LHS.Floats[0]), AA(LHS.Floats[1]), C(RHS.Floats[0]),
Tim Shen44bde892016-12-12 21:59:30 +00004026 CC(RHS.Floats[1]);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004027 assert(&A.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004028 assert(&AA.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004029 assert(&C.getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004030 assert(&CC.getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004031 assert(&Out.Floats[0].getSemantics() == &semIEEEdouble);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004032 assert(&Out.Floats[1].getSemantics() == &semIEEEdouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004033 return Out.addImpl(A, AA, C, CC, RM);
Tim Shen44bde892016-12-12 21:59:30 +00004034}
4035
4036APFloat::opStatus DoubleAPFloat::add(const DoubleAPFloat &RHS,
4037 roundingMode RM) {
4038 return addWithSpecial(*this, RHS, *this, RM);
4039}
4040
4041APFloat::opStatus DoubleAPFloat::subtract(const DoubleAPFloat &RHS,
4042 roundingMode RM) {
4043 changeSign();
4044 auto Ret = add(RHS, RM);
4045 changeSign();
4046 return Ret;
4047}
4048
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004049APFloat::opStatus DoubleAPFloat::multiply(const DoubleAPFloat &RHS,
4050 APFloat::roundingMode RM) {
Tim Shen7f127622017-01-24 00:19:45 +00004051 const auto &LHS = *this;
4052 auto &Out = *this;
4053 /* Interesting observation: For special categories, finding the lowest
4054 common ancestor of the following layered graph gives the correct
4055 return category:
4056
4057 NaN
4058 / \
4059 Zero Inf
4060 \ /
4061 Normal
4062
4063 e.g. NaN * NaN = NaN
4064 Zero * Inf = NaN
4065 Normal * Zero = Zero
4066 Normal * Inf = Inf
4067 */
4068 if (LHS.getCategory() == fcNaN) {
4069 Out = LHS;
4070 return opOK;
4071 }
4072 if (RHS.getCategory() == fcNaN) {
4073 Out = RHS;
4074 return opOK;
4075 }
4076 if ((LHS.getCategory() == fcZero && RHS.getCategory() == fcInfinity) ||
4077 (LHS.getCategory() == fcInfinity && RHS.getCategory() == fcZero)) {
4078 Out.makeNaN(false, false, nullptr);
4079 return opOK;
4080 }
4081 if (LHS.getCategory() == fcZero || LHS.getCategory() == fcInfinity) {
4082 Out = LHS;
4083 return opOK;
4084 }
4085 if (RHS.getCategory() == fcZero || RHS.getCategory() == fcInfinity) {
4086 Out = RHS;
4087 return opOK;
4088 }
4089 assert(LHS.getCategory() == fcNormal && RHS.getCategory() == fcNormal &&
4090 "Special cases not handled exhaustively");
4091
4092 int Status = opOK;
4093 APFloat A = Floats[0], B = Floats[1], C = RHS.Floats[0], D = RHS.Floats[1];
4094 // t = a * c
4095 APFloat T = A;
4096 Status |= T.multiply(C, RM);
4097 if (!T.isFiniteNonZero()) {
4098 Floats[0] = T;
Tim Shen7117e692017-01-26 00:11:07 +00004099 Floats[1].makeZero(/* Neg = */ false);
Tim Shen7f127622017-01-24 00:19:45 +00004100 return (opStatus)Status;
4101 }
4102
4103 // tau = fmsub(a, c, t), that is -fmadd(-a, c, t).
4104 APFloat Tau = A;
4105 T.changeSign();
4106 Status |= Tau.fusedMultiplyAdd(C, T, RM);
4107 T.changeSign();
4108 {
4109 // v = a * d
4110 APFloat V = A;
4111 Status |= V.multiply(D, RM);
4112 // w = b * c
4113 APFloat W = B;
4114 Status |= W.multiply(C, RM);
4115 Status |= V.add(W, RM);
4116 // tau += v + w
4117 Status |= Tau.add(V, RM);
4118 }
4119 // u = t + tau
4120 APFloat U = T;
4121 Status |= U.add(Tau, RM);
4122
4123 Floats[0] = U;
4124 if (!U.isFinite()) {
Tim Shen7117e692017-01-26 00:11:07 +00004125 Floats[1].makeZero(/* Neg = */ false);
Tim Shen7f127622017-01-24 00:19:45 +00004126 } else {
4127 // Floats[1] = (t - u) + tau
4128 Status |= T.subtract(U, RM);
4129 Status |= T.add(Tau, RM);
4130 Floats[1] = T;
4131 }
4132 return (opStatus)Status;
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004133}
4134
4135APFloat::opStatus DoubleAPFloat::divide(const DoubleAPFloat &RHS,
4136 APFloat::roundingMode RM) {
4137 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4138 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4139 auto Ret =
4140 Tmp.divide(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()), RM);
4141 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4142 return Ret;
4143}
4144
4145APFloat::opStatus DoubleAPFloat::remainder(const DoubleAPFloat &RHS) {
4146 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4147 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4148 auto Ret =
4149 Tmp.remainder(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4150 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4151 return Ret;
4152}
4153
4154APFloat::opStatus DoubleAPFloat::mod(const DoubleAPFloat &RHS) {
4155 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4156 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4157 auto Ret = Tmp.mod(APFloat(semPPCDoubleDoubleLegacy, RHS.bitcastToAPInt()));
4158 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4159 return Ret;
4160}
4161
4162APFloat::opStatus
4163DoubleAPFloat::fusedMultiplyAdd(const DoubleAPFloat &Multiplicand,
4164 const DoubleAPFloat &Addend,
4165 APFloat::roundingMode RM) {
4166 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4167 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4168 auto Ret = Tmp.fusedMultiplyAdd(
4169 APFloat(semPPCDoubleDoubleLegacy, Multiplicand.bitcastToAPInt()),
4170 APFloat(semPPCDoubleDoubleLegacy, Addend.bitcastToAPInt()), RM);
4171 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4172 return Ret;
4173}
4174
4175APFloat::opStatus DoubleAPFloat::roundToIntegral(APFloat::roundingMode RM) {
4176 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4177 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4178 auto Ret = Tmp.roundToIntegral(RM);
4179 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4180 return Ret;
4181}
4182
Tim Shen44bde892016-12-12 21:59:30 +00004183void DoubleAPFloat::changeSign() {
4184 Floats[0].changeSign();
4185 Floats[1].changeSign();
4186}
4187
4188APFloat::cmpResult
4189DoubleAPFloat::compareAbsoluteValue(const DoubleAPFloat &RHS) const {
4190 auto Result = Floats[0].compareAbsoluteValue(RHS.Floats[0]);
4191 if (Result != cmpEqual)
4192 return Result;
4193 Result = Floats[1].compareAbsoluteValue(RHS.Floats[1]);
4194 if (Result == cmpLessThan || Result == cmpGreaterThan) {
4195 auto Against = Floats[0].isNegative() ^ Floats[1].isNegative();
4196 auto RHSAgainst = RHS.Floats[0].isNegative() ^ RHS.Floats[1].isNegative();
4197 if (Against && !RHSAgainst)
4198 return cmpLessThan;
4199 if (!Against && RHSAgainst)
4200 return cmpGreaterThan;
4201 if (!Against && !RHSAgainst)
4202 return Result;
4203 if (Against && RHSAgainst)
4204 return (cmpResult)(cmpLessThan + cmpGreaterThan - Result);
4205 }
4206 return Result;
4207}
4208
4209APFloat::fltCategory DoubleAPFloat::getCategory() const {
4210 return Floats[0].getCategory();
4211}
4212
4213bool DoubleAPFloat::isNegative() const { return Floats[0].isNegative(); }
4214
4215void DoubleAPFloat::makeInf(bool Neg) {
4216 Floats[0].makeInf(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004217 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004218}
4219
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004220void DoubleAPFloat::makeZero(bool Neg) {
4221 Floats[0].makeZero(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004222 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004223}
4224
4225void DoubleAPFloat::makeLargest(bool Neg) {
4226 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4227 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x7fefffffffffffffull));
4228 Floats[1] = APFloat(semIEEEdouble, APInt(64, 0x7c8ffffffffffffeull));
4229 if (Neg)
4230 changeSign();
4231}
4232
4233void DoubleAPFloat::makeSmallest(bool Neg) {
4234 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4235 Floats[0].makeSmallest(Neg);
Tim Shen7117e692017-01-26 00:11:07 +00004236 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004237}
4238
4239void DoubleAPFloat::makeSmallestNormalized(bool Neg) {
4240 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4241 Floats[0] = APFloat(semIEEEdouble, APInt(64, 0x0360000000000000ull));
4242 if (Neg)
4243 Floats[0].changeSign();
Tim Shen7117e692017-01-26 00:11:07 +00004244 Floats[1].makeZero(/* Neg = */ false);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004245}
4246
Tim Shen44bde892016-12-12 21:59:30 +00004247void DoubleAPFloat::makeNaN(bool SNaN, bool Neg, const APInt *fill) {
4248 Floats[0].makeNaN(SNaN, Neg, fill);
Tim Shen7117e692017-01-26 00:11:07 +00004249 Floats[1].makeZero(/* Neg = */ false);
Tim Shen44bde892016-12-12 21:59:30 +00004250}
4251
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004252APFloat::cmpResult DoubleAPFloat::compare(const DoubleAPFloat &RHS) const {
4253 auto Result = Floats[0].compare(RHS.Floats[0]);
Tim Shen7117e692017-01-26 00:11:07 +00004254 // |Float[0]| > |Float[1]|
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004255 if (Result == APFloat::cmpEqual)
4256 return Floats[1].compare(RHS.Floats[1]);
4257 return Result;
4258}
4259
4260bool DoubleAPFloat::bitwiseIsEqual(const DoubleAPFloat &RHS) const {
4261 return Floats[0].bitwiseIsEqual(RHS.Floats[0]) &&
4262 Floats[1].bitwiseIsEqual(RHS.Floats[1]);
4263}
4264
4265hash_code hash_value(const DoubleAPFloat &Arg) {
4266 if (Arg.Floats)
4267 return hash_combine(hash_value(Arg.Floats[0]), hash_value(Arg.Floats[1]));
4268 return hash_combine(Arg.Semantics);
4269}
4270
4271APInt DoubleAPFloat::bitcastToAPInt() const {
4272 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4273 uint64_t Data[] = {
4274 Floats[0].bitcastToAPInt().getRawData()[0],
4275 Floats[1].bitcastToAPInt().getRawData()[0],
4276 };
4277 return APInt(128, 2, Data);
4278}
4279
4280APFloat::opStatus DoubleAPFloat::convertFromString(StringRef S,
4281 roundingMode RM) {
4282 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4283 APFloat Tmp(semPPCDoubleDoubleLegacy);
4284 auto Ret = Tmp.convertFromString(S, RM);
4285 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4286 return Ret;
4287}
4288
4289APFloat::opStatus DoubleAPFloat::next(bool nextDown) {
4290 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4291 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4292 auto Ret = Tmp.next(nextDown);
4293 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4294 return Ret;
4295}
4296
Simon Pilgrim00b34992017-03-20 14:40:12 +00004297APFloat::opStatus
4298DoubleAPFloat::convertToInteger(MutableArrayRef<integerPart> Input,
4299 unsigned int Width, bool IsSigned,
4300 roundingMode RM, bool *IsExact) const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004301 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4302 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4303 .convertToInteger(Input, Width, IsSigned, RM, IsExact);
4304}
4305
4306APFloat::opStatus DoubleAPFloat::convertFromAPInt(const APInt &Input,
4307 bool IsSigned,
4308 roundingMode RM) {
4309 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4310 APFloat Tmp(semPPCDoubleDoubleLegacy);
4311 auto Ret = Tmp.convertFromAPInt(Input, IsSigned, RM);
4312 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4313 return Ret;
4314}
4315
4316APFloat::opStatus
4317DoubleAPFloat::convertFromSignExtendedInteger(const integerPart *Input,
4318 unsigned int InputSize,
4319 bool IsSigned, roundingMode RM) {
4320 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4321 APFloat Tmp(semPPCDoubleDoubleLegacy);
4322 auto Ret = Tmp.convertFromSignExtendedInteger(Input, InputSize, IsSigned, RM);
4323 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4324 return Ret;
4325}
4326
4327APFloat::opStatus
4328DoubleAPFloat::convertFromZeroExtendedInteger(const integerPart *Input,
4329 unsigned int InputSize,
4330 bool IsSigned, roundingMode RM) {
4331 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4332 APFloat Tmp(semPPCDoubleDoubleLegacy);
4333 auto Ret = Tmp.convertFromZeroExtendedInteger(Input, InputSize, IsSigned, RM);
4334 *this = DoubleAPFloat(semPPCDoubleDouble, Tmp.bitcastToAPInt());
4335 return Ret;
4336}
4337
4338unsigned int DoubleAPFloat::convertToHexString(char *DST,
4339 unsigned int HexDigits,
4340 bool UpperCase,
4341 roundingMode RM) const {
4342 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4343 return APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
4344 .convertToHexString(DST, HexDigits, UpperCase, RM);
4345}
4346
4347bool DoubleAPFloat::isDenormal() const {
4348 return getCategory() == fcNormal &&
4349 (Floats[0].isDenormal() || Floats[1].isDenormal() ||
Tim Shen7117e692017-01-26 00:11:07 +00004350 // (double)(Hi + Lo) == Hi defines a normal number.
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004351 Floats[0].compare(Floats[0] + Floats[1]) != cmpEqual);
4352}
4353
4354bool DoubleAPFloat::isSmallest() const {
4355 if (getCategory() != fcNormal)
4356 return false;
4357 DoubleAPFloat Tmp(*this);
4358 Tmp.makeSmallest(this->isNegative());
4359 return Tmp.compare(*this) == cmpEqual;
4360}
4361
4362bool DoubleAPFloat::isLargest() const {
4363 if (getCategory() != fcNormal)
4364 return false;
4365 DoubleAPFloat Tmp(*this);
4366 Tmp.makeLargest(this->isNegative());
4367 return Tmp.compare(*this) == cmpEqual;
4368}
4369
4370bool DoubleAPFloat::isInteger() const {
4371 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
Davide Italiano5a2530d2017-08-21 16:51:54 +00004372 return Floats[0].isInteger() && Floats[1].isInteger();
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004373}
4374
4375void DoubleAPFloat::toString(SmallVectorImpl<char> &Str,
4376 unsigned FormatPrecision,
Serguei Katkov3a46eb42017-04-21 02:52:17 +00004377 unsigned FormatMaxPadding,
4378 bool TruncateZero) const {
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004379 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4380 APFloat(semPPCDoubleDoubleLegacy, bitcastToAPInt())
Serguei Katkov3a46eb42017-04-21 02:52:17 +00004381 .toString(Str, FormatPrecision, FormatMaxPadding, TruncateZero);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004382}
4383
4384bool DoubleAPFloat::getExactInverse(APFloat *inv) const {
4385 assert(Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4386 APFloat Tmp(semPPCDoubleDoubleLegacy, bitcastToAPInt());
4387 if (!inv)
4388 return Tmp.getExactInverse(nullptr);
4389 APFloat Inv(semPPCDoubleDoubleLegacy);
4390 auto Ret = Tmp.getExactInverse(&Inv);
4391 *inv = APFloat(semPPCDoubleDouble, Inv.bitcastToAPInt());
4392 return Ret;
4393}
4394
4395DoubleAPFloat scalbn(DoubleAPFloat Arg, int Exp, APFloat::roundingMode RM) {
4396 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4397 return DoubleAPFloat(semPPCDoubleDouble, scalbn(Arg.Floats[0], Exp, RM),
4398 scalbn(Arg.Floats[1], Exp, RM));
4399}
4400
4401DoubleAPFloat frexp(const DoubleAPFloat &Arg, int &Exp,
4402 APFloat::roundingMode RM) {
4403 assert(Arg.Semantics == &semPPCDoubleDouble && "Unexpected Semantics");
4404 APFloat First = frexp(Arg.Floats[0], Exp, RM);
4405 APFloat Second = Arg.Floats[1];
4406 if (Arg.getCategory() == APFloat::fcNormal)
4407 Second = scalbn(Second, -Exp, RM);
4408 return DoubleAPFloat(semPPCDoubleDouble, std::move(First), std::move(Second));
4409}
4410
Tim Shen85de51d2016-10-25 19:55:59 +00004411} // End detail namespace
4412
Tim Shen398f90f2016-11-06 07:38:37 +00004413APFloat::Storage::Storage(IEEEFloat F, const fltSemantics &Semantics) {
4414 if (usesLayout<IEEEFloat>(Semantics)) {
4415 new (&IEEE) IEEEFloat(std::move(F));
Tim Shen7b57ac42016-12-21 02:39:21 +00004416 return;
4417 }
4418 if (usesLayout<DoubleAPFloat>(Semantics)) {
Tim Shen398f90f2016-11-06 07:38:37 +00004419 new (&Double)
4420 DoubleAPFloat(Semantics, APFloat(std::move(F), F.getSemantics()),
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004421 APFloat(semIEEEdouble));
Tim Shen7b57ac42016-12-21 02:39:21 +00004422 return;
Tim Shen398f90f2016-11-06 07:38:37 +00004423 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004424 llvm_unreachable("Unexpected semantics");
Tim Shen398f90f2016-11-06 07:38:37 +00004425}
4426
Tim Shen85de51d2016-10-25 19:55:59 +00004427APFloat::opStatus APFloat::convertFromString(StringRef Str, roundingMode RM) {
Tim Shen601ba8c2017-01-27 02:11:07 +00004428 APFLOAT_DISPATCH_ON_SEMANTICS(convertFromString(Str, RM));
Tim Shen85de51d2016-10-25 19:55:59 +00004429}
4430
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004431hash_code hash_value(const APFloat &Arg) {
4432 if (APFloat::usesLayout<detail::IEEEFloat>(Arg.getSemantics()))
4433 return hash_value(Arg.U.IEEE);
4434 if (APFloat::usesLayout<detail::DoubleAPFloat>(Arg.getSemantics()))
4435 return hash_value(Arg.U.Double);
4436 llvm_unreachable("Unexpected semantics");
4437}
Tim Shen85de51d2016-10-25 19:55:59 +00004438
4439APFloat::APFloat(const fltSemantics &Semantics, StringRef S)
Tim Shen139a58f2016-10-27 22:52:40 +00004440 : APFloat(Semantics) {
4441 convertFromString(S, rmNearestTiesToEven);
4442}
4443
4444APFloat::opStatus APFloat::convert(const fltSemantics &ToSemantics,
4445 roundingMode RM, bool *losesInfo) {
Sven van Haastregt5ad5c3c2018-05-11 09:45:42 +00004446 if (&getSemantics() == &ToSemantics) {
4447 *losesInfo = false;
Tim Shen139a58f2016-10-27 22:52:40 +00004448 return opOK;
Sven van Haastregt5ad5c3c2018-05-11 09:45:42 +00004449 }
Tim Shen139a58f2016-10-27 22:52:40 +00004450 if (usesLayout<IEEEFloat>(getSemantics()) &&
Tim Shen7b57ac42016-12-21 02:39:21 +00004451 usesLayout<IEEEFloat>(ToSemantics))
Tim Shen139a58f2016-10-27 22:52:40 +00004452 return U.IEEE.convert(ToSemantics, RM, losesInfo);
Tim Shen7b57ac42016-12-21 02:39:21 +00004453 if (usesLayout<IEEEFloat>(getSemantics()) &&
4454 usesLayout<DoubleAPFloat>(ToSemantics)) {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004455 assert(&ToSemantics == &semPPCDoubleDouble);
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004456 auto Ret = U.IEEE.convert(semPPCDoubleDoubleLegacy, RM, losesInfo);
4457 *this = APFloat(ToSemantics, U.IEEE.bitcastToAPInt());
Tim Shen139a58f2016-10-27 22:52:40 +00004458 return Ret;
Tim Shen7b57ac42016-12-21 02:39:21 +00004459 }
4460 if (usesLayout<DoubleAPFloat>(getSemantics()) &&
4461 usesLayout<IEEEFloat>(ToSemantics)) {
Tim Shen139a58f2016-10-27 22:52:40 +00004462 auto Ret = getIEEE().convert(ToSemantics, RM, losesInfo);
Tim Shen398f90f2016-11-06 07:38:37 +00004463 *this = APFloat(std::move(getIEEE()), ToSemantics);
Tim Shen139a58f2016-10-27 22:52:40 +00004464 return Ret;
Tim Shen139a58f2016-10-27 22:52:40 +00004465 }
Tim Shen7b57ac42016-12-21 02:39:21 +00004466 llvm_unreachable("Unexpected semantics");
Tim Shen139a58f2016-10-27 22:52:40 +00004467}
Tim Shen85de51d2016-10-25 19:55:59 +00004468
Tim Shen398f90f2016-11-06 07:38:37 +00004469APFloat APFloat::getAllOnesValue(unsigned BitWidth, bool isIEEE) {
4470 if (isIEEE) {
4471 switch (BitWidth) {
4472 case 16:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004473 return APFloat(semIEEEhalf, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004474 case 32:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004475 return APFloat(semIEEEsingle, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004476 case 64:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004477 return APFloat(semIEEEdouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004478 case 80:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004479 return APFloat(semX87DoubleExtended, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004480 case 128:
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004481 return APFloat(semIEEEquad, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004482 default:
4483 llvm_unreachable("Unknown floating bit width");
4484 }
4485 } else {
4486 assert(BitWidth == 128);
Stephan Bergmann17c7f702016-12-14 11:57:17 +00004487 return APFloat(semPPCDoubleDouble, APInt::getAllOnesValue(BitWidth));
Tim Shen398f90f2016-11-06 07:38:37 +00004488 }
4489}
4490
Tim Shen44bde892016-12-12 21:59:30 +00004491void APFloat::print(raw_ostream &OS) const {
4492 SmallVector<char, 16> Buffer;
4493 toString(Buffer);
4494 OS << Buffer << "\n";
4495}
4496
Aaron Ballman615eb472017-10-15 14:32:27 +00004497#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Matthias Braun8c209aa2017-01-28 02:02:38 +00004498LLVM_DUMP_METHOD void APFloat::dump() const { print(dbgs()); }
4499#endif
Tim Shen44bde892016-12-12 21:59:30 +00004500
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004501void APFloat::Profile(FoldingSetNodeID &NID) const {
4502 NID.Add(bitcastToAPInt());
4503}
4504
4505/* Same as convertToInteger(integerPart*, ...), except the result is returned in
4506 an APSInt, whose initial bit-width and signed-ness are used to determine the
4507 precision of the conversion.
4508 */
4509APFloat::opStatus APFloat::convertToInteger(APSInt &result,
4510 roundingMode rounding_mode,
4511 bool *isExact) const {
4512 unsigned bitWidth = result.getBitWidth();
4513 SmallVector<uint64_t, 4> parts(result.getNumWords());
Simon Pilgrim00b34992017-03-20 14:40:12 +00004514 opStatus status = convertToInteger(parts, bitWidth, result.isSigned(),
Tim Shenfd1e5aa2017-01-23 22:39:35 +00004515 rounding_mode, isExact);
4516 // Keeps the original signed-ness.
4517 result = APInt(bitWidth, parts);
4518 return status;
4519}
4520
Tim Shen85de51d2016-10-25 19:55:59 +00004521} // End llvm namespace
Tim Shen601ba8c2017-01-27 02:11:07 +00004522
4523#undef APFLOAT_DISPATCH_ON_SEMANTICS